hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | 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 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
83f8257e20355335b0a652a0546a470ab75f318c | 4,946 | cpp | C++ | deps/libgeos/geos/src/geom/prep/PreparedPolygonPredicate.cpp | AmristarSolutions/node-gdal-next | 8c0a7d9b26c240bf04abbf1b1de312b0691b3d88 | [
"Apache-2.0"
] | 57 | 2020-02-08T17:52:17.000Z | 2021-10-14T03:45:09.000Z | deps/libgeos/geos/src/geom/prep/PreparedPolygonPredicate.cpp | AmristarSolutions/node-gdal-next | 8c0a7d9b26c240bf04abbf1b1de312b0691b3d88 | [
"Apache-2.0"
] | 47 | 2020-02-12T16:41:40.000Z | 2021-09-28T22:27:56.000Z | deps/libgeos/geos/src/geom/prep/PreparedPolygonPredicate.cpp | AmristarSolutions/node-gdal-next | 8c0a7d9b26c240bf04abbf1b1de312b0691b3d88 | [
"Apache-2.0"
] | 8 | 2020-03-17T11:18:07.000Z | 2021-10-14T03:45:15.000Z | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: geom/prep/PreparedPolygonPredicate.java rev. 1.4 (JTS-1.10)
* (2007-12-12)
*
**********************************************************************/
#include <geos/geom/prep/PreparedPolygonPredicate.h>
#include <geos/geom/prep/PreparedPolygon.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateFilter.h>
#include <geos/geom/util/ComponentCoordinateExtracter.h>
#include <geos/geom/Location.h>
#include <geos/algorithm/locate/PointOnGeometryLocator.h>
#include <geos/algorithm/locate/SimplePointInAreaLocator.h>
// std
#include <cstddef>
namespace geos {
namespace geom { // geos.geom
namespace prep { // geos.geom.prep
//
// private:
//
//
// protected:
//
struct LocationMatchingFilter : public GeometryComponentFilter {
explicit LocationMatchingFilter(algorithm::locate::PointOnGeometryLocator* locator, Location loc) :
pt_locator(locator), test_loc(loc), found(false) {}
algorithm::locate::PointOnGeometryLocator* pt_locator;
const Location test_loc;
bool found;
void filter_ro(const Geometry* g) override {
const Coordinate* pt = g->getCoordinate();
const auto loc = pt_locator->locate(pt);
if (loc == test_loc) {
found = true;
}
}
bool isDone() override {
return found;
}
};
struct LocationNotMatchingFilter : public GeometryComponentFilter {
explicit LocationNotMatchingFilter(algorithm::locate::PointOnGeometryLocator* locator, Location loc) :
pt_locator(locator), test_loc(loc), found(false) {}
algorithm::locate::PointOnGeometryLocator* pt_locator;
const Location test_loc;
bool found;
void filter_ro(const Geometry* g) override {
const Coordinate* pt = g->getCoordinate();
const auto loc = pt_locator->locate(pt);
if (loc != test_loc) {
found = true;
}
}
bool isDone() override {
return found;
}
};
struct OutermostLocationFilter : public GeometryComponentFilter {
explicit OutermostLocationFilter(algorithm::locate::PointOnGeometryLocator* locator) :
pt_locator(locator),
outermost_loc(geom::Location::UNDEF),
done(false) {}
algorithm::locate::PointOnGeometryLocator* pt_locator;
Location outermost_loc;
bool done;
void filter_ro(const Geometry* g) override {
const Coordinate* pt = g->getCoordinate();
auto loc = pt_locator->locate(pt);
if (outermost_loc == Location::UNDEF || outermost_loc == Location::INTERIOR) {
outermost_loc = loc;
} else if (loc == Location::EXTERIOR) {
outermost_loc = loc;
done = true;
}
}
bool isDone() override {
return done;
}
Location getOutermostLocation() {
return outermost_loc;
}
};
Location
PreparedPolygonPredicate::getOutermostTestComponentLocation(const geom::Geometry* testGeom) const
{
OutermostLocationFilter filter(prepPoly->getPointLocator());
testGeom->apply_ro(&filter);
return filter.getOutermostLocation();
}
bool
PreparedPolygonPredicate::isAllTestComponentsInTargetInterior(
const geom::Geometry* testGeom) const
{
LocationNotMatchingFilter filter(prepPoly->getPointLocator(), geom::Location::INTERIOR);
testGeom->apply_ro(&filter);
return !filter.found;
}
bool
PreparedPolygonPredicate::isAnyTestComponentInTarget(
const geom::Geometry* testGeom) const
{
LocationNotMatchingFilter filter(prepPoly->getPointLocator(), geom::Location::EXTERIOR);
testGeom->apply_ro(&filter);
return filter.found;
}
bool
PreparedPolygonPredicate::isAnyTestComponentInTargetInterior(
const geom::Geometry* testGeom) const
{
LocationMatchingFilter filter(prepPoly->getPointLocator(), geom::Location::INTERIOR);
testGeom->apply_ro(&filter);
return filter.found;
}
bool
PreparedPolygonPredicate::isAnyTargetComponentInAreaTest(
const geom::Geometry* testGeom,
const geom::Coordinate::ConstVect* targetRepPts) const
{
algorithm::locate::SimplePointInAreaLocator piaLoc(testGeom);
for(std::size_t i = 0, ni = targetRepPts->size(); i < ni; i++) {
const geom::Coordinate* pt = (*targetRepPts)[i];
const Location loc = piaLoc.locate(pt);
if(geom::Location::EXTERIOR != loc) {
return true;
}
}
return false;
}
//
// public:
//
} // namespace geos.geom.prep
} // namespace geos.geom
} // namespace geos
| 27.477778 | 106 | 0.660938 | [
"geometry"
] |
83fb7551285e716814dc1bd909af9b10e6787ca0 | 4,149 | cpp | C++ | src/allegro_flare/drawing_interface_html_canvas.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 25 | 2015-03-30T02:02:43.000Z | 2019-03-04T22:29:12.000Z | src/allegro_flare/drawing_interface_html_canvas.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 122 | 2015-04-01T08:15:26.000Z | 2019-10-16T20:31:22.000Z | src/allegro_flare/drawing_interface_html_canvas.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 4 | 2016-09-02T12:14:09.000Z | 2018-11-23T20:38:49.000Z |
#include <allegro_flare/drawing_interface_html_canvas.h>
#include <AllegroFlare/Color.hpp>
#include <AllegroFlare/Useful.hpp>
#include <AllegroFlare/UsefulPHP.hpp>
using namespace AllegroFlare;
namespace allegro_flare
{
int DrawingInterfaceHTMLCanvas::next_html5_canvas_id = 1;
DrawingInterfaceHTMLCanvas::DrawingInterfaceHTMLCanvas()
: DrawingInterface("html5 canvas")
{}
DrawingInterfaceHTMLCanvas::~DrawingInterfaceHTMLCanvas()
{}
std::string DrawingInterfaceHTMLCanvas::get_canvas_id()
{
return std::string("canvas") + tostring(current_canvas_id);
}
void DrawingInterfaceHTMLCanvas::prepare_surface(int surface_width, int surface_height)
{
current_document_output.clear();
current_document_output << "<canvas id=\"" << get_canvas_id() << "\" width=\"" << surface_width << "\" height=\"" << surface_height << " style=\"border: 1px solid black;\"></canvas>\n";
current_document_output << "<script type=\"text/javascript\">\n";
current_document_output << "var canvas = document.getElementById(\"" << get_canvas_id() << "\");\n";
current_document_output << "var context = canvas.getContext(\"2d\");\n";
current_document_output << "\n";
}
void DrawingInterfaceHTMLCanvas::draw_line(float x1, float y1, float x2, float y2, ALLEGRO_COLOR color, float thickness)
{
current_document_output << "context.beginPath();" << "\n";
current_document_output << "context.moveTo(" << x1 << ", " << y1 << ");" << "\n";
current_document_output << "context.lineTo(" << x2 << ", " << y2 << ");" << "\n";
current_document_output << "context.strokeStyle=\"" << color::get_css_str(color) << "\";" << "\n";
current_document_output << "context.lineWidth=\"" << thickness << "\";" << "\n";
current_document_output << "context.stroke();" << "\n";
current_document_output << "\n";
}
void DrawingInterfaceHTMLCanvas::draw_rectangle(float x1, float y1, float x2, float y2, ALLEGRO_COLOR outline_color, float thickness)
{
current_document_output << "context.strokeStyle=\"" << color::get_css_str(outline_color) << "\";" << "\n";
current_document_output << "context.lineWidth=\"" << thickness << "\";" << "\n";
current_document_output << "context.strokeRect(" << x1 << ", " << y1 << ", " << (x2-x1) << ", " << (y2-y1) << ");" << "\n";
current_document_output << "\n";
}
void DrawingInterfaceHTMLCanvas::draw_text(std::string text, float x, float y, float align_x, float align_y, ALLEGRO_COLOR color, std::string font_family, float font_size, ALLEGRO_FONT *font)
{
current_document_output << "context.fillStyle=\"" << color::get_css_str(color) << "\";" << "\n";
current_document_output << "context.font=\"" << (font_size/4) << "px " << font_family << "\";" << "\n";
current_document_output << "context.fillText(\"" << text << "\", " << x << ", " << y << ");" << "\n";
current_document_output << "\n";
}
void DrawingInterfaceHTMLCanvas::draw_ustr_chr(int32_t ustr_char, float x, float y, float align_x, float align_y, ALLEGRO_COLOR color, std::string font_family, float font_size, ALLEGRO_FONT *font)
{
current_document_output << "context.fillStyle=\"" << color::get_css_str(color) << "\";" << "\n";
current_document_output << "context.font=\"" << (font_size/4) << "px " << font_family << "\";" << "\n";
current_document_output << "context.fillText(String.fromCharCode(" << ustr_char << "), " << x << ", " << y << ");" << "\n";
current_document_output << "\n";
}
void DrawingInterfaceHTMLCanvas::finish_surface()
{
current_document_output << "</script>" << "\n";
}
bool DrawingInterfaceHTMLCanvas::save_file(std::string file_basename)
{
std::string filename = file_basename + ".canvas.html";
if (php::file_exists(filename)) al_remove_filename(file_basename.c_str());
php::file_put_contents(filename, get_output());
return true;
}
std::string DrawingInterfaceHTMLCanvas::get_output()
{
return current_document_output.str();
}
}
| 31.195489 | 199 | 0.638949 | [
"solid"
] |
83fd21523b1c102429b7785c68fe9a0f628accc2 | 9,277 | cpp | C++ | test/biggles_core.cpp | fbi-octopus/biggles | 2dac4f1748ab87242951239caf274f302be1143a | [
"Apache-2.0"
] | 1 | 2019-11-15T14:01:59.000Z | 2019-11-15T14:01:59.000Z | test/biggles_core.cpp | fbi-octopus/biggles | 2dac4f1748ab87242951239caf274f302be1143a | [
"Apache-2.0"
] | null | null | null | test/biggles_core.cpp | fbi-octopus/biggles | 2dac4f1748ab87242951239caf274f302be1143a | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <vector>
#include "biggles/detail/pair_collection.hpp"
#include "biggles/observation.hpp"
#include "biggles/point_2d.hpp"
#include "biggles/track.hpp"
// include this last to stop pre-processor macros breaking things
extern "C" {
#include <ccan/tap/tap.h>
}
using namespace biggles;
void test_point_2d()
{
point_2d p1, p2(3.f, 4.f), p3(p2);
const point_2d p4(5,6);
ok1(x(p1) == 0.f);
ok1(y(p1) == 0.f);
ok1(x(p2) == 3.f);
ok1(y(p2) == 4.f);
ok1(x(p3) == x(p2));
ok1(y(p3) == y(p2));
ok1(x(p4) == 5.f);
ok1(y(p4) == 6.f);
x(p2) = 4.5f;
y(p2) = x(p4);
ok1(x(p2) == 4.5f);
ok1(y(p2) == 5.f);
}
void test_observation()
{
diag("test observation");
observation o1(new observation_t());
observation o2(new_obs(3.f, 4.f, 100));
observation o3(o2);
const observation o4(new_obs(5,6,7));
ok1(x(o1) == 0.f);
ok1(y(o1) == 0.f);
ok1(t(o1) == 0);
ok1(x(o2) == 3.f);
ok1(y(o2) == 4.f);
ok1(t(o2) == 100);
ok1(x(o3) == x(o2));
ok1(y(o3) == y(o2));
ok1(t(o3) == t(o2));
ok1(x(o4) == 5.f);
ok1(y(o4) == 6.f);
ok1(t(o4) == 7);
o2->set_x(4.5f);
o2->set_y(x(o4));
o1->set_t(1);
o2->set_t(t(o1));
ok1(x(o2) == 4.5f);
ok1(y(o2) == 5.f);
ok1(t(o2) == 1);
}
void test_track()
{
observation obs[] = {
new_obs(1.0f, 2.0f, 1), // 0
new_obs(1.0f, 3.0f, 1), // 1
new_obs(3.0f, 4.0f, 1), // 2
new_obs(1.0f, 0.0f, 1), // 3
new_obs(1.3f, 2.2f, 2), // 4
new_obs(2.1f, 1.6f, 2), // 5
new_obs(1.3f, 0.1f, 2), // 6
new_obs(3.2f, 4.5f, 2), // 7
new_obs(0.2f, 4.5f, 3), // 8
new_obs(3.2f, 7.5f, 4), // 9
};
const size_t n_obs = sizeof(obs) / sizeof(observation);
size_t indices[] = { 1, 5 };
const size_t n_indices = sizeof(indices) / sizeof(size_t);
track t1(1, 4, indices, indices + n_indices, obs, obs + n_obs, 1.f), t2(t1), t3;
ok1(t1.first_time_stamp() == 1);
ok1(t1.last_time_stamp() == 4);
ok1(t1.duration() == 3);
ok1(t1.dynamic_drag() == 1.f);
ok1(t1.size() == 2);
ok1(*t1.begin() == obs[1]);
ok1(*(--t1.end()) == obs[5]);
ok1(x(t1.min_location()) == 1.f);
ok1(y(t1.min_location()) == 1.6f);
ok1(x(t1.max_location()) == 2.1f);
ok1(y(t1.max_location()) == 3.0f);
ok1(within_bounds(t1,point_2d(1.5f, 2.5f)));
ok1(!within_bounds(t1,point_2d(8.5f, 2.5f)));
ok1(!within_bounds(t1,point_2d(0.5f, 2.5f)));
ok1(!within_bounds(t1,point_2d(1.5f, 1.5f)));
ok1(!within_bounds(t1,point_2d(1.5f, 9.5f)));
ok1(within_bounds(t1,point_2d(1.5f, 2.5f), 1));
ok1(!within_bounds(t1,point_2d(8.5f, 2.5f), 1));
ok1(!within_bounds(t1,point_2d(0.5f, 2.5f), 1));
ok1(!within_bounds(t1,point_2d(1.5f, 1.5f), 1));
ok1(!within_bounds(t1,point_2d(1.5f, 9.5f), 1));
ok1(within_bounds(t1,point_2d(1.5f, 2.5f), 2));
ok1(!within_bounds(t1,point_2d(8.5f, 2.5f), 2));
ok1(!within_bounds(t1,point_2d(0.5f, 2.5f), 2));
ok1(!within_bounds(t1,point_2d(1.5f, 1.5f), 2));
ok1(!within_bounds(t1,point_2d(1.5f, 9.5f), 2));
ok1(!within_bounds(t1,point_2d(1.5f, 2.5f), 0));
ok1(!within_bounds(t1,point_2d(1.5f, 2.5f), 41));
ok1(within_bounds(t1,new_obs(1.5f, 2.5f, 1)));
ok1(!within_bounds(t1,new_obs(8.5f, 2.5f, 1)));
ok1(!within_bounds(t1,new_obs(0.5f, 2.5f, 1)));
ok1(!within_bounds(t1,new_obs(1.5f, 1.5f, 1)));
ok1(!within_bounds(t1,new_obs(1.5f, 9.5f, 1)));
ok1(within_bounds(t1,new_obs(1.5f, 2.5f, 2)));
ok1(!within_bounds(t1,new_obs(8.5f, 2.5f, 2)));
ok1(!within_bounds(t1,new_obs(0.5f, 2.5f, 2)));
ok1(!within_bounds(t1,new_obs(1.5f, 1.5f, 2)));
ok1(!within_bounds(t1,new_obs(1.5f, 9.5f, 2)));
ok1(!within_bounds(t1,new_obs(1.5f, 2.5f, 0)));
ok1(!within_bounds(t1,new_obs(1.5f, 2.5f, 41)));
ok1(t1.size() == 2);
ok1(t2.first_time_stamp() == 1);
ok1(t2.last_time_stamp() == 4);
ok1(t2.duration() == 3);
ok1(t2.size() == 2);
ok1(*t2.begin() == obs[1]);
ok1(*(--t2.end()) == obs[5]);
ok1(x(t2.min_location()) == 1.f);
ok1(y(t2.min_location()) == 1.6f);
ok1(x(t2.max_location()) == 2.1f);
ok1(y(t2.max_location()) == 3.0f);
ok1(within_bounds(t2,point_2d(1.5f, 2.5f)));
ok1(!within_bounds(t2,point_2d(8.5f, 2.5f)));
ok1(!within_bounds(t2,point_2d(0.5f, 2.5f)));
ok1(!within_bounds(t2,point_2d(1.5f, 1.5f)));
ok1(!within_bounds(t2,point_2d(1.5f, 9.5f)));
ok1(within_bounds(t2,point_2d(1.5f, 2.5f), 1));
ok1(!within_bounds(t2,point_2d(8.5f, 2.5f), 1));
ok1(!within_bounds(t2,point_2d(0.5f, 2.5f), 1));
ok1(!within_bounds(t2,point_2d(1.5f, 1.5f), 1));
ok1(!within_bounds(t2,point_2d(1.5f, 9.5f), 1));
ok1(within_bounds(t2,point_2d(1.5f, 2.5f), 2));
ok1(!within_bounds(t2,point_2d(8.5f, 2.5f), 2));
ok1(!within_bounds(t2,point_2d(0.5f, 2.5f), 2));
ok1(!within_bounds(t2,point_2d(1.5f, 1.5f), 2));
ok1(!within_bounds(t2,point_2d(1.5f, 9.5f), 2));
ok1(!within_bounds(t2,point_2d(1.5f, 2.5f), 0));
ok1(!within_bounds(t2,point_2d(1.5f, 2.5f), 41));
ok1(within_bounds(t2,new_obs(1.5f, 2.5f, 1)));
ok1(!within_bounds(t2,new_obs(8.5f, 2.5f, 1)));
ok1(!within_bounds(t2,new_obs(0.5f, 2.5f, 1)));
ok1(!within_bounds(t2,new_obs(1.5f, 1.5f, 1)));
ok1(!within_bounds(t2,new_obs(1.5f, 9.5f, 1)));
ok1(within_bounds(t2,new_obs(1.5f, 2.5f, 2)));
ok1(!within_bounds(t2,new_obs(8.5f, 2.5f, 2)));
ok1(!within_bounds(t2,new_obs(0.5f, 2.5f, 2)));
ok1(!within_bounds(t2,new_obs(1.5f, 1.5f, 2)));
ok1(!within_bounds(t2,new_obs(1.5f, 9.5f, 2)));
ok1(!within_bounds(t2,new_obs(1.5f, 2.5f, 0)));
ok1(!within_bounds(t2,new_obs(1.5f, 2.5f, 41)));
ok1(t2.size() == 2);
ok1(t3.first_time_stamp() == 0);
ok1(t3.last_time_stamp() == 0);
ok1(t3.duration() == 0);
ok1(t3.size() == 0);
ok1(!within_bounds(t3,point_2d(0.f, 0.f)));
ok1(!within_bounds(t3,point_2d(0.f, 0.f), 0));
ok1(!within_bounds(t3,new_obs(0.f, 0.f, 0)));
// test merging
size_t indices_2[] = { 8, 9 };
const size_t n_indices_2 = sizeof(indices_2) / sizeof(size_t);
track t4(3, 10, indices_2, indices_2 + n_indices_2, obs, obs + n_obs, 1.f);
track t5(t4,t1,1.f), t6(t1,t4,1.f), t6a(t1,t4,2.f);
ok1(t5 == t6);
ok1(t5 != t4);
ok1(t5 != t1);
ok1(t6 != t6a);
ok1(t5.first_time_stamp() == 1);
ok1(t5.last_time_stamp() == 10);
ok1(t5.min_location() == point_2d(0.2f, 1.6f));
ok1(t5.max_location() == point_2d(3.2f, 7.5f));
track t7(t1,t3,1.f), t8(t3,t1,1.f);
ok1(t7 == t8);
ok1(t7 != t1);
ok1(t7 != t3);
bool caught(false);
try
{
track t8(t1,t1,1.f);
}
catch(std::runtime_error& e)
{
caught = true;
}
ok(caught, "merging overlapping tracks fails");
track t9(t8, 5.f);
ok1(t9 != t8);
ok1(t9.dynamic_drag() == 5.f);
}
void test_pair_collection()
{
typedef std::pair<int, int> int_pair;
int_pair input_pairs[] =
{
std::make_pair( 1, 1 ),
std::make_pair( 2, 1 ),
std::make_pair( 2, 2 ),
std::make_pair( 1, 2 ), // duplicate of 1
std::make_pair( 3, 4 ),
std::make_pair( 5, 4 ),
std::make_pair( 1, 4 ),
std::make_pair( 4, 7 ),
std::make_pair( 7, 2 ),
};
size_t n_pairs = sizeof(input_pairs) / sizeof(int_pair);
ok1(n_pairs > 0);
detail::pair_collection<int> pairs(input_pairs, input_pairs + n_pairs);
diag("Pair count: %zu", pairs.size());
ok1(pairs.size() == n_pairs - 1); // -1 to account for duplicate
BOOST_FOREACH(const detail::pair_collection<int>::value_pair& p, pairs)
{
diag("pair collection contains (%i, %i)", p.first, p.second);
}
ok1(!pairs.contains_pair_with_element(8));
pairs.insert(std::make_pair( 4, 8 ));
ok1(pairs.size() == n_pairs);
ok1(pairs.contains_pair_with_element(8));
ok1(!pairs.contains_pair_with_element(0));
ok1(pairs.contains_pair_with_element(1));
ok1(pairs.contains_pair_with_element(2));
ok1(pairs.contains_pair_with_element(3));
ok1(pairs.contains_pair_with_element(4));
ok1(pairs.contains_pair_with_element(5));
ok1(!pairs.contains_pair_with_element(6));
ok1(pairs.contains_pair_with_element(7));
ok1(pairs.contains_pair_with_element(8));
pairs.erase_pairs_with_element(4);
ok1(pairs.size() == n_pairs - 5);
ok1(!pairs.contains_pair_with_element(0));
ok1(pairs.contains_pair_with_element(1));
ok1(pairs.contains_pair_with_element(2));
ok1(!pairs.contains_pair_with_element(3));
ok1(!pairs.contains_pair_with_element(4));
ok1(!pairs.contains_pair_with_element(5));
ok1(!pairs.contains_pair_with_element(6));
ok1(pairs.contains_pair_with_element(7));
ok1(!pairs.contains_pair_with_element(8));
BOOST_FOREACH(const detail::pair_collection<int>::value_pair& p, pairs)
{
diag("pair collection contains (%i, %i)", p.first, p.second);
}
}
int main(int argc, char** argv)
{
plan_tests(10 + 15 + 102 + 24);
test_point_2d();
test_observation();
test_track();
test_pair_collection();
return exit_status();
}
| 28.900312 | 84 | 0.584241 | [
"vector"
] |
86033080f8be1d8b77a8c34b7f63a0e40c933cba | 2,276 | cpp | C++ | src/flame/db/mongodb/client.cpp | partyfly/php-flame | aa7b06a1183f4f32dd1adaeefd564c6fbf8e8ea9 | [
"MIT"
] | null | null | null | src/flame/db/mongodb/client.cpp | partyfly/php-flame | aa7b06a1183f4f32dd1adaeefd564c6fbf8e8ea9 | [
"MIT"
] | null | null | null | src/flame/db/mongodb/client.cpp | partyfly/php-flame | aa7b06a1183f4f32dd1adaeefd564c6fbf8e8ea9 | [
"MIT"
] | null | null | null | #include "deps.h"
#include "../../flame.h"
#include "../../coroutine.h"
#include "../../thread_worker.h"
#include "client_implement.h"
#include "client.h"
#include "collection.h"
namespace flame {
namespace db {
namespace mongodb {
php::value client::__construct(php::parameters& params) {
impl = new client_implement(this);
return nullptr;
}
php::value client::__destruct(php::parameters& params) {
impl->worker_.close_work(impl, client_implement::destroy_wk, client_implement::destroy_cb);
return nullptr;
}
void client::default_cb(uv_work_t* req, int status) {
client_request_t* ctx = reinterpret_cast<client_request_t*>(req->data);
if(ctx->co) ctx->co->next(ctx->rv);
delete ctx;
}
php::value client::connect(php::parameters& params) {
client_request_t* ctx = new client_request_t {
coroutine::current, impl, nullptr
};
ctx->req.data = ctx;
if(params.length() > 0 && params[0].is_string()) {
ctx->name = params[0];
}
impl->worker_.queue_work(&ctx->req,
client_implement::connect_wk,
connect_cb);
return flame::async(this);
}
void client::connect_cb(uv_work_t* req, int status) {
client_request_t* ctx = reinterpret_cast<client_request_t*>(req->data);
if(ctx->rv.is_string()) {
php::string& message = ctx->rv;
ctx->co->fail(message, 0);
}else{
ctx->co->next(ctx->rv);
}
delete ctx;
}
void client::collection_cb(uv_work_t* req, int status) {
client_request_t* ctx = reinterpret_cast<client_request_t*>(req->data);
if(ctx->rv.is_pointer()) {
mongoc_collection_t* col = ctx->rv.ptr<mongoc_collection_t>();
php::object obj = php::object::create<mongodb::collection>();
mongodb::collection* cpp = obj.native<mongodb::collection>();
// ctx->self ===> impl
cpp->init(&ctx->self->worker_, ctx->self->client_, col);
ctx->rv = std::move(obj);
}
ctx->co->next(ctx->rv);
delete ctx;
}
php::value client::collection(php::parameters& params) {
client_request_t* ctx = new client_request_t {
coroutine::current, impl, nullptr, params[0].to_string()
};
ctx->req.data = ctx;
impl->worker_.queue_work(&ctx->req, client_implement::collection_wk, collection_cb);
return flame::async(this);
}
}
}
}
| 31.611111 | 94 | 0.660369 | [
"object"
] |
860b40591ef4f80b010017fdc22c032d033a21b2 | 489 | cpp | C++ | 27.remove_element.cpp | willyii/LeetcodeRecord | e2ce7ed140409b00ada0cc17854f6a537bf2fc51 | [
"MIT"
] | null | null | null | 27.remove_element.cpp | willyii/LeetcodeRecord | e2ce7ed140409b00ada0cc17854f6a537bf2fc51 | [
"MIT"
] | null | null | null | 27.remove_element.cpp | willyii/LeetcodeRecord | e2ce7ed140409b00ada0cc17854f6a537bf2fc51 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int> &nums, int val) {
int lo = 0, hi = nums.size() - 1;
while (hi >= lo && nums[lo] != val) {
lo++;
}
while (hi >= lo && nums[hi] == val) {
hi--;
}
while (lo <= hi) {
nums[lo++] = nums[hi--];
while (hi >= lo && nums[lo] != val) {
lo++;
}
while (hi >= lo && nums[hi] == val) {
hi--;
}
}
return lo;
}
};
| 17.464286 | 49 | 0.429448 | [
"vector"
] |
86133b03cc11a0185ca1fbeaa80673679cd93cbc | 3,705 | cpp | C++ | src/other/openscenegraph/src/osgViewer/Scene.cpp | Zitara/BRLCAD | 620449d036e38bd52257f6b5b10daa55d9284900 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 1 | 2019-10-23T16:17:49.000Z | 2019-10-23T16:17:49.000Z | src/other/openscenegraph/src/osgViewer/Scene.cpp | pombredanne/sf.net-brlcad | fb56f37c201b51241e8f3aa7b979436856f43b8c | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/openscenegraph/src/osgViewer/Scene.cpp | pombredanne/sf.net-brlcad | fb56f37c201b51241e8f3aa7b979436856f43b8c | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 1 | 2018-12-21T21:09:47.000Z | 2018-12-21T21:09:47.000Z | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library 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
* OpenSceneGraph Public License for more details.
*/
#include <osgViewer/Scene>
#include <osgGA/EventVisitor>
using namespace osgViewer;
namespace osgViewer
{
struct SceneSingleton
{
SceneSingleton() {}
inline void add(Scene* scene)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
_cache.push_back(scene);
}
inline void remove(Scene* scene)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
for(SceneCache::iterator itr = _cache.begin();
itr != _cache.end();
++itr)
{
if (scene==itr->get())
{
_cache.erase(itr);
break;
}
}
}
inline Scene* getScene(osg::Node* node)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
for(SceneCache::iterator itr = _cache.begin();
itr != _cache.end();
++itr)
{
Scene* scene = itr->get();
if (scene && scene->getSceneData()==node) return scene;
}
return 0;
}
typedef std::vector< osg::observer_ptr<Scene> > SceneCache;
SceneCache _cache;
OpenThreads::Mutex _mutex;
};
static SceneSingleton& getSceneSingleton()
{
static SceneSingleton s_sceneSingleton;
return s_sceneSingleton;
}
// Use a proxy to force the initialization of the SceneSingleton during static initialization
OSG_INIT_SINGLETON_PROXY(SceneSingletonProxy, getSceneSingleton())
}
Scene::Scene():
osg::Referenced(true)
{
setDatabasePager(osgDB::DatabasePager::create());
setImagePager(new osgDB::ImagePager);
getSceneSingleton().add(this);
}
Scene::~Scene()
{
getSceneSingleton().remove(this);
}
void Scene::setSceneData(osg::Node* node)
{
_sceneData = node;
}
osg::Node* Scene::getSceneData()
{
return _sceneData.get();
}
const osg::Node* Scene::getSceneData() const
{
return _sceneData.get();
}
void Scene::setDatabasePager(osgDB::DatabasePager* dp)
{
_databasePager = dp;
}
void Scene::setImagePager(osgDB::ImagePager* ip)
{
_imagePager = ip;
}
void Scene::updateSceneGraph(osg::NodeVisitor& updateVisitor)
{
if (!_sceneData) return;
if (getDatabasePager())
{
// synchronize changes required by the DatabasePager thread to the scene graph
getDatabasePager()->updateSceneGraph((*updateVisitor.getFrameStamp()));
}
if (getImagePager())
{
// synchronize changes required by the DatabasePager thread to the scene graph
getImagePager()->updateSceneGraph(*(updateVisitor.getFrameStamp()));
}
if (getSceneData())
{
updateVisitor.setImageRequestHandler(getImagePager());
getSceneData()->accept(updateVisitor);
}
}
Scene* Scene::getScene(osg::Node* node)
{
return getSceneSingleton().getScene(node);
return 0;
}
Scene* Scene::getOrCreateScene(osg::Node* node)
{
if (!node) return 0;
osgViewer::Scene* scene = getScene(node);
if (!scene)
{
scene = new Scene;
scene->setSceneData(node);
}
return scene;
}
| 23.301887 | 93 | 0.648583 | [
"vector"
] |
8617f72634b6dc7eefc43bfe3d908d46bff4ab77 | 19,752 | cpp | C++ | src/inventory.cpp | crazyBaboon/MathWorlds | dd35e88e207a26be8632999ad09eeef81820343d | [
"CC-BY-4.0"
] | 1 | 2018-03-01T13:03:01.000Z | 2018-03-01T13:03:01.000Z | src/inventory.cpp | crazyBaboon/MathWorlds | dd35e88e207a26be8632999ad09eeef81820343d | [
"CC-BY-4.0"
] | null | null | null | src/inventory.cpp | crazyBaboon/MathWorlds | dd35e88e207a26be8632999ad09eeef81820343d | [
"CC-BY-4.0"
] | null | null | null | /*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "inventory.h"
#include "serialization.h"
#include "debug.h"
#include <sstream>
#include "log.h"
#include "itemdef.h"
#include "util/strfnd.h"
#include "content_mapnode.h" // For loading legacy MaterialItems
#include "nameidmapping.h" // For loading legacy MaterialItems
#include "util/serialize.h"
#include "util/string.h"
/*
ItemStack
*/
static content_t content_translate_from_19_to_internal(content_t c_from)
{
for(u32 i=0; i<sizeof(trans_table_19)/sizeof(trans_table_19[0]); i++)
{
if(trans_table_19[i][1] == c_from)
{
return trans_table_19[i][0];
}
}
return c_from;
}
ItemStack::ItemStack(const std::string &name_, u16 count_,
u16 wear_, IItemDefManager *itemdef) :
name(itemdef->getAlias(name_)),
count(count_),
wear(wear_)
{
if (name.empty() || count == 0)
clear();
else if (itemdef->get(name).type == ITEM_TOOL)
count = 1;
}
void ItemStack::serialize(std::ostream &os) const
{
DSTACK(FUNCTION_NAME);
if(empty())
return;
// Check how many parts of the itemstring are needed
int parts = 1;
if(count != 1)
parts = 2;
if(wear != 0)
parts = 3;
if (!metadata.empty())
parts = 4;
os<<serializeJsonStringIfNeeded(name);
if(parts >= 2)
os<<" "<<count;
if(parts >= 3)
os<<" "<<wear;
if (parts >= 4) {
os << " ";
metadata.serialize(os);
}
}
void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
{
DSTACK(FUNCTION_NAME);
clear();
// Read name
name = deSerializeJsonStringIfNeeded(is);
// Skip space
std::string tmp;
std::getline(is, tmp, ' ');
if(!tmp.empty())
throw SerializationError("Unexpected text after item name");
if(name == "MaterialItem")
{
// Obsoleted on 2011-07-30
u16 material;
is>>material;
u16 materialcount;
is>>materialcount;
// Convert old materials
if(material <= 0xff)
material = content_translate_from_19_to_internal(material);
if(material > 0xfff)
throw SerializationError("Too large material number");
// Convert old id to name
NameIdMapping legacy_nimap;
content_mapnode_get_name_id_mapping(&legacy_nimap);
legacy_nimap.getName(material, name);
if(name == "")
name = "unknown_block";
if (itemdef)
name = itemdef->getAlias(name);
count = materialcount;
}
else if(name == "MaterialItem2")
{
// Obsoleted on 2011-11-16
u16 material;
is>>material;
u16 materialcount;
is>>materialcount;
if(material > 0xfff)
throw SerializationError("Too large material number");
// Convert old id to name
NameIdMapping legacy_nimap;
content_mapnode_get_name_id_mapping(&legacy_nimap);
legacy_nimap.getName(material, name);
if(name == "")
name = "unknown_block";
if (itemdef)
name = itemdef->getAlias(name);
count = materialcount;
}
else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
|| name == "craft" || name == "CraftItem")
{
// Obsoleted on 2012-01-07
std::string all;
std::getline(is, all, '\n');
// First attempt to read inside ""
Strfnd fnd(all);
fnd.next("\"");
// If didn't skip to end, we have ""s
if(!fnd.at_end()){
name = fnd.next("\"");
} else { // No luck, just read a word then
fnd.start(all);
name = fnd.next(" ");
}
fnd.skip_over(" ");
if (itemdef)
name = itemdef->getAlias(name);
count = stoi(trim(fnd.next("")));
if(count == 0)
count = 1;
}
else if(name == "MBOItem")
{
// Obsoleted on 2011-10-14
throw SerializationError("MBOItem not supported anymore");
}
else if(name == "tool" || name == "ToolItem")
{
// Obsoleted on 2012-01-07
std::string all;
std::getline(is, all, '\n');
// First attempt to read inside ""
Strfnd fnd(all);
fnd.next("\"");
// If didn't skip to end, we have ""s
if(!fnd.at_end()){
name = fnd.next("\"");
} else { // No luck, just read a word then
fnd.start(all);
name = fnd.next(" ");
}
count = 1;
// Then read wear
fnd.skip_over(" ");
if (itemdef)
name = itemdef->getAlias(name);
wear = stoi(trim(fnd.next("")));
}
else
{
do // This loop is just to allow "break;"
{
// The real thing
// Apply item aliases
if (itemdef)
name = itemdef->getAlias(name);
// Read the count
std::string count_str;
std::getline(is, count_str, ' ');
if(count_str.empty())
{
count = 1;
break;
}
else
count = stoi(count_str);
// Read the wear
std::string wear_str;
std::getline(is, wear_str, ' ');
if(wear_str.empty())
break;
else
wear = stoi(wear_str);
// Read metadata
metadata.deSerialize(is);
// In case fields are added after metadata, skip space here:
//std::getline(is, tmp, ' ');
//if(!tmp.empty())
// throw SerializationError("Unexpected text after metadata");
} while(false);
}
if (name.empty() || count == 0)
clear();
else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
count = 1;
}
void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
{
std::istringstream is(str, std::ios::binary);
deSerialize(is, itemdef);
}
std::string ItemStack::getItemString() const
{
std::ostringstream os(std::ios::binary);
serialize(os);
return os.str();
}
ItemStack ItemStack::addItem(const ItemStack &newitem_,
IItemDefManager *itemdef)
{
ItemStack newitem = newitem_;
// If the item is empty or the position invalid, bail out
if(newitem.empty())
{
// nothing can be added trivially
}
// If this is an empty item, it's an easy job.
else if(empty())
{
*this = newitem;
newitem.clear();
}
// If item name or metadata differs, bail out
else if (name != newitem.name
|| metadata != newitem.metadata)
{
// cannot be added
}
// If the item fits fully, add counter and delete it
else if(newitem.count <= freeSpace(itemdef))
{
add(newitem.count);
newitem.clear();
}
// Else the item does not fit fully. Add all that fits and return
// the rest.
else
{
u16 freespace = freeSpace(itemdef);
add(freespace);
newitem.remove(freespace);
}
return newitem;
}
bool ItemStack::itemFits(const ItemStack &newitem_,
ItemStack *restitem,
IItemDefManager *itemdef) const
{
ItemStack newitem = newitem_;
// If the item is empty or the position invalid, bail out
if(newitem.empty())
{
// nothing can be added trivially
}
// If this is an empty item, it's an easy job.
else if(empty())
{
newitem.clear();
}
// If item name or metadata differs, bail out
else if (name != newitem.name
|| metadata != newitem.metadata)
{
// cannot be added
}
// If the item fits fully, delete it
else if(newitem.count <= freeSpace(itemdef))
{
newitem.clear();
}
// Else the item does not fit fully. Return the rest.
// the rest.
else
{
u16 freespace = freeSpace(itemdef);
newitem.remove(freespace);
}
if(restitem)
*restitem = newitem;
return newitem.empty();
}
ItemStack ItemStack::takeItem(u32 takecount)
{
if(takecount == 0 || count == 0)
return ItemStack();
ItemStack result = *this;
if(takecount >= count)
{
// Take all
clear();
}
else
{
// Take part
remove(takecount);
result.count = takecount;
}
return result;
}
ItemStack ItemStack::peekItem(u32 peekcount) const
{
if(peekcount == 0 || count == 0)
return ItemStack();
ItemStack result = *this;
if(peekcount < count)
result.count = peekcount;
return result;
}
/*
Inventory
*/
InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
m_name(name),
m_size(size),
m_width(0),
m_itemdef(itemdef)
{
clearItems();
}
InventoryList::~InventoryList()
{
}
void InventoryList::clearItems()
{
m_items.clear();
for(u32 i=0; i<m_size; i++)
{
m_items.push_back(ItemStack());
}
//setDirty(true);
}
void InventoryList::setSize(u32 newsize)
{
if(newsize != m_items.size())
m_items.resize(newsize);
m_size = newsize;
}
void InventoryList::setWidth(u32 newwidth)
{
m_width = newwidth;
}
void InventoryList::setName(const std::string &name)
{
m_name = name;
}
void InventoryList::serialize(std::ostream &os) const
{
//os.imbue(std::locale("C"));
os<<"Width "<<m_width<<"\n";
for(u32 i=0; i<m_items.size(); i++)
{
const ItemStack &item = m_items[i];
if(item.empty())
{
os<<"Empty";
}
else
{
os<<"Item ";
item.serialize(os);
}
os<<"\n";
}
os<<"EndInventoryList\n";
}
void InventoryList::deSerialize(std::istream &is)
{
//is.imbue(std::locale("C"));
clearItems();
u32 item_i = 0;
m_width = 0;
for(;;)
{
std::string line;
std::getline(is, line, '\n');
std::istringstream iss(line);
//iss.imbue(std::locale("C"));
std::string name;
std::getline(iss, name, ' ');
if(name == "EndInventoryList")
{
break;
}
// This is a temporary backwards compatibility fix
else if(name == "end")
{
break;
}
else if(name == "Width")
{
iss >> m_width;
if (iss.fail())
throw SerializationError("incorrect width property");
}
else if(name == "Item")
{
if(item_i > getSize() - 1)
throw SerializationError("too many items");
ItemStack item;
item.deSerialize(iss, m_itemdef);
m_items[item_i++] = item;
}
else if(name == "Empty")
{
if(item_i > getSize() - 1)
throw SerializationError("too many items");
m_items[item_i++].clear();
}
}
}
InventoryList::InventoryList(const InventoryList &other)
{
*this = other;
}
InventoryList & InventoryList::operator = (const InventoryList &other)
{
m_items = other.m_items;
m_size = other.m_size;
m_width = other.m_width;
m_name = other.m_name;
m_itemdef = other.m_itemdef;
//setDirty(true);
return *this;
}
bool InventoryList::operator == (const InventoryList &other) const
{
if(m_size != other.m_size)
return false;
if(m_width != other.m_width)
return false;
if(m_name != other.m_name)
return false;
for(u32 i=0; i<m_items.size(); i++)
{
ItemStack s1 = m_items[i];
ItemStack s2 = other.m_items[i];
if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
s1.metadata != s2.metadata)
return false;
}
return true;
}
const std::string &InventoryList::getName() const
{
return m_name;
}
u32 InventoryList::getSize() const
{
return m_items.size();
}
u32 InventoryList::getWidth() const
{
return m_width;
}
u32 InventoryList::getUsedSlots() const
{
u32 num = 0;
for(u32 i=0; i<m_items.size(); i++)
{
if(!m_items[i].empty())
num++;
}
return num;
}
u32 InventoryList::getFreeSlots() const
{
return getSize() - getUsedSlots();
}
const ItemStack& InventoryList::getItem(u32 i) const
{
assert(i < m_size); // Pre-condition
return m_items[i];
}
ItemStack& InventoryList::getItem(u32 i)
{
assert(i < m_size); // Pre-condition
return m_items[i];
}
ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
{
if(i >= m_items.size())
return newitem;
ItemStack olditem = m_items[i];
m_items[i] = newitem;
//setDirty(true);
return olditem;
}
void InventoryList::deleteItem(u32 i)
{
assert(i < m_items.size()); // Pre-condition
m_items[i].clear();
}
ItemStack InventoryList::addItem(const ItemStack &newitem_)
{
ItemStack newitem = newitem_;
if(newitem.empty())
return newitem;
/*
First try to find if it could be added to some existing items
*/
for(u32 i=0; i<m_items.size(); i++)
{
// Ignore empty slots
if(m_items[i].empty())
continue;
// Try adding
newitem = addItem(i, newitem);
if(newitem.empty())
return newitem; // All was eaten
}
/*
Then try to add it to empty slots
*/
for(u32 i=0; i<m_items.size(); i++)
{
// Ignore unempty slots
if(!m_items[i].empty())
continue;
// Try adding
newitem = addItem(i, newitem);
if(newitem.empty())
return newitem; // All was eaten
}
// Return leftover
return newitem;
}
ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
{
if(i >= m_items.size())
return newitem;
ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
//if(leftover != newitem)
// setDirty(true);
return leftover;
}
bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
ItemStack *restitem) const
{
if(i >= m_items.size())
{
if(restitem)
*restitem = newitem;
return false;
}
return m_items[i].itemFits(newitem, restitem, m_itemdef);
}
bool InventoryList::roomForItem(const ItemStack &item_) const
{
ItemStack item = item_;
ItemStack leftover;
for(u32 i=0; i<m_items.size(); i++)
{
if(itemFits(i, item, &leftover))
return true;
item = leftover;
}
return false;
}
bool InventoryList::containsItem(const ItemStack &item) const
{
u32 count = item.count;
if(count == 0)
return true;
for(std::vector<ItemStack>::const_reverse_iterator
i = m_items.rbegin();
i != m_items.rend(); ++i)
{
if(count == 0)
break;
if(i->name == item.name)
{
if(i->count >= count)
return true;
else
count -= i->count;
}
}
return false;
}
ItemStack InventoryList::removeItem(const ItemStack &item)
{
ItemStack removed;
for(std::vector<ItemStack>::reverse_iterator
i = m_items.rbegin();
i != m_items.rend(); ++i)
{
if(i->name == item.name)
{
u32 still_to_remove = item.count - removed.count;
removed.addItem(i->takeItem(still_to_remove), m_itemdef);
if(removed.count == item.count)
break;
}
}
return removed;
}
ItemStack InventoryList::takeItem(u32 i, u32 takecount)
{
if(i >= m_items.size())
return ItemStack();
ItemStack taken = m_items[i].takeItem(takecount);
//if(!taken.empty())
// setDirty(true);
return taken;
}
void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
{
// Take item from source list
ItemStack item1;
if (count == 0)
item1 = changeItem(i, ItemStack());
else
item1 = takeItem(i, count);
if (item1.empty())
return;
// Try to add the item to destination list
u32 dest_size = dest->getSize();
// First try all the non-empty slots
for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
if (!m_items[dest_i].empty()) {
item1 = dest->addItem(dest_i, item1);
if (item1.empty()) return;
}
}
// Then try all the empty ones
for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
if (m_items[dest_i].empty()) {
item1 = dest->addItem(dest_i, item1);
if (item1.empty()) return;
}
}
// If we reach this, the item was not fully added
// Add the remaining part back to the source item
addItem(i, item1);
}
u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
u32 count, bool swap_if_needed, bool *did_swap)
{
if(this == dest && i == dest_i)
return count;
// Take item from source list
ItemStack item1;
if(count == 0)
item1 = changeItem(i, ItemStack());
else
item1 = takeItem(i, count);
if(item1.empty())
return 0;
// Try to add the item to destination list
u32 oldcount = item1.count;
item1 = dest->addItem(dest_i, item1);
// If something is returned, the item was not fully added
if(!item1.empty())
{
// If olditem is returned, nothing was added.
bool nothing_added = (item1.count == oldcount);
// If something else is returned, part of the item was left unadded.
// Add the other part back to the source item
addItem(i, item1);
// If olditem is returned, nothing was added.
// Swap the items
if (nothing_added && swap_if_needed) {
// Tell that we swapped
if (did_swap != NULL) {
*did_swap = true;
}
// Take item from source list
item1 = changeItem(i, ItemStack());
// Adding was not possible, swap the items.
ItemStack item2 = dest->changeItem(dest_i, item1);
// Put item from destination list to the source list
changeItem(i, item2);
}
}
return (oldcount - item1.count);
}
/*
Inventory
*/
Inventory::~Inventory()
{
clear();
}
void Inventory::clear()
{
m_dirty = true;
for(u32 i=0; i<m_lists.size(); i++)
{
delete m_lists[i];
}
m_lists.clear();
}
void Inventory::clearContents()
{
m_dirty = true;
for(u32 i=0; i<m_lists.size(); i++)
{
InventoryList *list = m_lists[i];
for(u32 j=0; j<list->getSize(); j++)
{
list->deleteItem(j);
}
}
}
Inventory::Inventory(IItemDefManager *itemdef)
{
m_dirty = false;
m_itemdef = itemdef;
}
Inventory::Inventory(const Inventory &other)
{
*this = other;
m_dirty = false;
}
Inventory & Inventory::operator = (const Inventory &other)
{
// Gracefully handle self assignment
if(this != &other)
{
m_dirty = true;
clear();
m_itemdef = other.m_itemdef;
for(u32 i=0; i<other.m_lists.size(); i++)
{
m_lists.push_back(new InventoryList(*other.m_lists[i]));
}
}
return *this;
}
bool Inventory::operator == (const Inventory &other) const
{
if(m_lists.size() != other.m_lists.size())
return false;
for(u32 i=0; i<m_lists.size(); i++)
{
if(*m_lists[i] != *other.m_lists[i])
return false;
}
return true;
}
void Inventory::serialize(std::ostream &os) const
{
for(u32 i=0; i<m_lists.size(); i++)
{
InventoryList *list = m_lists[i];
os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
list->serialize(os);
}
os<<"EndInventory\n";
}
void Inventory::deSerialize(std::istream &is)
{
clear();
for(;;)
{
std::string line;
std::getline(is, line, '\n');
std::istringstream iss(line);
std::string name;
std::getline(iss, name, ' ');
if(name == "EndInventory")
{
break;
}
// This is a temporary backwards compatibility fix
else if(name == "end")
{
break;
}
else if(name == "List")
{
std::string listname;
u32 listsize;
std::getline(iss, listname, ' ');
iss>>listsize;
InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
list->deSerialize(is);
m_lists.push_back(list);
}
else
{
throw SerializationError("invalid inventory specifier: " + name);
}
}
}
InventoryList * Inventory::addList(const std::string &name, u32 size)
{
m_dirty = true;
s32 i = getListIndex(name);
if(i != -1)
{
if(m_lists[i]->getSize() != size)
{
delete m_lists[i];
m_lists[i] = new InventoryList(name, size, m_itemdef);
}
return m_lists[i];
}
else
{
//don't create list with invalid name
if (name.find(" ") != std::string::npos) return NULL;
InventoryList *list = new InventoryList(name, size, m_itemdef);
m_lists.push_back(list);
return list;
}
}
InventoryList * Inventory::getList(const std::string &name)
{
s32 i = getListIndex(name);
if(i == -1)
return NULL;
return m_lists[i];
}
std::vector<const InventoryList*> Inventory::getLists()
{
std::vector<const InventoryList*> lists;
for(u32 i=0; i<m_lists.size(); i++)
{
InventoryList *list = m_lists[i];
lists.push_back(list);
}
return lists;
}
bool Inventory::deleteList(const std::string &name)
{
s32 i = getListIndex(name);
if(i == -1)
return false;
m_dirty = true;
delete m_lists[i];
m_lists.erase(m_lists.begin() + i);
return true;
}
const InventoryList * Inventory::getList(const std::string &name) const
{
s32 i = getListIndex(name);
if(i == -1)
return NULL;
return m_lists[i];
}
const s32 Inventory::getListIndex(const std::string &name) const
{
for(u32 i=0; i<m_lists.size(); i++)
{
if(m_lists[i]->getName() == name)
return i;
}
return -1;
}
//END
| 19.811434 | 90 | 0.657351 | [
"vector"
] |
86194a9fe3e7646811aa8e683efca3a27053c6f8 | 2,838 | cpp | C++ | leetcode/cpp/qt_design_phone_directory.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | 5 | 2016-10-29T09:28:11.000Z | 2019-10-19T23:02:48.000Z | leetcode/cpp/qt_design_phone_directory.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | leetcode/cpp/qt_design_phone_directory.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | /**
* @Author: Tian Qiao
* @Date: 2016-08-03T15:28:29+08:00
* @Email: qiaotian@me.com
* @Last modified by: Tian Qiao
* @Last modified time: 2016-08-03T15:28:34+08:00
* @Tag: List, Design
*/
/*
Design a Phone Directory which supports the following operations:
get: Provide a number which is not assigned to anyone.
check: Check if a number is available or not.
release: Recycle or release a number.
Example:
// Init a phone directory containing a total of 3 numbers: 0, 1, and 2.
PhoneDirectory directory = new PhoneDirectory(3);
// It can return any available phone number. Here we assume it returns 0.
directory.get();
// Assume it returns 1.
directory.get();
// The number 2 is available, so return true.
directory.check(2);
// It returns 2, the only number that is left.
directory.get();
// The number 2 is no longer available, so return false.
directory.check(2);
// Release number 2 back to the pool.
directory.release(2);
// Number 2 is available again, return true.
directory.check(2);
*/
// Use array instead of unordered_set
// the former part of array is used to store the unavailable numbers, while the
// the later part to store the available numbers, where 'index' seperate both.
class PhoneDirectory {
public:
/** Initialize your data structure here
@param maxNumbers - The maximum numbers that can be stored in the phone directory. */
//unordered_set<int> avail;
//int capacity = 0;
vector<int> freelist; // store the available and unavailable elements
vector<bool> flaglist; // mark the number is available or not
int index; // point to first available elements, all elements store before index have been used
PhoneDirectory(int maxNumbers) {
freelist.resize(maxNumbers, 0);
flaglist.resize(maxNumbers, true);
index = 0;
for(int i=0; i<maxNumbers; i++) freelist[i] = i;
}
/** Provide a number which is not assigned to anyone.
@return - Return an available number. Return -1 if none is available. */
int get() {
if(index<freelist.size()) {
flaglist[freelist[index]] = false;
return freelist[index++];
} else {
return -1;
}
}
/** Check if a number is available or not. */
bool check(int number) {
return number>=0 && number<freelist.size() && flaglist[number];
}
/** Recycle or release a number. */
void release(int number) {
if(number>=0 && number<freelist.size() && !flaglist[number]) {
flaglist[number] = true;
freelist[--index] = number;
}
}
};
/**
* Your PhoneDirectory object will be instantiated and called as such:
* PhoneDirectory obj = new PhoneDirectory(maxNumbers);
* int param_1 = obj.get();
* bool param_2 = obj.check(number);
* obj.release(number);
*/
| 29.257732 | 103 | 0.660324 | [
"object",
"vector"
] |
861c81dd9fe92cbecc9517a8f930a1bcf05e014c | 1,784 | hpp | C++ | test/TestSink.hpp | iboB/jalog | d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9 | [
"MIT"
] | 3 | 2021-12-07T06:16:31.000Z | 2021-12-22T14:12:36.000Z | test/TestSink.hpp | iboB/jalog | d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9 | [
"MIT"
] | null | null | null | test/TestSink.hpp | iboB/jalog | d89a5bb4ef8b0ea701a7cd3ea0229de3fbb3ecd9 | [
"MIT"
] | null | null | null | // jalog
// Copyright (c) 2021-2022 Borislav Stanimirov
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// https://opensource.org/licenses/MIT
//
#include <doctest/doctest.h>
#include <jalog/Sink.hpp>
#include <jalog/Entry.hpp>
#include "TestTime.hpp"
#include <string>
#include <cstdint>
#include <vector>
#include <algorithm>
class TestSink final : public jalog::Sink
{
public:
virtual void record(const jalog::Entry& entry) override
{
entries.emplace_back(entry);
}
struct EntryCopy
{
EntryCopy() = default;
EntryCopy(const jalog::Entry& e)
: scope(e.scope)
, level(e.level)
, timestamp(tonano(e.timestamp))
, text(e.text)
{}
jalog::ScopeDesc scope;
jalog::Level level;
uint64_t timestamp;
std::string text;
};
std::vector<EntryCopy> entries;
void checkSameEntries(const TestSink& other) const
{
auto& es0 = entries;
auto& es = other.entries;
CHECK(es0.size() == es.size());
for (size_t ei = 0; ei < es0.size(); ++ei)
{
auto& e0 = es0[ei];
auto& e = es[ei];
CHECK(&e0 != &e);
CHECK(e0.scope.label() == e.scope.label());
CHECK(e0.scope.id() == e.scope.id());
CHECK(e0.scope.userData == e.scope.userData);
CHECK(e0.level == e.level);
CHECK(e0.timestamp == e.timestamp);
CHECK(e0.text == e.text);
}
}
static void checkSortedEntries(const std::vector<EntryCopy>& es)
{
CHECK(std::is_sorted(es.begin(), es.end(), [](auto& a, auto& b) {
return a.timestamp < b.timestamp;
}));
}
};
| 24.777778 | 73 | 0.557175 | [
"vector"
] |
861da1a753958c84a76c7cb1929f6eedb3f89055 | 25,052 | cxx | C++ | src/larcv3/core/dataformat/Tensor.cxx | felker/larcv3 | c73936ece5cb11ca854b10987e32930f633fc998 | [
"MIT"
] | null | null | null | src/larcv3/core/dataformat/Tensor.cxx | felker/larcv3 | c73936ece5cb11ca854b10987e32930f633fc998 | [
"MIT"
] | null | null | null | src/larcv3/core/dataformat/Tensor.cxx | felker/larcv3 | c73936ece5cb11ca854b10987e32930f633fc998 | [
"MIT"
] | null | null | null | #ifndef __LARCV3DATAFORMAT_TENSOR_CXX__
#define __LARCV3DATAFORMAT_TENSOR_CXX__
#include "larcv3/core/base/larbys.h"
#include "larcv3/core/base/larcv_logger.h"
#include "larcv3/core/dataformat/Tensor.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
namespace larcv3 {
template<size_t dimension>
Tensor<dimension>::Tensor(const std::vector<size_t> & dims)
: _meta()
{
for(size_t i = 0; i < dims.size(); i ++) _meta.set_dimension(i, 1.0, dims[i]);
_img.resize(_meta.total_voxels());
}
template<size_t dimension>
Tensor<dimension>::Tensor(const ImageMeta<dimension>& meta)
: _img(meta.total_voxels(), 0.)
, _meta(meta)
{}
template<size_t dimension>
Tensor<dimension>::Tensor(const ImageMeta<dimension>& meta, const std::vector<float>& img)
: _img(img)
, _meta(meta)
{ if (img.size() != meta.total_voxels()) throw larbys("Inconsistent dimensions!"); }
template<size_t dimension>
Tensor<dimension>::Tensor(const Tensor& rhs)
: _img(rhs._img)
, _meta(rhs._meta)
{}
template<size_t dimension>
void Tensor<dimension>::reset(const ImageMeta<dimension>& meta)
{
_meta = meta;
if (_img.size() != _meta.total_voxels()) _img.resize(_meta.total_voxels());
paint(0.);
}
/// from numpy ctor
template<size_t dimension>
Tensor<dimension>::Tensor(pybind11::array_t<float> pyarray){
auto buffer = pyarray.request();
// First, we do checks that this is an acceptable dimension:
if (buffer.ndim != dimension){
LARCV_ERROR() << "ERROR: cannot convert array of dimension " << buffer.ndim
<< " to " << std::to_string(dimension) << "D Tensor\n";
throw larbys();
}
// With that satisfied, create the meta object:
for (size_t dim = 0; dim < dimension; ++dim)
_meta.set_dimension(dim, (double)(buffer.shape[dim]), (double)(buffer.shape[dim]));
// Now, we copy the data from numpy into our own buffer:
_img.resize(_meta.total_voxels());
auto ptr = static_cast<float *>(buffer.ptr);
for (size_t i = 0; i < _meta.total_voxels(); ++i) {
_img[i] = ptr[i];
}
}
// Return a numpy array of this object (no copy by default)
template<size_t dimension>
pybind11::array_t<float> Tensor<dimension>::as_array(){
// Cast the dimensions to std::array:
std::array<size_t, dimension> dimensions;
for (size_t i = 0; i < dimension; ++i) dimensions[i] = _meta.number_of_voxels(i);
return pybind11::array_t<float>(
// _meta.number_of_voxels()[0],
dimensions,
{},
&(_img[0])
);
}
// void Image2D::resize(const std::vector<size_t> & counts, float fillval)
// {
// auto const current_counts = _meta.number_of_voxels();
// // Create a new meta
// std::vector<float> img(rows * cols, fillval);
// size_t npixels = std::min(current_rows, rows);
// for (size_t c = 0; c < std::min(cols, current_cols); ++c) {
// for (size_t r = 0; r < npixels; ++r) {
// img[c * rows + r] = _img[c * current_rows + r];
// }
// }
// _meta.update(rows, cols);
// _img = std::move(img);
// }
template<size_t dimension>
void Tensor<dimension>::clear() {
_img.clear();
_img.resize(1, 0);
_meta = ImageMeta<dimension>();
//std::cout << "[Image2D (" << this << ")] Cleared image2D memory " << std::endl;
}
template<size_t dimension>
void Tensor<dimension>::clear_data() { for (auto& v : _img) v = 0.; }
template<size_t dimension>
void Tensor<dimension>::set_pixel( size_t index, float value ) {
if ( index >= _img.size() ) throw larbys("Out-of-bound pixel set request!");
_img[ index ] = value;
}
template<size_t dimension>
void Tensor<dimension>::set_pixel( const std::vector<size_t> & coords, float value ) {
size_t idx = _meta.index(coords);
if ( idx >= _meta.total_voxels() )
throw larbys("Out-of-bound pixel set request!");
_img[ idx ] = value;
}
template<size_t dimension>
void Tensor<dimension>::paint(float value)
{ for (auto& v : _img) v = value; }
template<size_t dimension>
void Tensor<dimension>::threshold(float thresh, bool lower)
{ for (auto& v : _img) if ( (lower && v < thresh) || (!lower && v > thresh ) ) v = thresh; }
template<size_t dimension>
void Tensor<dimension>::binarize(float thresh, float lower_overwrite, float upper_overwrite)
{ for (auto& v : _img) v = (v <= thresh ? lower_overwrite : upper_overwrite); }
template<size_t dimension>
float Tensor<dimension>::pixel(const std::vector<size_t> & coords) const{
// Get the access index:
return _img[_meta.index(coords)];
}
template<size_t dimension>
float Tensor<dimension>::pixel(size_t index) const{
return _img.at(index);
}
template<size_t dimension>
void Tensor<dimension>::copy(const std::vector<size_t> & coords, const float* src, size_t num_pixel)
{
const size_t idx = _meta.index(coords);
if (idx + num_pixel - 1 >= _img.size()) throw larbys("memcpy size exceeds allocated memory!");
memcpy(&(_img[idx]), src, num_pixel * sizeof(float));
}
template<size_t dimension>
void Tensor<dimension>::copy(const std::vector<size_t> & coords, const std::vector<float>& src, size_t num_pixel)
{
if (!num_pixel)
this->copy(coords, (float*)(&(src[0])), src.size());
else if (num_pixel <= src.size())
this->copy(coords, (float*)&src[0], num_pixel);
else
throw larbys("Not enough pixel in source!");
}
template<size_t dimension>
void Tensor<dimension>::copy(const std::vector<size_t> & coords, const short* src, size_t num_pixel)
{
const size_t idx = _meta.index(coords);
if (idx + num_pixel - 1 >= _img.size()) throw larbys("memcpy size exceeds allocated memory!");
for (size_t i = 0; i < num_pixel; ++i) _img[idx + i] = src[idx];
}
template<size_t dimension>
void Tensor<dimension>::copy(const std::vector<size_t> & coords, const std::vector<short>& src, size_t num_pixel)
{
if (!num_pixel)
this->copy(coords, (short*)(&(src[0])), src.size());
else if (num_pixel <= src.size())
this->copy(coords, (short*)&src[0], num_pixel);
else
throw larbys("Not enough pixel in source!");
}
template<size_t dimension>
void Tensor<dimension>::reverse_copy(const std::vector<size_t> & coords, const std::vector<float>& src, size_t nskip, size_t num_pixel)
{
size_t idx = 0;
try {
idx = _meta.index(coords);
} catch (const larbys& err) {
std::cout << "Exception caught @ " << __FUNCTION__ << std::endl
<< "Image2Tensor<dimension>D ... fill coords[0]: " << coords[0] << " => " << (coords[0] + num_pixel - 1) << std::endl
<< "Tensor<dimension> ... orig idx: " << nskip << " => " << nskip + num_pixel - 1 << std::endl
<< "Re-throwing exception..." << std::endl;
throw err;
}
if (!num_pixel) num_pixel = src.size() - nskip;
if ( (idx + 1) < num_pixel ) num_pixel = idx + 1;
for (size_t i = 0; i < num_pixel; ++i) { _img[idx + i] = src[nskip + num_pixel - i - 1]; }
}
template<size_t dimension>
void Tensor<dimension>::reverse_copy(const std::vector<size_t> & coords, const std::vector<short>& src, size_t nskip, size_t num_pixel)
{
size_t idx = 0;
try {
idx = _meta.index(coords);
} catch (const larbys& err) {
std::cout << "Exception caught @ " << __FUNCTION__ << std::endl
<< "Tensor<dimension> ... fill coords[0]: " << coords[0] << " => " << (coords[0] + num_pixel - 1) << std::endl
<< "Tensor<dimension> ... orig idx: " << nskip << " => " << nskip + num_pixel - 1 << std::endl
<< "Re-throwing exception..." << std::endl;
throw err;
}
if (!num_pixel) num_pixel = src.size() - nskip;
if ( (idx + 1) < num_pixel ) num_pixel = idx + 1;
for (size_t i = 0; i < num_pixel; ++i) { _img[idx + i] = (float)(src[nskip + num_pixel - i - 1]); }
}
// template<size_t dimension>
// Tensor<dimension> Tensor<dimension>::crop(const ImageMeta& crop_meta) const
// {
// // Croppin region must be within the image2D
// if ( crop_meta.min_x() < _meta.min_x() || crop_meta.min_y() < _meta.min_y() ||
// crop_meta.max_x() > _meta.max_x() || crop_meta.max_y() > _meta.max_y() )
// throw larbys("Cropping region contains region outside the image2D!");
//
// size_t min_col = _meta.col(crop_meta.min_x() + _meta.pixel_width() / 2. );
// size_t max_col = _meta.col(crop_meta.max_x() - _meta.pixel_width() / 2. );
// size_t min_row = _meta.row(crop_meta.min_y() + _meta.pixel_height() / 2. );
// size_t max_row = _meta.row(crop_meta.max_y() - _meta.pixel_height() / 2. );
// /*
// std::cout<<"Cropping! Requested:" << std::endl
// << crop_meta.dump() << std::overlay
//
// <<"Original:"<<std::endl
// <<_meta.dump()<<std::endl;
//
// std::cout<<min_col<< " => " << max_col << " ... " << min_row << " => " << max_row << std::endl;
// std::cout<<_meta.width() << " / " << _meta.cols() << " = " << _meta.pixel_width() << std::endl;
// */
// ImageMeta res_meta( (max_col - min_col + 1) * _meta.pixel_width(),
// (max_row - min_row + 1) * _meta.pixel_height(),
// (max_row - min_row + 1),
// (max_col - min_col + 1),
// _meta.min_x() + min_col * _meta.pixel_width(),
// _meta.min_y() + min_row * _meta.pixel_height(),
// _meta.id(), _meta.unit());
//
// std::vector<float> img;
// img.resize(res_meta.cols() * res_meta.rows());
//
// size_t column_size = max_row - min_row + 1;
// for (size_t col = min_col; col <= max_col; ++col)
//
// memcpy(&(img[(col - min_col)*column_size]), &(_img[_meta.index(min_row, col)]), column_size * sizeof(float));
//
// //std::cout<<"Cropped:" << std::endl << res_meta.dump()<<std::endl;
//
// return Tensor<dimansion>(std::move(res_meta), std::move(img));
// }
// void Image2D::overlay(const Image2D& rhs, CompressionModes_t mode )
// {
// auto const& rhs_meta = rhs.meta();
// if (rhs_meta.pixel_height() != _meta.pixel_height() || rhs_meta.pixel_width() != _meta.pixel_width())
// throw larbys("Overlay not supported yzet for images w/ different pixel size!");
// double x_min = std::max(_meta.min_x(), rhs_meta.min_x());
// double x_max = std::min(_meta.max_x(), rhs_meta.max_x());
// if (x_min >= x_max) return;
// double y_min = std::max(_meta.min_y(), rhs_meta.min_y());
// double y_max = std::min(_meta.max_y(), rhs_meta.max_y());
// if (y_min >= y_max) return;
// size_t row_min1 = _meta.row(y_min);
// size_t col_min1 = _meta.col(x_min);
// size_t row_min2 = rhs_meta.row(y_min);
// size_t col_min2 = rhs_meta.col(x_min);
// size_t nrows = (y_max - y_min) / _meta.pixel_height();
// size_t ncols = (x_max - x_min) / _meta.pixel_width();
// auto const& img2 = rhs.as_vector();
// for (size_t col_index = 0; col_index < ncols; ++col_index) {
// size_t index1 = _meta.index(row_min1, col_min1 + col_index);
// size_t index2 = rhs_meta.index(row_min2, col_min2 + col_index);
// switch (mode) {
// case kSum:
// for (size_t row_index = 0; row_index < nrows; ++row_index)
// _img.at(index1 + row_index) += img2.at(index2 + row_index);
// //_img[index1 + row_index] += img2[index2 + row_index];
// break;
// case kAverage:
// for (size_t row_index = 0; row_index < nrows; ++row_index)
// _img[index1 + row_index] += (_img[index1 + row_index] + img2[index2 + row_index]) / 2.;
// break;
// case kMaxPool:
// for (size_t row_index = 0; row_index < nrows; ++row_index)
// _img[index1 + row_index] = std::max(_img[index1 + row_index], img2[index2 + row_index]);
// break;
// case kOverWrite:
// for (size_t row_index = 0; row_index < nrows; ++row_index)
// _img[index1 + row_index] = img2[index2 + row_index];
// break;
// }
// }
// }
template<size_t dimension>
std::vector<float>&& Tensor<dimension>::move()
{ return std::move(_img); }
template<size_t dimension>
void Tensor<dimension>::move(std::vector<float>&& data)
{ _img = std::move(data); }
template<size_t dimension>
Tensor<dimension>& Tensor<dimension>::operator+=(const std::vector<float>& rhs)
{
if (rhs.size() != _img.size()) throw larbys("Cannot call += uniry operator w/ incompatible size!");
for (size_t i = 0; i < _img.size(); ++i) _img[i] += rhs[i];
return (*this);
}
template<size_t dimension>
Tensor<dimension>& Tensor<dimension>::operator+=(const larcv3::Tensor<dimension>& rhs)
{
if (rhs.size() != _img.size()) throw larbys("Cannot call += uniry operator w/ incompatible size!");
for(size_t index = 0; index < meta().total_voxels(); index ++ ){
set_pixel(index, pixel(index) + rhs.pixel(index));
}
return (*this);
}
template<size_t dimension>
Tensor<dimension>& Tensor<dimension>::operator-=(const std::vector<float>& rhs)
{
if (rhs.size() != _img.size()) throw larbys("Cannot call += uniry operator w/ incompatible size!");
for (size_t i = 0; i < _img.size(); ++i) _img[i] -= rhs[i];
return (*this);
}
template<size_t dimension>
void Tensor<dimension>::eltwise(const std::vector<float>& arr, bool allow_longer) {
// check multiplication is valid
if ( !( (allow_longer && _img.size() <= arr.size()) || arr.size() == _img.size() ) ) {
char oops[500];
sprintf( oops, "Image2D element-wise multiplication not valid. LHS size = %zu, while argument size = %zu",
_img.size(), arr.size());
throw larbys(oops);
}
// Element-wise multiplication: do random access as dimension has already been checked
for (size_t i = 0; i < _img.size(); ++i)
_img[i] *= arr[i];
}
template<size_t dimension>
void Tensor<dimension>::eltwise( const Tensor<dimension>& rhs ) {
// check multiplication is valid
auto const& meta = rhs.meta();
if (meta.total_voxels() != _meta.total_voxels() ) {
char oops[500];
sprintf( oops, "Tensor<dimension> element-wise multiplication not valid. LHS n_voxels (%zu) != RHS n_voxels (%zu)",
_meta.total_voxels(), meta.total_voxels());
throw larbys(oops);
}
eltwise(rhs.as_vector(), false);
}
template<size_t dimension>
Tensor<dimension> Tensor<dimension>::compress(
std::array<size_t, dimension> compression, PoolType_t pool_type) const
{
// First, compress the meta:
ImageMeta<dimension> compressed_meta = this->_meta.compress(compression);
float unfilled_value(0.0);
// default fill value depends on pooling type:
if (pool_type == larcv3::kPoolMax)
unfilled_value = - std::numeric_limits< float >::max();
// Create an output tensor:
Tensor<dimension> output(compressed_meta);
std::vector<float> output_data;
output_data.resize(compressed_meta.total_voxels(), unfilled_value);
// Loop over the pixels, find the position in the new tensor, and add it.
for (size_t index = 0; index < _img.size() ; index ++ ){
// First, get the old coordinates of this voxel:
auto coordinates = this->_meta.coordinates(index);
for (size_t d = 0; d < dimension; d ++) coordinates[d] = size_t(coordinates[d] / compression[d]);
size_t new_index = compressed_meta.index(coordinates);
// Add the new voxel to the new set:
if ( pool_type == larcv3::kPoolMax){
if (output_data[new_index] < _img[index]){
// Replace only if this new value is larger than the old
output_data[new_index] = _img[index];
}
}
else {
output_data[new_index] += _img[index];
}
}
output.move(std::move(output_data));
// Correct the output values by the total ratio of compression if averaging:
if (pool_type == larcv3::kPoolAverage){
float ratio = 1.0;
for (size_t d = 0; d < dimension; d ++) ratio *= compression[d];
output /= ratio;
}
return output;
}
template<size_t dimension>
Tensor<dimension> Tensor<dimension>::compress(
size_t compression, PoolType_t pool_type) const
{
std::array<size_t, dimension> comp;
for (size_t i = 0; i < dimension; ++i ) comp[i] = compression;
return this->compress(comp, pool_type);
}
template class Tensor<1>;
template class Tensor<2>;
template class Tensor<3>;
template class Tensor<4>;
template<> std::string as_string<Tensor<1>>() {return "Tensor1D";}
template<> std::string as_string<Tensor<2>>() {return "Tensor2D";}
template<> std::string as_string<Tensor<3>>() {return "Tensor3D";}
template<> std::string as_string<Tensor<4>>() {return "Tensor4D";}
}
#endif
/*
*
*
* Here are the implementations of the deprecated functions
*
*
*
*
void Image2D::compress(size_t rows, size_t cols, CompressionModes_t mode)
{
_img = copy_compress(rows, cols, mode);
_meta.update(rows, cols);
}
void Image2D::paint_row(int row, float value)
{
for ( size_t col = 0; col < _meta.cols(); col++ )
set_pixel( row, col, value );
}
void Image2D::paint_col(int col, float value)
{
for ( size_t row = 0; row < _meta.rows(); row++ )
set_pixel( row, col, value );
}
Image2D::Image2D(ImageMeta&& meta, std::vector<float>&& img)
: _img(std::move(img))
, _meta(std::move(meta))
{ if (_img.size() != _meta.rows() * _meta.cols()) throw larbys("Inconsistent dimensions!"); }
std::vector<float> Image2D::copy_compress(size_t rows, size_t cols, CompressionModes_t mode) const
{
if (mode == kOverWrite)
throw larbys("kOverWrite is invalid for copy_compress!");
const size_t self_cols = _meta.cols();
const size_t self_rows = _meta.rows();
if (self_cols % cols || self_rows % rows) {
char oops[500];
sprintf(oops, "Compression only possible if height/width are modular 0 of compression factor! H:%zuMOD%zu=%zu W:%zuMOD%zu=%zu",
self_rows, rows, self_rows % rows, self_cols, cols, self_cols % cols);
throw larbys(oops);
}
size_t cols_factor = self_cols / cols;
size_t rows_factor = self_rows / rows;
std::vector<float> result(cols * rows, 0);
for (size_t col = 0; col < cols; ++col) {
for (size_t row = 0; row < rows; ++row) {
float value = 0;
for (size_t orig_col = col * cols_factor; orig_col < (col + 1)*cols_factor; ++orig_col)
for (size_t orig_row = row * rows_factor; orig_row < (row + 1)*rows_factor; ++orig_row) {
if ( mode != kMaxPool ) {
// for sum and average mode
value += _img[orig_col * self_rows + orig_row];
}
else {
// maxpool
value = ( value < _img[orig_col * self_rows + orig_row] ) ? _img[orig_col * self_rows + orig_row] : value;
}
}
result[col * rows + row] = value;
if ( mode == kAverage )
result[col * rows + row] /= (float)(rows_factor * cols_factor);
}
}
return result;
}
Image2D Image2D::crop(const BBox2D& bbox, const DistanceUnit_t unit) const
{
if (unit != _meta.unit())
throw larbys("Cannot crop Image2D with BBox with different length unit!");
// Croppin region must be within the image2D
if ( bbox.min_x() < _meta.min_x() || bbox.min_y() < _meta.min_y() ||
bbox.max_x() > _meta.max_x() || bbox.max_y() > _meta.max_y() )
throw larbys("Cropping region contains region outside the image2D!");
size_t min_col = _meta.col(bbox.min_x() + _meta.pixel_width() / 2. );
size_t max_col = _meta.col(bbox.max_x() - _meta.pixel_width() / 2. );
size_t min_row = _meta.row(bbox.min_y() + _meta.pixel_height() / 2. );
size_t max_row = _meta.row(bbox.max_y() - _meta.pixel_height() / 2. );
// *
// std::cout<<"Cropping! Requested:" << std::endl
// << crop_meta.dump() << std::endl
// <<"Original:"<<std::endl
// <<_meta.dump()<<std::endl;
// std::cout<<min_col<< " => " << max_col << " ... " << min_row << " => " << max_row << std::endl;
// std::cout<<_meta.width() << " / " << _meta.cols() << " = " << _meta.pixel_width() << std::endl;
// *
ImageMeta res_meta( (max_col - min_col + 1) * _meta.pixel_width(),
(max_row - min_row + 1) * _meta.pixel_height(),
(max_row - min_row + 1),
(max_col - min_col + 1),
_meta.min_x() + min_col * _meta.pixel_width(),
_meta.min_y() + min_row * _meta.pixel_height(),
_meta.id(), _meta.unit());
std::vector<float> img;
img.resize(res_meta.cols() * res_meta.rows());
size_t column_size = max_row - min_row + 1;
for (size_t col = min_col; col <= max_col; ++col)
memcpy(&(img[(col - min_col)*column_size]), &(_img[_meta.index(min_row, col)]), column_size * sizeof(float));
//std::cout<<"Cropped:" << std::endl << res_meta.dump()<<std::endl;
return Image2D(std::move(res_meta), std::move(img));
}
Image2D Image2D::multiRHS( const Image2D& rhs ) const {
// check multiplication is valid
if ( meta().cols() != rhs.meta().rows() ) {
char oops[500];
sprintf( oops, "Image2D Matrix multiplication not valid. LHS cols (%zu) != RHS rows (%zu).", meta().cols(), rhs.meta().rows() );
throw larbys(oops);
}
// LHS copies internal data
Image2D out( *this );
out.resize( (*this).meta().rows(), rhs.meta().cols() );
for (int r = 0; r < (int)(out.meta().rows()); r++) {
for (int c = 0; c < (int)(out.meta().cols()); c++) {
float val = 0.0;
for (int k = 0; k < (int)(meta().cols()); k++) {
val += pixel( r, k ) * rhs.pixel(k, c);
}
out.set_pixel( r, c, val );
}
}
return out;
}
Image2D Image2D::operator*(const Image2D& rhs) const {
return (*this).multiRHS( rhs );
}
Image2D& Image2D::operator*=( const Image2D& rhs ) {
(*this) = multiRHS( rhs );
return (*this);
}
*/
#include <pybind11/operators.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
;
template <size_t dimension>
void init_tensor_base(pybind11::module m){
using Class = larcv3::Tensor<dimension>;
pybind11::class_<Class> tensor(m, larcv3::as_string<Class>().c_str());
tensor.def(pybind11::init<>());
tensor.def(pybind11::init<const std::vector<size_t> &> ());
tensor.def(pybind11::init<const larcv3::ImageMeta<dimension>& > ());
tensor.def(pybind11::init<const larcv3::ImageMeta<dimension>&, const std::vector<float>&> ());
tensor.def(pybind11::init<const larcv3::Tensor<dimension>&> ());
tensor.def(pybind11::init<pybind11::array_t<float, pybind11::array::c_style>> ());
tensor.def("reset", &Class::reset);
tensor.def("size", &Class::size);
tensor.def("pixel",
(float (Class::*)(const std::vector<size_t> & ) const)(&Class::pixel));
tensor.def("pixel",
(float (Class::*)(size_t ) const)( &Class::pixel));
tensor.def("meta", &Class::meta);
tensor.def("as_vector", &Class::as_vector);
tensor.def("set_pixel",
(void (Class::*)(const std::vector<size_t> &, float ))(&Class::set_pixel));
tensor.def("set_pixel",
(void (Class::*)( size_t, float ))( &Class::set_pixel));
tensor.def("paint", &Class::paint);
tensor.def("threshold", &Class::threshold);
tensor.def("binarize", &Class::binarize);
tensor.def("clear_data", &Class::clear_data);
tensor.def("compress",
(Class (Class::*)(std::array<size_t, dimension> compression, larcv3::PoolType_t)const)(&Class::compress));
tensor.def("compress",
(Class (Class::*)( size_t, larcv3::PoolType_t ) const)( &Class::compress));
tensor.def(pybind11::self += float());
tensor.def(pybind11::self + float());
tensor.def(pybind11::self -= float());
tensor.def(pybind11::self - float());
tensor.def(pybind11::self *= float());
tensor.def(pybind11::self * float());
tensor.def(pybind11::self /= float());
tensor.def(pybind11::self / float());
// tensor.def(pybind11::self += const std::vector<float>&);
// tensor.def(pybind11::self -= const std::vector<float>&);
tensor.def(pybind11::self += pybind11::self);
tensor.def("eltwise",
(void (Class::*)(const Class& rhs ))(&Class::eltwise));
tensor.def("eltwise",
(void (Class::*)( const std::vector<float>&, bool ))(&Class::eltwise));
tensor.def("as_array", &Class::as_array);
}
void init_tensor(pybind11::module m){
init_tensor_base<1>(m);
init_tensor_base<2>(m);
init_tensor_base<3>(m);
init_tensor_base<4>(m);
}
| 34.554483 | 137 | 0.601509 | [
"object",
"shape",
"vector"
] |
862384de4a653e7946d37b0dc32aa4f06bde346d | 1,183 | cpp | C++ | cpp/0001-0099/46. Permutations/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | cpp/0001-0099/46. Permutations/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | cpp/0001-0099/46. Permutations/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | class Solution {
public:
void backtrack(vector<int>& nums, int level, vector<vector<int>>& ans) {
// Reached the maximum depth
if (level == nums.size() - 1) {
ans.push_back(nums);
return;
}
// Every number left to the level-th number are "finalized"
// in the current and subsequent recursive calls
for (int l = level; l < nums.size(); ++l) {
// Swap the two number.
// For example, when nums = [1,2,3], level = 0, we get
// nums = [1,2,3], [2,1,3], and [3,2,1].
// For [2,1,3], level = 1, we get
// nums = [2,1,3], [2,3,1].
// In level 2, the base case is executed, appending
// the result to ans.
// When l = level, it is equivalent to no swap.
swap(nums[l], nums[level]);
backtrack(nums, level+1, ans);
// Revert to the state before swap
swap(nums[l], nums[level]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
backtrack(nums, 0, ans);
return ans;
}
}; | 34.794118 | 76 | 0.486052 | [
"vector"
] |
862645ad103f810bf1aa30f24d528a61530b1836 | 9,241 | cxx | C++ | src/MeteringSDK/MCORE/private/MTimeZoneAndroid.cxx | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 9 | 2016-09-02T17:24:58.000Z | 2021-12-14T19:43:48.000Z | src/MeteringSDK/MCORE/private/MTimeZoneAndroid.cxx | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 1 | 2018-09-06T21:48:42.000Z | 2018-09-06T21:48:42.000Z | src/MeteringSDK/MCORE/private/MTimeZoneAndroid.cxx | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 4 | 2016-09-06T16:54:36.000Z | 2021-12-16T16:15:24.000Z | // File MCORE/private/MTimeZoneAndroid.cxx
#ifndef M__TIMEZONE_USE_ANDROID_IMPLEMENTATION
#error "Do not compile .cxx files directly, they are included!"
#endif
#include <jni.h> // repeat the include purely for the IDE to recognize types
#include "MJavaEnv.h"
static const char s_androidClassName[] = "com/elster/MTools/android/DynamicTimeZone";
static jmethodID s_idConstructor = NULL;
static jmethodID s_idGetStandardName = NULL;
static jmethodID s_idGetDaylightName = NULL;
static jmethodID s_idGetDisplayName = NULL;
static jmethodID s_idClone = NULL;
static jmethodID s_idEquals = NULL;
static jmethodID s_idGetCurrent = NULL;
static jmethodID s_idGetAllTimeZoneNames = NULL;
static jmethodID s_idGetAllTimeZoneDisplayNames = NULL;
static jmethodID s_idGetAllTimeZoneLocalNames = NULL;
static jmethodID s_idIsDST = NULL;
static jmethodID s_idGetUtcToLocalOffset = NULL;
static jmethodID s_idGetLocalToUtcOffset = NULL;
static jclass DoCreateTimeZoneClass(MJavaEnv& env)
{
// Check the last ID, this way we know if all are initialized
//
jclass clazz = env.FindClass(s_androidClassName); // do not cache class object, it is thread dependent!
if ( s_idGetLocalToUtcOffset == NULL ) // but cache methods
{
s_idConstructor = env.GetMethodID(clazz, "<init>", "(Ljava/lang/String;)V");
s_idGetStandardName = env.GetMethodID(clazz, "getStandardName", "()Ljava/lang/String;");
s_idGetDaylightName = env.GetMethodID(clazz, "getDaylightName", "()Ljava/lang/String;");
s_idGetDisplayName = env.GetMethodID(clazz, "getDisplayName", "()Ljava/lang/String;");
s_idClone = env.GetMethodID(clazz, "clone", "()Lcom/elster/MTools/android/DynamicTimeZone;");
s_idEquals = env.GetMethodID(clazz, "equals", "(Lcom/elster/MTools/android/DynamicTimeZone;)Z");
s_idGetCurrent = env.GetStaticMethodID(clazz, "getCurrent", "()Lcom/elster/MTools/android/DynamicTimeZone;");
s_idGetAllTimeZoneNames = env.GetStaticMethodID(clazz, "getAllTimeZoneNames", "()[Ljava/lang/String;");
s_idGetAllTimeZoneDisplayNames = env.GetStaticMethodID(clazz, "getAllTimeZoneDisplayNames", "()[Ljava/lang/String;");
s_idGetAllTimeZoneLocalNames = env.GetStaticMethodID(clazz, "getAllTimeZoneLocalNames", "()[Ljava/lang/String;");
s_idIsDST = env.GetMethodID(clazz, "isDST", "(JZ)Z");
s_idGetUtcToLocalOffset = env.GetMethodID(clazz, "getUtcToLocalOffset", "(J)I");
s_idGetLocalToUtcOffset = env.GetMethodID(clazz, "getLocalToUtcOffset", "(J)I");
}
return clazz;
}
MTimeZone::DynamicTimeZone& MTimeZone::DynamicTimeZone::operator=(const DynamicTimeZone& other)
{
Reset();
M_ASSERT(m_timeZone == NULL);
M_ASSERT(!m_isInitialized);
m_isInitialized = other.m_isInitialized;
if ( other.m_timeZone != NULL )
{
MJavaEnv env;
jobject zone = env->CallObjectMethod(other.m_timeZone, s_idClone);
env.CheckForJavaException();
m_timeZone = env->NewGlobalRef(zone);
}
return *this;
}
bool MTimeZone::DynamicTimeZone::operator==(const DynamicTimeZone& other) const
{
if ( m_isInitialized != other.m_isInitialized || m_timeZone == NULL || other.m_timeZone == NULL ) // easy cases
return false;
// both timezones are Java objects
MJavaEnv env;
jboolean val = env->CallBooleanMethod(m_timeZone, s_idEquals, other.m_timeZone);
env.CheckForJavaException();
return val == JNI_FALSE ? false : true;
}
void MTimeZone::DynamicTimeZone::Reset()
{
m_isInitialized = false;
if ( m_timeZone != NULL )
{
jobject savedTimeZone = m_timeZone;
m_timeZone = NULL;
MJavaEnv env;
env->DeleteGlobalRef(savedTimeZone); // free pointer, mark for garbage collector
env.CheckForJavaException();
}
}
void MTimeZone::DoSetFromLocalJavaObject(MJavaEnv& env, jobject zone)
{
m_dynamic.m_timeZone = env->NewGlobalRef(zone);
m_dynamic.m_isInitialized = true;
jstring name = reinterpret_cast<jstring>(env->CallObjectMethod(zone, s_idGetStandardName));
env.CheckForJavaException();
const char* cStr = env->GetStringUTFChars(name, 0);
m_standardName = cStr;
env->ReleaseStringUTFChars(name, cStr);
env->DeleteLocalRef(name);
name = reinterpret_cast<jstring>(env->CallObjectMethod(zone, s_idGetDaylightName));
env.CheckForJavaException();
cStr = env->GetStringUTFChars(name, 0);
m_daylightName = cStr;
env->ReleaseStringUTFChars(name, cStr);
env->DeleteLocalRef(name);
name = reinterpret_cast<jstring>(env->CallObjectMethod(zone, s_idGetDisplayName));
env.CheckForJavaException();
cStr = env->GetStringUTFChars(name, 0);
m_displayName = cStr;
env->ReleaseStringUTFChars(name, cStr);
env->DeleteLocalRef(name);
const MTime& now = MTime::GetCurrentUtcTime();
m_standardOffset = GetStandardOffsetForTime(now);
m_daylightOffset = GetDaylightOffsetForYear(now.GetYear());
DoComputeRecurringSwitchTimes();
}
bool MTimeZone::DoSetByName(const MStdString& originalName)
{
Clear();
MJavaEnv env;
// Exceptions here are valid cases of bad environment
jclass c = DoCreateTimeZoneClass(env); // throws an exception at failure
jstring originalNameJ = env.NewLocalStringUTF(originalName);
try
{
// Exceptions here are due to a bad name
jobject zone = env->NewObject(c, s_idConstructor, originalNameJ);
env.CheckForJavaException();
DoSetFromLocalJavaObject(env, zone);
return true;
}
catch ( ... )
{
}
return false;
}
void MTimeZone::SetFromCurrentSystem()
{
Clear();
MJavaEnv env;
jclass c = DoCreateTimeZoneClass(env); // throws an exception at failure
jobject zone = env->CallStaticObjectMethod(c, s_idGetCurrent);
env.CheckForJavaException();
DoSetFromLocalJavaObject(env, zone);
}
bool MTimeZone::IsDST(const MTime& t, bool isTimeUtc) const
{
if ( m_dynamic.GetInitialized() )
{
MJavaEnv env;
jlong seconds = static_cast<jlong>(t.GetSecondsSince1970());
jboolean val = env->CallBooleanMethod(m_dynamic.m_timeZone, s_idIsDST, seconds, isTimeUtc ? JNI_TRUE : JNI_FALSE);
env.CheckForJavaException();
return val == JNI_FALSE ? false : true;
}
return DoStaticTestIfDST(t, m_switchToDaylightTime, m_switchToStandardTime, m_standardOffset, m_daylightOffset, isTimeUtc);
}
int MTimeZone::GetUtcToLocalOffset(const MTime& t) const
{
if ( m_dynamic.GetInitialized() )
{
MJavaEnv env;
jlong seconds = static_cast<jlong>(t.GetSecondsSince1970());
jint val = env->CallIntMethod(m_dynamic.m_timeZone, s_idGetUtcToLocalOffset, seconds);
env.CheckForJavaException();
return static_cast<int>(val);
}
int offset = m_standardOffset;
if ( DoStaticTestIfDST(t, m_switchToDaylightTime, m_switchToStandardTime, m_standardOffset, m_daylightOffset, true) )
offset += m_daylightOffset;
return offset;
}
int MTimeZone::GetLocalToUtcOffset(const MTime& t) const
{
if ( m_dynamic.GetInitialized() )
{
MJavaEnv env;
jlong seconds = static_cast<jlong>(t.GetSecondsSince1970());
jint val = env->CallIntMethod(m_dynamic.m_timeZone, s_idGetLocalToUtcOffset, seconds);
env.CheckForJavaException();
return static_cast<int>(val);
}
int offset = -m_standardOffset;
if ( DoStaticTestIfDST(t, m_switchToDaylightTime, m_switchToStandardTime, m_standardOffset, m_daylightOffset, false) )
offset -= m_daylightOffset;
return offset;
}
static void DoFillCollectionWith(MStdStringVector& result, jmethodID* id)
{
MJavaEnv env;
M_ASSERT(result.empty());
jclass c = DoCreateTimeZoneClass(env); // static method, create class
jobjectArray names = reinterpret_cast<jobjectArray>(env->CallStaticObjectMethod(c, *id));
env.CheckForJavaException(); // names will not be returned if there is an exception
int size = env->GetArrayLength(names);
for ( int i = 0; i < size; ++i )
{
jstring jStr = (jstring)env->GetObjectArrayElement(names, i);
env.CheckForJavaException();
const char* cStr = env->GetStringUTFChars(jStr, NULL);
env.CheckForJavaException();
result.push_back(cStr);
env->ReleaseStringUTFChars(jStr, cStr);
env->DeleteLocalRef(jStr);
}
env->DeleteLocalRef(names);
}
MStdStringVector MTimeZone::GetAllTimeZoneNames()
{
MStdStringVector result;
DoFillCollectionWith(result, &s_idGetAllTimeZoneNames); // need to pass an address as at the time of the call s_idGetAllTimeZoneNames might not be initialized
return result;
}
MStdStringVector MTimeZone::GetAllTimeZoneDisplayNames()
{
MStdStringVector result;
DoFillCollectionWith(result, &s_idGetAllTimeZoneDisplayNames); // need to pass an address as at the time of the call s_idGetAllTimeZoneDisplayNames might not be initialized
return result;
}
MStdStringVector MTimeZone::GetAllTimeZoneLocalNames()
{
MStdStringVector result;
DoFillCollectionWith(result, &s_idGetAllTimeZoneLocalNames); // need to pass an address as at the time of the call s_idGetAllTimeZoneLocalNames might not be initialized
return result;
}
| 36.964 | 175 | 0.719403 | [
"object"
] |
862ec8793b9363c2e1ddc78ed4cd6f5e35db337c | 946 | cpp | C++ | mainapp/Classes/Games/MultiplicationBoard/MultiplicationBoardInfo.cpp | JaagaLabs/GLEXP-Team-KitkitSchool | f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0 | [
"Apache-2.0"
] | 45 | 2019-05-16T20:49:31.000Z | 2021-11-05T21:40:54.000Z | mainapp/Classes/Games/MultiplicationBoard/MultiplicationBoardInfo.cpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 10 | 2019-05-17T13:38:22.000Z | 2021-07-31T19:38:27.000Z | mainapp/Classes/Games/MultiplicationBoard/MultiplicationBoardInfo.cpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 29 | 2019-05-16T17:49:26.000Z | 2021-12-30T16:36:24.000Z | //
// MultiplicationBoardInfo.cpp
// KitkitSchool
//
// Created by harunom on 7/22/18.
//
#include "MultiplicationBoardInfo.hpp"
#include "Utils/TodoUtil.h"
std::vector<std::string> MultiplicationBoardInfo::enumerateLevelIDs()
{
vector<std::string> ddLevels;
//tsv 데이터 파일에서 제일 높은 레벨을 가져온다.
int maxLevel = getMaxLevel();
//레벨 추가
for (int i = 1; i <= maxLevel; i++) ddLevels.push_back(TodoUtil::itos(i));
return ddLevels;
}
int MultiplicationBoardInfo::getMaxLevel()
{
string P = "Games/MultiplicationBoard/multiplicationboard_level.tsv";
string S = FileUtils::getInstance()->getStringFromFile(P);
auto data = TodoUtil::readTSV(S);
int rowIndex = 0;
int maxLevel = 1;
while (rowIndex < data.size())
{
int level = TodoUtil::stoi(data[rowIndex++][1]);
if (level > maxLevel)
maxLevel = level;
}
return maxLevel;
}
| 20.12766 | 78 | 0.623679 | [
"vector"
] |
862f11f551a73232ce9821bb7fbac7ae62cb7b7e | 3,501 | cpp | C++ | algorithms-and-data-structures/strings/f_lcs.cpp | nothingelsematters/university | 5561969b1b11678228aaf7e6660e8b1a93d10294 | [
"WTFPL"
] | 1 | 2018-06-03T17:48:50.000Z | 2018-06-03T17:48:50.000Z | algorithms-and-data-structures/strings/f_lcs.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | null | null | null | algorithms-and-data-structures/strings/f_lcs.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | 14 | 2019-04-07T21:27:09.000Z | 2021-12-05T13:37:25.000Z | #include <iostream>
#include <map>
#include <vector>
struct Vertex {
int length;
int suf_link;
int counted = -1;
std::string res;
std::map<char, int> trans;
};
struct SufTree {
SufTree() {
vertexes.push_back(Vertex());
vertexes.back().length = 0;
vertexes.back().suf_link = -1;
}
void add(char c) {
int index = size();
vertexes.push_back(Vertex());
vertexes.back().length = vertexes[last].length + 1;
int parent;
for (parent = last; parent != -1 && vertexes[parent].trans.find(c) ==
vertexes[parent].trans.end(); parent = vertexes[parent].suf_link) {
vertexes[parent].trans[c] = index;
}
if (parent == -1) {
vertexes[index].suf_link = 0;
} else {
int transition = vertexes[parent].trans[c];
if (vertexes[parent].length + 1 == vertexes[transition].length) {
vertexes[index].suf_link = transition;
} else {
int copy = size();
vertexes.push_back(Vertex());
vertexes.back().length = vertexes[parent].length + 1;
vertexes.back().trans = vertexes[transition].trans;
vertexes.back().suf_link = vertexes[transition].suf_link;
while (parent != -1 && vertexes[parent].trans[c] == transition) {
vertexes[parent].trans[c] = copy;
parent = vertexes[parent].suf_link;
}
vertexes[transition].suf_link = vertexes[index].suf_link = copy;
}
}
last = index;
}
size_t size() const { return vertexes.size(); }
Vertex& operator[](size_t i) { return vertexes[i]; }
int last = 0;
private:
std::vector<Vertex> vertexes;
};
std::pair<size_t, std::string> st_lcs_dfs(SufTree& st, size_t v, size_t quantity, size_t depth = 0) {
size_t accept = 0;
size_t const full = (1 << quantity) - 1;
std::string loc_max;
char transition;
for (auto i: st[v].trans) {
if (i.first < quantity) {
accept |= 1 << i.first;
} else {
size_t q;
std::string s;
if (st[i.second].counted == -1) {
auto tmp = st_lcs_dfs(st, i.second, quantity, depth + 1);
q = tmp.first;
s = std::move(tmp.second);
} else {
q = st[i.second].counted;
s = st[i.second].res;
}
if (q == full) {
if (s.size() >= loc_max.size()) {
transition = i.first;
loc_max = std::move(s);
loc_max.push_back(i.first);
}
} else {
accept |= q;
}
}
}
if (loc_max.size() > 0) {
st[v].counted = full;
st[v].res = loc_max;
return {full, std::move(loc_max)};
}
st[v].counted = accept;
return {accept, ""};
}
int main() {
size_t quantity;
std::cin >> quantity;
SufTree st;
char divider[quantity];
for (int i = 0; i < quantity; ++i) {
std::string str;
std::cin >> str;
for (auto c: str) {
st.add(c);
}
divider[i] = i;
st.add(i);
}
std::string str = st_lcs_dfs(st, 0, quantity).second;
for (auto i = str.rbegin(); i != str.rend(); ++i) {
std::cout << *i;
}
return 0;
}
| 29.420168 | 101 | 0.48529 | [
"vector"
] |
863eb72c5afb4c96ecd7053a3b3a76ea6ccc89c3 | 9,697 | cpp | C++ | lib/curlpipe/http.cpp | joewiz/curlpipe | e969d69bd156869f0ebdee85eed7cc8529c3e10e | [
"MIT"
] | 4 | 2019-03-08T19:56:41.000Z | 2022-03-11T09:55:48.000Z | lib/curlpipe/http.cpp | joewiz/curlpipe | e969d69bd156869f0ebdee85eed7cc8529c3e10e | [
"MIT"
] | 5 | 2018-11-22T16:11:32.000Z | 2018-11-23T13:01:32.000Z | lib/curlpipe/http.cpp | xquery/curlscript | b5a745ae481f578044b6c6016442b2f4620a0156 | [
"MIT"
] | 1 | 2018-11-22T15:49:26.000Z | 2018-11-22T15:49:26.000Z | /******************************************************************************
* curlpipe - https://github.com/xquery/curlpipe
******************************************************************************
* Copyright (c) 2017-2018 James Fuller <jim.fuller@webcomposite.com>
*
* 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 <cwchar>
#include <cmath>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <map>
#include <cassert>
#include <curl/curl.h>
#include "log.h"
#define SUPPORT_NETRC 1
#ifdef _WIN32
#define WAITMS(x) Sleep(x)
#else
/* Portable sleep for platforms other than Windows. */
#define WAITMS(x) \
struct timeval wait = { 0, (x) * 1000 }; \
(void)select(0, NULL, NULL, NULL, &wait);
#endif
using namespace std;
CURLM *curlm;
struct CURLMsg *m;
int http_status_code,rc;
struct curl_slist *headers = NULL;
int init_http(){
DLOG_S(INFO) << "init http";
curlm = curl_multi_init();
headers = curl_slist_append(headers, "");
return CURLE_OK;
}
int cleanup_http(){
DLOG_S(INFO) << "cleanup http";
curl_multi_cleanup(curlm);
curl_global_cleanup();
return CURLE_OK;
}
static size_t headerCallback(void *ptr, size_t size, size_t nmemb, void *stream){
DLOG_S(INFO) << "response header:" << (char *)ptr;
return size * nmemb;
}
static size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp) {
((std::string *) userp)->append((char *) contents, size * nmemb);
return size * nmemb;
}
int http_set_options(CURL *c, CURLU *urlp, vector <tuple<string,string>> httpheaders){
DLOG_S(INFO) << "set http opts";
char *url;
rc = curl_url_get(urlp, CURLUPART_URL, &url, 0);
DLOG_S(INFO) << "set url to: " << url;
curl_easy_setopt(c, CURLOPT_CURLU, urlp);
#ifdef SUPPORT_NETRC
curl_easy_setopt(c, CURLOPT_NETRC,CURL_NETRC_OPTIONAL);
#endif
curl_easy_setopt(c, CURLOPT_VERBOSE, 0L);
curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, headerCallback);
#ifndef NDEBUG
curl_easy_setopt(c, CURLOPT_VERBOSE, 1L);
#endif
curl_easy_setopt(c, CURLOPT_HEADER, 0L);
for ( const auto& i : httpheaders ) {
string header = get<0>(i) + ": " + get<1>(i);
DLOG_S(INFO) << "set http header: " << header;
headers = curl_slist_append(headers, header.c_str());
}
curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(c, CURLOPT_USERAGENT, "curlpipe via curl");
curl_easy_setopt(c, CURLOPT_FAILONERROR, 1L);
curl_easy_setopt(c, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(c, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, writeCallback);
//REMOVE
curl_easy_setopt(c, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(c, CURLOPT_SSL_VERIFYHOST, 0L);
// curl_easy_setopt(c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// curl_easy_setopt(c, CURLOPT_USERPWD, "test:test");
return CURLE_OK;
}
int exec(){
int still_running = -1;
curl_multi_perform(curlm, &still_running);
CURLMcode mc;
int numfds;
while (still_running) {
mc = curl_multi_wait(curlm, NULL, 0, 1000, &numfds);
if(mc != CURLM_OK) {
LOG_S(ERROR) << "curl_multi_wait() failed, code " << mc;
break;
}
curl_multi_perform(curlm, &still_running);
}
CURL *eh = nullptr;
CURLMsg *msg = nullptr;
CURLcode return_code;
int msgs_left = 0;
while ((msg = curl_multi_info_read(curlm, &msgs_left))) {
if (msg->msg == CURLMSG_DONE) {
eh = msg->easy_handle;
http_status_code=0;
const char *url;
curl_easy_getinfo(eh, CURLINFO_RESPONSE_CODE, &http_status_code);
curl_easy_getinfo(eh, CURLINFO_EFFECTIVE_URL, &url);
return_code = msg->data.result;
if(return_code!=CURLE_OK) {
LOG_S(ERROR) << "url: " << url;
LOG_S(ERROR) << "http status code: " << http_status_code;
LOG_S(ERROR) << "error code: " << curl_easy_strerror(msg->data.result);
continue;
}
if(http_status_code==200) {
DLOG_S(INFO) << "HTTP Status Code: " << http_status_code;
} else {
LOG_S(ERROR) << "HTTP Status Code: " << http_status_code;
}
curl_multi_remove_handle(curlm, eh);
curl_easy_cleanup(eh);
}else{
LOG_S(ERROR) << "error: after curl_multi_info_read(), CURLMsg=" << msg->msg;}
}
return 0;
}
string http_get(CURLU *urlp, vector <tuple<string,string>> httpheaders){
std::ostringstream ss;
string readBuffer;
int handle_count;
CURL *c = NULL;
c = curl_easy_init();
if (c) {
http_set_options(c, urlp, httpheaders);
// curl_easy_setopt(c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// curl_easy_setopt(c, CURLOPT_USERPWD, "test:test");
curl_easy_setopt(c, CURLOPT_HTTPGET, 1L);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &readBuffer);
curl_multi_add_handle(curlm, c);
DLOG_S(INFO) << "perform HTTP GET";
int result = exec();
if(result==0){
ss << readBuffer;
}else{
//error
}
}
return ss.str();
}
string http_post(CURLU *urlp, string payload, vector <tuple<string,string>> httpheaders){
std::ostringstream ss;
string readBuffer;
CURL *c = NULL;
c = curl_easy_init();
if (c) {
//ungodly hack (for now)
//headers = NULL;
// if(payload.find("{") == 0){
// headers = curl_slist_append(headers, "Content-Type:application/json");
// }else if(payload.find("<") == 0){
// headers = curl_slist_append(headers, "Content-Type:application/xml");
// }else if(payload.find("&") != std::string::npos){
// headers = curl_slist_append(headers, "Content-Type:application/x-www-form-urlencoded");
// }else {
// headers = curl_slist_append(headers, "Content-Type:text/plain");
// }
// curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(c, CURLOPT_POST, 1L);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(c, CURLOPT_POSTFIELDS, payload.c_str());
http_set_options(c,urlp, httpheaders);
curl_multi_add_handle(curlm, c);
DLOG_S(INFO) << "perform HTTP POST";
int result = exec();
if(result==0){
ss << readBuffer;
}else{
//error
}
}
return ss.str();
}
string http_delete(CURLU *urlp, vector <tuple<string,string>> httpheaders){
std::ostringstream ss;
string readBuffer;
CURL *c = NULL;
c = curl_easy_init();
if (c) {
http_set_options(c,urlp, httpheaders);
curl_easy_setopt(c, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(c, CURLOPT_WRITEDATA, &readBuffer);
curl_multi_add_handle(curlm, c);
DLOG_S(INFO) << "perform HTTP DELETE";
int result = exec();
if(result==0){
ss << readBuffer;
}else{
//error
}
}
return ss.str();
}
string http_put(CURLU *urlp, string payload, vector <tuple<string,string>> httpheaders){
std::ostringstream ss;
string readBuffer;
CURL *c = NULL;
c = curl_easy_init();
if (c) {
http_set_options(c,urlp, httpheaders);
//ungodly hack (for now)
//headers = NULL;
// if(payload.find("{") == 0){
// headers = curl_slist_append(headers, "Content-Type:application/json");
// }else if(payload.find("<") == 0){
// headers = curl_slist_append(headers, "Content-Type:application/xml");
//
// }else if(payload.find("&") != std::string::npos){
// headers = curl_slist_append(headers, "Content-Type:application/x-www-form-urlencoded");
// }else {
// headers = curl_slist_append(headers, "Content-Type:text/plain");
// }
// curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(c, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(c, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(c, CURLOPT_POSTFIELDS, payload.c_str());
curl_multi_add_handle(curlm, c);
DLOG_S(INFO) << "perform HTTP PUT";
int result = exec();
if(result==0){
ss << readBuffer;
}else{
//error
}
}
return ss.str();
} | 31.080128 | 101 | 0.611529 | [
"vector"
] |
8641f3bc3a9ee0eda1eb9f999e3bb93d7e7d1de6 | 451 | cpp | C++ | EOlymp/00008.cpp | vdshk/algos | 8896c9edd30225acbdb51fa2e9760c0cc4adf307 | [
"MIT"
] | null | null | null | EOlymp/00008.cpp | vdshk/algos | 8896c9edd30225acbdb51fa2e9760c0cc4adf307 | [
"MIT"
] | null | null | null | EOlymp/00008.cpp | vdshk/algos | 8896c9edd30225acbdb51fa2e9760c0cc4adf307 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define len(a) (int)a.size()
using namespace std;
typedef vector<int> vint;
typedef long double ld;
typedef long long ll;
typedef string str;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
int s = sqrt(n);
cout << 2 * n + s + ((n + s - 1) / s);
} | 18.791667 | 42 | 0.611973 | [
"vector"
] |
86448a17e46dda4d94698fad1eb6145f7d8f2ea1 | 31,579 | cxx | C++ | arrows/serialize/protobuf/tests/test_convert_protobuf.cxx | chetnieter/kwiver | cebc8156b5109d423ffac34f6e4bb442d36c24ab | [
"BSD-3-Clause"
] | 176 | 2015-07-31T23:33:37.000Z | 2022-03-21T23:42:44.000Z | arrows/serialize/protobuf/tests/test_convert_protobuf.cxx | chetnieter/kwiver | cebc8156b5109d423ffac34f6e4bb442d36c24ab | [
"BSD-3-Clause"
] | 1,276 | 2015-05-03T01:21:27.000Z | 2022-03-31T15:32:20.000Z | arrows/serialize/protobuf/tests/test_convert_protobuf.cxx | chetnieter/kwiver | cebc8156b5109d423ffac34f6e4bb442d36c24ab | [
"BSD-3-Clause"
] | 85 | 2015-01-25T05:13:38.000Z | 2022-01-14T14:59:37.000Z | // This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
#include <gtest/gtest.h>
#include <arrows/serialize/protobuf/convert_protobuf.h>
#include <arrows/serialize/protobuf/convert_protobuf_point.h>
#include <vital/types/activity.h>
#include <vital/types/activity_type.h>
#include <vital/types/bounding_box.h>
#include <vital/types/detected_object.h>
#include <vital/types/detected_object_set.h>
#include <vital/types/detected_object_type.h>
#include <vital/types/geo_polygon.h>
#include <vital/types/geodesy.h>
#include <vital/types/image_container.h>
#include <vital/types/metadata.h>
#include <vital/types/metadata_tags.h>
#include <vital/types/metadata_traits.h>
#include <vital/types/object_track_set.h>
#include <vital/types/polygon.h>
#include <vital/types/timestamp.h>
#include <vital/types/track.h>
#include <vital/types/track_set.h>
#include <vital/vital_types.h>
#include <vital/types/protobuf/activity.pb.h>
#include <vital/types/protobuf/activity_type.pb.h>
#include <vital/types/protobuf/bounding_box.pb.h>
#include <vital/types/protobuf/detected_object_type.pb.h>
#include <vital/types/protobuf/detected_object.pb.h>
#include <vital/types/protobuf/detected_object_set.pb.h>
#include <vital/types/protobuf/geo_point.pb.h>
#include <vital/types/protobuf/geo_polygon.pb.h>
#include <vital/types/protobuf/image.pb.h>
#include <vital/types/protobuf/metadata.pb.h>
#include <vital/types/protobuf/metadata.pb.h>
#include <vital/types/protobuf/object_track_set.pb.h>
#include <vital/types/protobuf/object_track_state.pb.h>
#include <vital/types/protobuf/polygon.pb.h>
#include <vital/types/protobuf/string.pb.h>
#include <vital/types/protobuf/timestamp.pb.h>
#include <vital/types/protobuf/track.pb.h>
#include <vital/types/protobuf/track_set.pb.h>
#include <vital/types/protobuf/track_state.pb.h>
#include <sstream>
#include <iostream>
namespace kasp = kwiver::arrows::serialize::protobuf;
// ----------------------------------------------------------------------------
int main(int argc, char** argv)
{
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, activity_default )
{
// This tests the behavior when participants
// and activity_type are set to NULL
auto const act = kwiver::vital::activity{};
auto act_proto = kwiver::protobuf::activity{};
// Set some data to check that fields are overwritten
auto const at_in = std::make_shared< kwiver::vital::activity_type >();
auto const start_in = kwiver::vital::timestamp { 1, 1 };
auto const end_in = kwiver::vital::timestamp { 2, 2 };
auto const part_in = std::make_shared< kwiver::vital::object_track_set >();
auto act_dser =
kwiver::vital::activity{ 5, "label", 3.14, at_in, start_in, end_in, part_in };
kasp::convert_protobuf( act, act_proto );
kasp::convert_protobuf( act_proto, act_dser );
// Check members
EXPECT_EQ( act.id(), act_dser.id() );
EXPECT_EQ( act.label(), act_dser.label() );
EXPECT_EQ( act.type(), act_dser.type() );
EXPECT_EQ( act.participants(), act_dser.participants() );
EXPECT_DOUBLE_EQ( act.confidence(), act_dser.confidence() );
// Timestamps are invalid so can't do a direct comparison
auto const start = act.start();
auto const end = act.end();
auto const start_dser = act_dser.start();
auto const end_dser = act_dser.end();
EXPECT_EQ( start.get_time_seconds(), start_dser.get_time_seconds() );
EXPECT_EQ( start.get_frame(), start_dser.get_frame() );
EXPECT_EQ( start.get_time_domain_index(), start_dser.get_time_domain_index() );
EXPECT_EQ( end.get_time_seconds(), end_dser.get_time_seconds() );
EXPECT_EQ( end.get_frame(), end_dser.get_frame() );
EXPECT_EQ( end.get_time_domain_index(), end_dser.get_time_domain_index() );
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, activity )
{
auto at_sptr = std::make_shared< kwiver::vital::activity_type >();
at_sptr->set_score( "first", 1 );
at_sptr->set_score( "second", 10 );
at_sptr->set_score( "third", 101 );
// Create object_track_set consisting of
// 1 track_sptr with 10 track states
auto track_sptr = kwiver::vital::track::create();
track_sptr->set_id( 1 );
for ( int i = 0; i < 10; i++ )
{
auto const bbox =
kwiver::vital::bounding_box_d{ 10.0 + i, 10.0 + i, 20.0 + i, 20.0 + i };
auto dobj_dot_sptr = std::make_shared< kwiver::vital::detected_object_type >();
dobj_dot_sptr->set_score( "key", i / 10.0 );
auto const dobj_sptr =
std::make_shared< kwiver::vital::detected_object >( bbox, i / 10.0, dobj_dot_sptr );
auto const ots_sptr =
std::make_shared< kwiver::vital::object_track_state >( i, i, dobj_sptr );
track_sptr->append( ots_sptr );
}
auto const tracks = std::vector< kwiver::vital::track_sptr >{ track_sptr };
auto const obj_trk_set_sptr =
std::make_shared< kwiver::vital::object_track_set >( tracks );
// Now both timestamps
auto const start = kwiver::vital::timestamp{ 1, 1 };
auto const end = kwiver::vital::timestamp{ 2, 2 };
// Now construct activity
auto const act =
kwiver::vital::activity{ 5, "test_label", 3.1415, at_sptr, start, end, obj_trk_set_sptr };
auto act_proto = kwiver::protobuf::activity{};
auto act_dser = kwiver::vital::activity{};
kasp::convert_protobuf( act, act_proto );
kasp::convert_protobuf( act_proto, act_dser );
// Now check equality
EXPECT_EQ( act.id(), act_dser.id() );
EXPECT_EQ( act.label(), act_dser.label() );
EXPECT_DOUBLE_EQ( act.confidence(), act_dser.confidence() );
EXPECT_EQ( act.start(), act_dser.start() );
EXPECT_EQ( act.end(), act_dser.end() );
// Check values in the retrieved class map
auto const act_type = act.type();
auto const act_type_dser = act_dser.type();
EXPECT_EQ( act_type->size(), act_type_dser->size() );
EXPECT_DOUBLE_EQ( act_type->score( "first" ), act_type_dser->score( "first" ) );
EXPECT_DOUBLE_EQ( act_type->score( "second" ), act_type_dser->score( "second" ) );
EXPECT_DOUBLE_EQ( act_type->score( "third" ), act_type_dser->score( "third" ) );
// Now the object_track_set
auto const parts = act.participants();
auto const parts_dser = act_dser.participants();
EXPECT_EQ( parts->size(), parts_dser->size() );
auto const trk = parts->get_track( 1 );
auto const trk_dser = parts_dser->get_track( 1 );
// Iterate over the track_states
for ( int i = 0; i < 10; i++ )
{
auto const trk_state_sptr = *trk->find( i );
auto const trk_state_dser_sptr = *trk_dser->find( i );
EXPECT_EQ( trk_state_sptr->frame(), trk_state_dser_sptr->frame() );
auto const obj_trk_state_sptr =
kwiver::vital::object_track_state::downcast( trk_state_sptr );
auto const obj_trk_state_dser_sptr =
kwiver::vital::object_track_state::downcast( trk_state_dser_sptr );
EXPECT_EQ( obj_trk_state_sptr->time(), obj_trk_state_dser_sptr->time() );
auto const do_ser_sptr = obj_trk_state_sptr->detection();
auto const do_dser_sptr = obj_trk_state_dser_sptr->detection();
EXPECT_EQ( do_ser_sptr->bounding_box(), do_dser_sptr->bounding_box() );
EXPECT_EQ( do_ser_sptr->confidence(), do_dser_sptr->confidence() );
auto const dot_ser_sptr = do_ser_sptr->type();
auto const dot_dser_sptr = do_dser_sptr->type();
if ( dot_ser_sptr )
{
EXPECT_EQ( dot_ser_sptr->size(), dot_dser_sptr->size() );
EXPECT_EQ( dot_ser_sptr->score( "key" ), dot_dser_sptr->score( "key" ) );
}
}
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, bounding_box )
{
kwiver::vital::bounding_box_d bbox { 1, 2, 3, 4 };
kwiver::protobuf::bounding_box bbox_proto;
kwiver::vital::bounding_box_d bbox_dser { 11, 12, 13, 14 };
kasp::convert_protobuf( bbox, bbox_proto );
kasp::convert_protobuf( bbox_proto, bbox_dser );
EXPECT_EQ( bbox, bbox_dser );
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, detected_object_type )
{
kwiver::vital::detected_object_type dot;
dot.set_score( "first", 1 );
dot.set_score( "second", 10 );
dot.set_score( "third", 101 );
dot.set_score( "last", 121 );
kwiver::protobuf::detected_object_type dot_proto;
kwiver::vital::detected_object_type dot_dser;
kasp::convert_protobuf( dot, dot_proto );
kasp::convert_protobuf( dot_proto, dot_dser );
EXPECT_EQ( dot.size(), dot_dser.size() );
auto o_it = dot.begin();
auto d_it = dot_dser.begin();
for (size_t i = 0; i < dot.size(); ++i )
{
EXPECT_EQ( *(o_it->first), *(d_it->first) );
EXPECT_EQ( o_it->second, d_it->second );
++o_it;
++d_it;
}
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, activity_type )
{
kwiver::vital::activity_type at;
at.set_score( "first", 1 );
at.set_score( "second", 10 );
at.set_score( "third", 101 );
at.set_score( "last", 121 );
kwiver::protobuf::activity_type at_proto;
kwiver::vital::activity_type at_dser;
kasp::convert_protobuf( at, at_proto );
kasp::convert_protobuf( at_proto, at_dser );
EXPECT_EQ( at.size(), at_dser.size() );
auto o_it = at.begin();
auto d_it = at_dser.begin();
for (size_t i = 0; i < at.size(); ++i )
{
EXPECT_EQ( *(o_it->first), *(d_it->first) );
EXPECT_EQ( o_it->second, d_it->second );
++o_it;
++d_it;
}
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, detected_object )
{
auto dot = std::make_shared<kwiver::vital::detected_object_type>();
dot->set_score( "first", 1 );
dot->set_score( "second", 10 );
dot->set_score( "third", 101 );
dot->set_score( "last", 121 );
kwiver::vital::detected_object dobj( kwiver::vital::bounding_box_d{ 1, 2, 3, 4 }, 3.14159, dot );
dobj.set_detector_name( "test_detector" );
dobj.set_index( 1234 );
kwiver::protobuf::detected_object dobj_proto;
kwiver::vital::detected_object dobj_dser( kwiver::vital::bounding_box_d{ 11, 12, 13, 14 }, 13.14159, dot );
kasp::convert_protobuf( dobj, dobj_proto );
kasp::convert_protobuf( dobj_proto, dobj_dser );
EXPECT_EQ( dobj.bounding_box(), dobj_dser.bounding_box() );
EXPECT_EQ( dobj.index(), dobj_dser.index() );
EXPECT_EQ( dobj.confidence(), dobj_dser.confidence() );
EXPECT_EQ( dobj.detector_name(), dobj_dser.detector_name() );
dot = dobj.type();
if (dot)
{
auto dot_dser = dobj_dser.type();
EXPECT_EQ( dot->size(), dot_dser->size() );
auto o_it = dot->begin();
auto d_it = dot_dser->begin();
for (size_t i = 0; i < dot->size(); ++i )
{
EXPECT_EQ( *(o_it->first), *(d_it->first) );
EXPECT_EQ( o_it->second, d_it->second );
++o_it;
++d_it;
}
}
}
// ---------------------------------------------------------------------------
TEST( convert_protobuf, detected_object_set )
{
kwiver::vital::detected_object_set dos;
for ( int i=0; i < 10; i++ )
{
auto dot_sptr = std::make_shared<kwiver::vital::detected_object_type>();
dot_sptr->set_score( "first", 1 + i );
dot_sptr->set_score( "second", 10 + i );
dot_sptr->set_score( "third", 101 + i );
dot_sptr->set_score( "last", 121 + i );
auto det_object_sptr = std::make_shared< kwiver::vital::detected_object>(
kwiver::vital::bounding_box_d{ 1.0 + i, 2.0 + i, 3.0 + i, 4.0 + i }, 3.14159, dot_sptr );
det_object_sptr->set_detector_name( "test_detector" );
det_object_sptr->set_index( 1234 + i);
dos.add( det_object_sptr );
}
kwiver::protobuf::detected_object_set dos_proto;
kwiver::vital::detected_object_set dos_dser;
kasp::convert_protobuf( dos, dos_proto );
kasp::convert_protobuf( dos_proto, dos_dser );
for ( int i = 0; i < 10; i++ )
{
auto ser_do_sptr = dos.at(i);
auto dser_do_sptr = dos_dser.at(i);
EXPECT_EQ( ser_do_sptr->bounding_box(), dser_do_sptr->bounding_box() );
EXPECT_EQ( ser_do_sptr->index(), dser_do_sptr->index() );
EXPECT_EQ( ser_do_sptr->confidence(), dser_do_sptr->confidence() );
EXPECT_EQ( ser_do_sptr->detector_name(), dser_do_sptr->detector_name() );
auto ser_dot_sptr = ser_do_sptr->type();
auto dser_dot_sptr = dser_do_sptr->type();
if ( ser_dot_sptr )
{
EXPECT_EQ( ser_dot_sptr->size(),dser_dot_sptr->size() );
auto ser_it = ser_dot_sptr->begin();
auto dser_it = dser_dot_sptr->begin();
for ( size_t j = 0; j < ser_dot_sptr->size(); ++j )
{
EXPECT_EQ( *(ser_it->first), *(ser_it->first) );
EXPECT_EQ( dser_it->second, dser_it->second );
}
}
} // end for
}
// ----------------------------------------------------------------------------
TEST (convert_protobuf, timestamp)
{
kwiver::vital::timestamp tstamp{1, 1};
kwiver::protobuf::timestamp ts_proto;
kwiver::vital::timestamp ts_dser;
kasp::convert_protobuf( tstamp, ts_proto );
kasp::convert_protobuf( ts_proto, ts_dser );
EXPECT_EQ (tstamp, ts_dser);
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, image)
{
kwiver::vital::image img{200, 300, 3};
char* cp = static_cast< char* >(img.memory()->data() );
for ( size_t i = 0; i < img.size(); ++i )
{
*cp++ = i;
}
kwiver::vital::image_container_sptr img_container =
std::make_shared< kwiver::vital::simple_image_container >( img );
kwiver::protobuf::image image_proto;
kwiver::vital::image_container_sptr img_dser;
kasp::convert_protobuf( img_container, image_proto );
kasp::convert_protobuf( image_proto, img_dser );
// Check the content of images
EXPECT_TRUE ( kwiver::vital::equal_content( img_container->get_image(), img_dser->get_image()) );
}
// ----------------------------------------------------------------------------
TEST (convert_protobuf, string)
{
std::string str("Test string");
kwiver::protobuf::string str_proto;
std::string str_dser;
kasp::convert_protobuf( str, str_proto );
kasp::convert_protobuf( str_proto, str_dser );
EXPECT_EQ (str, str_dser);
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, polygon )
{
kwiver::vital::polygon obj;
obj.push_back( 100, 100 );
obj.push_back( 400, 100 );
obj.push_back( 400, 400 );
obj.push_back( 100, 400 );
kwiver::protobuf::polygon obj_proto;
kwiver::vital::polygon obj_dser;
kasp::convert_protobuf( obj, obj_proto );
kasp::convert_protobuf( obj_proto, obj_dser );
EXPECT_EQ( obj.num_vertices(), obj_dser.num_vertices() );
EXPECT_EQ( obj.at(0), obj_dser.at(0) );
EXPECT_EQ( obj.at(1), obj_dser.at(1) );
EXPECT_EQ( obj.at(2), obj_dser.at(2) );
EXPECT_EQ( obj.at(3), obj_dser.at(3) );
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, geo_point_2d )
{
// --- 2d variant ---
kwiver::vital::geo_point::geo_2d_point_t geo( 42.50, 73.54 );
kwiver::vital::geo_point obj( geo, kwiver::vital::SRID::lat_lon_WGS84 );
kwiver::protobuf::geo_point obj_proto;
kwiver::vital::geo_point::geo_2d_point_t geo_dser( 0, 0 );
kwiver::vital::geo_point obj_dser( geo_dser, 0 );
kasp::convert_protobuf( obj, obj_proto );
kasp::convert_protobuf( obj_proto, obj_dser );
EXPECT_EQ( obj.location(), obj_dser.location() );
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, geo_point_raw )
{
// --- 3d variant ---
kwiver::vital::geo_point::geo_3d_point_t geo( 42.50, 73.54, 16.33 );
kwiver::vital::geo_point obj( geo, kwiver::vital::SRID::lat_lon_WGS84 );
kwiver::protobuf::geo_point obj_proto;
kwiver::vital::geo_point::geo_3d_point_t geo_dser( 0, 0, 0 );
kwiver::vital::geo_point obj_dser( geo_dser, 0 );
kasp::convert_protobuf( obj, obj_proto );
kasp::convert_protobuf( obj_proto, obj_dser );
EXPECT_EQ( obj.location(), obj_dser.location() );
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, geo_polygon )
{
kwiver::vital::polygon raw_obj;
raw_obj.push_back( 100, 100 );
raw_obj.push_back( 400, 100 );
raw_obj.push_back( 400, 400 );
raw_obj.push_back( 100, 400 );
kwiver::vital::geo_polygon obj( raw_obj, kwiver::vital::SRID::lat_lon_WGS84 );
kwiver::protobuf::geo_polygon obj_proto;
kwiver::vital::geo_polygon obj_dser;
kasp::convert_protobuf( obj, obj_proto );
kasp::convert_protobuf( obj_proto, obj_dser );
kwiver::vital::polygon dser_raw_obj = obj_dser.polygon();
EXPECT_EQ( raw_obj.num_vertices(), dser_raw_obj.num_vertices() );
EXPECT_EQ( raw_obj.at(0), dser_raw_obj.at(0) );
EXPECT_EQ( raw_obj.at(1), dser_raw_obj.at(1) );
EXPECT_EQ( raw_obj.at(2), dser_raw_obj.at(2) );
EXPECT_EQ( raw_obj.at(3), dser_raw_obj.at(3) );
EXPECT_EQ( obj_dser.crs(), kwiver::vital::SRID::lat_lon_WGS84 );
}
// ----------------------------------------------------------------------------
TEST( convert_protobuf, metadata )
{
kwiver::vital::metadata meta;
meta.add< kwiver::vital::VITAL_META_METADATA_ORIGIN >( "test-source" );
meta.add< kwiver::vital::VITAL_META_UNIX_TIMESTAMP >( 12345678 );
meta.add< kwiver::vital::VITAL_META_SENSOR_VERTICAL_FOV >( 12345.678 );
{
kwiver::vital::geo_point::geo_2d_point_t geo_2d{ 42.50, 73.54 };
kwiver::vital::geo_point pt{ geo_2d, kwiver::vital::SRID::lat_lon_WGS84 };
meta.add< kwiver::vital::VITAL_META_FRAME_CENTER >( pt );
}
{
kwiver::vital::geo_point::geo_3d_point_t geo{ 42.50, 73.54, 16.33 };
kwiver::vital::geo_point pt{ geo, kwiver::vital::SRID::lat_lon_WGS84 };
meta.add< kwiver::vital::VITAL_META_FRAME_CENTER >( pt );
}
{
kwiver::vital::polygon raw_obj;
raw_obj.push_back( 100, 100 );
raw_obj.push_back( 400, 100 );
raw_obj.push_back( 400, 400 );
raw_obj.push_back( 100, 400 );
kwiver::vital::geo_polygon poly( raw_obj,
kwiver::vital::SRID::lat_lon_WGS84 );
meta.add< kwiver::vital::VITAL_META_CORNER_POINTS >( poly );
}
kwiver::protobuf::metadata obj_proto;
kwiver::vital::metadata meta_dser;
kasp::convert_protobuf( meta, obj_proto );
kasp::convert_protobuf( obj_proto, meta_dser );
//+ test for equality - TBD
}
//----------------------------------------------------------------------------
TEST( convert_protobuf, track_state )
{
kwiver::vital::track_state trk_state{ 1 };
kwiver::protobuf::track_state proto_trk_state;
kwiver::vital::track_state dser_trk_state;
kasp::convert_protobuf( trk_state, proto_trk_state );
kasp::convert_protobuf( proto_trk_state, dser_trk_state );
EXPECT_EQ ( trk_state, dser_trk_state );
}
//----------------------------------------------------------------------------
TEST( convert_protobuf, object_track_state )
{
auto dot_sptr = std::make_shared< kwiver::vital::detected_object_type >();
dot_sptr->set_score( "first", 1 );
dot_sptr->set_score( "second", 10 );
dot_sptr->set_score( "third", 101 );
dot_sptr->set_score( "last", 121 );
auto dobj_sptr = std::make_shared< kwiver::vital::detected_object>(
kwiver::vital::bounding_box_d{ 1, 2, 3, 4 },
3.14159265, dot_sptr );
dobj_sptr->set_detector_name( "test_detector" );
dobj_sptr->set_index( 1234 );
kwiver::vital::object_track_state obj_trk_state( 1, 1, dobj_sptr );
obj_trk_state.set_image_point( ::kwiver::vital::point_2d( 123, 321 ) );
obj_trk_state.set_track_point( ::kwiver::vital::point_3d( 123, 234, 345 ) );
kwiver::protobuf::object_track_state proto_obj_trk_state;
kwiver::vital::object_track_state obj_trk_state_dser;
// do conversion to and fro
kasp::convert_protobuf( obj_trk_state, proto_obj_trk_state );
kasp::convert_protobuf( proto_obj_trk_state, obj_trk_state_dser );
auto do_sptr = obj_trk_state.detection();
auto do_sptr_dser = obj_trk_state_dser.detection();
EXPECT_EQ( do_sptr->bounding_box(), do_sptr_dser->bounding_box() );
EXPECT_EQ( do_sptr->index(), do_sptr_dser->index() );
EXPECT_EQ( do_sptr->confidence(), do_sptr_dser->confidence() );
EXPECT_EQ( do_sptr->detector_name(), do_sptr_dser->detector_name() );
auto dot_sptr_dser = do_sptr_dser->type();
if ( dot_sptr )
{
EXPECT_EQ( dot_sptr->size(), dot_sptr_dser->size() );
auto it = dot_sptr->begin();
auto it_dser = dot_sptr_dser->begin();
for ( size_t i = 0; i < dot_sptr->size(); ++i )
{
EXPECT_EQ( *(it->first), *(it_dser->first) );
EXPECT_EQ( it->second, it_dser->second );
}
}
EXPECT_EQ(obj_trk_state.time(), obj_trk_state_dser.time());
EXPECT_EQ(obj_trk_state.frame(), obj_trk_state_dser.frame());
EXPECT_EQ( obj_trk_state.image_point().value(), obj_trk_state_dser.image_point().value() );
EXPECT_EQ( obj_trk_state.track_point().value(), obj_trk_state_dser.track_point().value() );
}
// ---------------------------------------------------------------------------
TEST( convert_protobuf, track )
{
// test track with object track state
kwiver::protobuf::track proto_obj_trk;
auto trk_dser=kwiver::vital::track::create();
auto trk = kwiver::vital::track::create();
trk->set_id(1);
for (int i=0; i<10; i++)
{
auto dot = std::make_shared<kwiver::vital::detected_object_type>();
dot->set_score( "first", 1 );
dot->set_score( "second", 10 );
dot->set_score( "third", 101 );
dot->set_score( "last", 121 );
auto dobj_sptr = std::make_shared< kwiver::vital::detected_object>(
kwiver::vital::bounding_box_d{ 1, 2, 3, 4 },
3.14159265, dot );
dobj_sptr->set_detector_name( "test_detector" );
dobj_sptr->set_index( 1234 );
auto obj_trk_state_sptr = std::make_shared< kwiver::vital::object_track_state >
( i, i, dobj_sptr );
bool insert_success = trk->insert( obj_trk_state_sptr );
if ( !insert_success )
{
std::cerr << "Failed to insert object track state" << std::endl;
}
}
// Convert track to protobuf and back
kasp::convert_protobuf( trk, proto_obj_trk );
kasp::convert_protobuf( proto_obj_trk, trk_dser );
// Check track id
EXPECT_EQ( trk->id(), trk_dser->id() );
for ( int i=0; i<10; i++ )
{
auto trk_state_sptr = *trk->find( i );
auto dser_trk_state_sptr = *trk_dser->find( i );
EXPECT_EQ( trk_state_sptr->frame(), dser_trk_state_sptr->frame() );
auto obj_trk_state_sptr = kwiver::vital::object_track_state::downcast( trk_state_sptr );
auto dser_obj_trk_state_sptr = kwiver::vital::object_track_state::
downcast( dser_trk_state_sptr );
auto ser_do_sptr = obj_trk_state_sptr->detection();
auto dser_do_sptr = dser_obj_trk_state_sptr->detection();
EXPECT_EQ( ser_do_sptr->bounding_box(), dser_do_sptr->bounding_box() );
EXPECT_EQ( ser_do_sptr->index(), dser_do_sptr->index() );
EXPECT_EQ( ser_do_sptr->confidence(), dser_do_sptr->confidence() );
EXPECT_EQ( ser_do_sptr->detector_name(), dser_do_sptr->detector_name() );
auto ser_dot_sptr = ser_do_sptr->type();
auto dser_dot_sptr = dser_do_sptr->type();
if ( ser_dot_sptr )
{
EXPECT_EQ( ser_dot_sptr->size(),dser_dot_sptr->size() );
auto ser_it = ser_dot_sptr->begin();
auto dser_it = dser_dot_sptr->begin();
for ( size_t j = 0; j < ser_dot_sptr->size(); ++j )
{
EXPECT_EQ( *(ser_it->first), *(ser_it->first) );
EXPECT_EQ( dser_it->second, dser_it->second );
}
}
}
// test track with track state
kwiver::protobuf::track proto_trk;
trk = kwiver::vital::track::create();
trk_dser = kwiver::vital::track::create();
trk->set_id( 2 );
for ( int i = 0; i < 10; i++ )
{
auto trk_state_sptr = std::make_shared< kwiver::vital::track_state>( i );
bool insert_success = trk->insert( trk_state_sptr );
if ( !insert_success )
{
std::cerr << "Failed to insert track state" << std::endl;
}
}
kasp::convert_protobuf( trk, proto_trk );
kasp::convert_protobuf( proto_trk, trk_dser );
EXPECT_EQ( trk->id(), trk_dser->id() );
for ( int i=0; i<10; i++ )
{
auto obj_trk_state_sptr = *trk->find( i );
auto dser_trk_state_sptr = *trk_dser->find( i );
EXPECT_EQ( obj_trk_state_sptr->frame(), dser_trk_state_sptr->frame() );
}
}
// ---------------------------------------------------------------------------
TEST( convert_protobuf, track_set )
{
kwiver::protobuf::track_set proto_trk_set;
auto trk_set_sptr = std::make_shared< kwiver::vital::track_set >();
auto trk_set_sptr_dser = std::make_shared< kwiver::vital::track_set >();
for ( kwiver::vital::track_id_t trk_id=1; trk_id<5; ++trk_id )
{
auto trk = kwiver::vital::track::create();
trk->set_id( trk_id );
for ( int i=trk_id*10; i < ( trk_id+1 )*10; i++ )
{
auto trk_state_sptr = std::make_shared< kwiver::vital::track_state>( i );
bool insert_success = trk->insert( trk_state_sptr );
if ( !insert_success )
{
std::cerr << "Failed to insert track state" << std::endl;
}
}
trk_set_sptr->insert(trk);
}
kasp::convert_protobuf( trk_set_sptr, proto_trk_set );
kasp::convert_protobuf( proto_trk_set, trk_set_sptr_dser );
for ( kwiver::vital::track_id_t trk_id=1; trk_id<5; ++trk_id )
{
auto trk = trk_set_sptr->get_track( trk_id );
auto trk_dser = trk_set_sptr_dser->get_track( trk_id );
EXPECT_EQ( trk->id(), trk_dser->id() );
for ( int i=trk_id*10; i < ( trk_id+1 )*10; i++ )
{
auto obj_trk_state_sptr = *trk->find( i );
auto dser_trk_state_sptr = *trk_dser->find( i );
EXPECT_EQ( obj_trk_state_sptr->frame(), dser_trk_state_sptr->frame() );
}
}
}
// ---------------------------------------------------------------------------
TEST( convert_protobuf, object_track_set )
{
kwiver::protobuf::object_track_set proto_obj_trk_set;
auto obj_trk_set_sptr = std::make_shared< kwiver::vital::object_track_set >();
auto obj_trk_set_sptr_dser = std::make_shared< kwiver::vital::object_track_set >();
for ( kwiver::vital::track_id_t trk_id=1; trk_id<5; ++trk_id )
{
auto trk = kwiver::vital::track::create();
trk->set_id( trk_id );
for ( int i=trk_id*10; i < ( trk_id+1 )*10; i++ )
{
auto dot = std::make_shared<kwiver::vital::detected_object_type>();
dot->set_score( "first", 1 );
dot->set_score( "second", 10 );
dot->set_score( "third", 101 );
dot->set_score( "last", 121 );
auto dobj_sptr = std::make_shared< kwiver::vital::detected_object>(
kwiver::vital::bounding_box_d{ 1, 2, 3, 4 },
3.14159265, dot );
dobj_sptr->set_detector_name( "test_detector" );
dobj_sptr->set_index( 1234 );
auto obj_trk_state_sptr = std::make_shared< kwiver::vital::object_track_state >
( i, i, dobj_sptr );
bool insert_success = trk->insert( obj_trk_state_sptr );
if ( !insert_success )
{
std::cerr << "Failed to insert object track state" << std::endl;
}
}
obj_trk_set_sptr->insert(trk);
}
kasp::convert_protobuf( obj_trk_set_sptr, proto_obj_trk_set );
kasp::convert_protobuf( proto_obj_trk_set, obj_trk_set_sptr_dser );
for ( kwiver::vital::track_id_t trk_id=1; trk_id<5; ++trk_id )
{
auto trk = obj_trk_set_sptr->get_track( trk_id );
auto trk_dser = obj_trk_set_sptr_dser->get_track( trk_id );
EXPECT_EQ( trk->id(), trk_dser->id() );
for ( int i=trk_id*10; i < ( trk_id+1 )*10; i++ )
{
auto trk_state_sptr = *trk->find( i );
auto dser_trk_state_sptr = *trk_dser->find( i );
EXPECT_EQ( trk_state_sptr->frame(), dser_trk_state_sptr->frame() );
auto obj_trk_state_sptr = kwiver::vital::object_track_state::downcast( trk_state_sptr );
auto dser_obj_trk_state_sptr = kwiver::vital::object_track_state::
downcast( dser_trk_state_sptr );
auto ser_do_sptr = obj_trk_state_sptr->detection();
auto dser_do_sptr = dser_obj_trk_state_sptr->detection();
EXPECT_EQ( ser_do_sptr->bounding_box(), dser_do_sptr->bounding_box() );
EXPECT_EQ( ser_do_sptr->index(), dser_do_sptr->index() );
EXPECT_EQ( ser_do_sptr->confidence(), dser_do_sptr->confidence() );
EXPECT_EQ( ser_do_sptr->detector_name(), dser_do_sptr->detector_name() );
auto ser_dot_sptr = ser_do_sptr->type();
auto dser_dot_sptr = dser_do_sptr->type();
if ( ser_dot_sptr )
{
EXPECT_EQ( ser_dot_sptr->size(),dser_dot_sptr->size() );
auto ser_it = ser_dot_sptr->begin();
auto dser_it = dser_dot_sptr->begin();
for ( size_t j = 0; j < ser_dot_sptr->size(); ++j )
{
EXPECT_EQ( *(ser_it->first), *(ser_it->first) );
EXPECT_EQ( dser_it->second, dser_it->second );
}
}
}
}
}
// ----------------------------------------------------------------------------
TEST (convert_protobuf, covariance)
{
#define TEST_COV(T, ... ) \
do { \
::kwiver::vital::T::matrix_type val; \
val << __VA_ARGS__; \
::kwiver::vital::T obj( val ); \
::kwiver::protobuf::covariance obj_proto; \
::kwiver::vital::T obj_dser; \
\
kasp::convert_protobuf( obj, obj_proto ); \
kasp::convert_protobuf( obj_proto, obj_dser ); \
\
EXPECT_EQ( obj, obj_dser ); \
} while (0)
TEST_COV( covariance_2d, 1, 2, 3, 4 );
TEST_COV( covariance_2f, 1, 2, 3, 4 );
TEST_COV( covariance_3d, 1, 2, 3, 4, 5, 6, 7, 8, 9 );
TEST_COV( covariance_3f, 1, 2, 3, 4, 5, 6, 7, 8, 9 );
TEST_COV( covariance_4d, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 );
TEST_COV( covariance_4f, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 );
#undef TEST_COV
}
// ----------------------------------------------------------------------------
TEST (convert_protobuf, points)
{
{
::kwiver::vital::point_2i obj( 1, 2 );
::kwiver::protobuf::point_i obj_proto;
::kwiver::vital::point_2i obj_dser;
kasp::convert_protobuf( obj, obj_proto );
kasp::convert_protobuf( obj_proto, obj_dser );
EXPECT_EQ( obj.value(), obj_dser.value() );
}
#define TEST_POINT(T, ... ) \
do { \
::kwiver::vital::T obj( __VA_ARGS__ ); \
::kwiver::protobuf::point_d obj_proto; \
::kwiver::vital::T obj_dser; \
\
kasp::convert_protobuf( obj, obj_proto ); \
kasp::convert_protobuf( obj_proto, obj_dser ); \
\
EXPECT_EQ( obj.value(), obj_dser.value() ); \
} while (0)
TEST_POINT( point_2d, 1, 2 );
TEST_POINT( point_2f, 1, 2 );
TEST_POINT( point_3d, 1, 2, 3 );
TEST_POINT( point_3f, 1, 2, 3 );
TEST_POINT( point_4d, 1, 2, 3, 4 );
TEST_POINT( point_4f, 1, 2, 3, 4 );
#undef TEST_POINT
}
| 34.287731 | 109 | 0.617689 | [
"object",
"vector",
"3d"
] |
86457ee4591d1908e2b4490f19ef938d9fcfcf94 | 15,670 | cpp | C++ | dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/visualization/tools/real_sense_viewer.cpp | hddxds/scripts_from_gi | afb8977c001b860335f9062464e600d9115ea56e | [
"Apache-2.0"
] | 2 | 2019-04-10T14:04:52.000Z | 2019-05-29T03:41:58.000Z | software/SLAM/ygz_slam_ros/Thirdparty/PCL/visualization/tools/real_sense_viewer.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | null | null | null | software/SLAM/ygz_slam_ros/Thirdparty/PCL/visualization/tools/real_sense_viewer.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | 1 | 2021-12-20T06:54:41.000Z | 2021-12-20T06:54:41.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2015-, Open Perception, 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 the name of the copyright holder(s) 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 <iostream>
#include <boost/format.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/common/time.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/io/io_exception.h>
#include <pcl/io/real_sense_grabber.h>
#include <pcl/visualization/pcl_visualizer.h>
using namespace pcl::console;
void
printHelp (int, char **argv)
{
std::cout << std::endl;
std::cout << "****************************************************************************" << std::endl;
std::cout << "* *" << std::endl;
std::cout << "* REAL SENSE VIEWER - Usage Guide *" << std::endl;
std::cout << "* *" << std::endl;
std::cout << "****************************************************************************" << std::endl;
std::cout << std::endl;
std::cout << "Usage: " << argv[0] << " [Options] device_id" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << std::endl;
std::cout << " --help, -h : Show this help" << std::endl;
std::cout << " --list, -l : List connected RealSense devices and supported modes" << std::endl;
std::cout << " --mode <id> : Use capture mode <id> from the list of supported modes" << std::endl;
std::cout << std::endl;
std::cout << "Keyboard commands:" << std::endl;
std::cout << std::endl;
std::cout << " When the focus is on the viewer window, the following keyboard commands" << std::endl;
std::cout << " are available:" << std::endl;
std::cout << " * t/T : increase or decrease depth data confidence threshold" << std::endl;
std::cout << " * k : enable next temporal filtering method" << std::endl;
std::cout << " * s : save the last grabbed cloud to disk" << std::endl;
std::cout << " * h : print the list of standard PCL viewer commands" << std::endl;
std::cout << std::endl;
std::cout << "Notes:" << std::endl;
std::cout << std::endl;
std::cout << " The device to grab data from is selected using device_id argument. It" << std::endl;
std::cout << " could be either:" << std::endl;
std::cout << " * serial number (e.g. 231400041-03)" << std::endl;
std::cout << " * device index (e.g. #2 for the second connected device)" << std::endl;
std::cout << std::endl;
std::cout << " If device_id is not given, then the first available device will be used." << std::endl;
std::cout << std::endl;
std::cout << " If capture mode is not given, then the grabber will try to enable both" << std::endl;
std::cout << " depth and color streams at VGA resolution and 30 Hz framerate. If this" << std::endl;
std::cout << " particular mode is not available, the one that most closely matches this" << std::endl;
std::cout << " specification will be chosen." << std::endl;
std::cout << std::endl;
}
void
printDeviceList ()
{
typedef boost::shared_ptr<pcl::RealSenseGrabber> RealSenseGrabberPtr;
std::vector<RealSenseGrabberPtr> grabbers;
std::cout << "Connected devices: ";
boost::format fmt ("\n #%i %s");
boost::format fmt_dm ("\n %2i) %d Hz %dx%d Depth");
boost::format fmt_dcm ("\n %2i) %d Hz %dx%d Depth %dx%d Color");
while (true)
{
try
{
grabbers.push_back (RealSenseGrabberPtr (new pcl::RealSenseGrabber));
std::cout << boost::str (fmt % grabbers.size () % grabbers.back ()->getDeviceSerialNumber ());
std::vector<pcl::RealSenseGrabber::Mode> xyz_modes = grabbers.back ()->getAvailableModes (true);
std::cout << "\n Depth modes:";
if (xyz_modes.size ())
for (size_t i = 0; i < xyz_modes.size (); ++i)
std::cout << boost::str (fmt_dm % (i + 1) % xyz_modes[i].fps % xyz_modes[i].depth_width % xyz_modes[i].depth_height);
else
{
std::cout << " none";
}
std::vector<pcl::RealSenseGrabber::Mode> xyzrgba_modes = grabbers.back ()->getAvailableModes (false);
std::cout << "\n Depth + color modes:";
if (xyz_modes.size ())
for (size_t i = 0; i < xyzrgba_modes.size (); ++i)
{
const pcl::RealSenseGrabber::Mode& m = xyzrgba_modes[i];
std::cout << boost::str (fmt_dcm % (i + xyz_modes.size () + 1) % m.fps % m.depth_width % m.depth_height % m.color_width % m.color_height);
}
else
std::cout << " none";
}
catch (pcl::io::IOException& e)
{
break;
}
}
if (grabbers.size ())
std::cout << std::endl;
else
std::cout << "none" << std::endl;
}
template <typename PointT>
class RealSenseViewer
{
public:
typedef pcl::PointCloud<PointT> PointCloudT;
RealSenseViewer (pcl::RealSenseGrabber& grabber)
: grabber_ (grabber)
, viewer_ ("RealSense Viewer")
, window_ (3)
, threshold_ (6)
, temporal_filtering_ (pcl::RealSenseGrabber::RealSense_None)
{
viewer_.setCameraFieldOfView (0.785398); // approximately 45 degrees
viewer_.setCameraPosition (0, 0, 0, 0, 0, 1, 0, 1, 0);
viewer_.registerKeyboardCallback (&RealSenseViewer::keyboardCallback, *this);
viewer_.registerPointPickingCallback (&RealSenseViewer::pointPickingCallback, *this);
}
~RealSenseViewer ()
{
connection_.disconnect ();
}
void
run ()
{
boost::function<void (const typename PointCloudT::ConstPtr&)> f = boost::bind (&RealSenseViewer::cloudCallback, this, _1);
connection_ = grabber_.registerCallback (f);
grabber_.start ();
printMode (grabber_.getMode ());
viewer_.setSize (grabber_.getMode ().depth_width, grabber_.getMode ().depth_height);
while (!viewer_.wasStopped ())
{
if (new_cloud_)
{
boost::mutex::scoped_lock lock (new_cloud_mutex_);
if (!viewer_.updatePointCloud (new_cloud_, "cloud"))
{
viewer_.addPointCloud (new_cloud_, "cloud");
viewer_.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "cloud");
}
displaySettings ();
last_cloud_ = new_cloud_;
new_cloud_.reset ();
}
viewer_.spinOnce (1, true);
}
grabber_.stop ();
}
private:
void
cloudCallback (typename PointCloudT::ConstPtr cloud)
{
if (!viewer_.wasStopped ())
{
boost::mutex::scoped_lock lock (new_cloud_mutex_);
new_cloud_ = cloud;
}
}
void
keyboardCallback (const pcl::visualization::KeyboardEvent& event, void*)
{
if (event.keyDown ())
{
if (event.getKeyCode () == 'w' || event.getKeyCode () == 'W')
{
window_ += event.getKeyCode () == 'w' ? 1 : -1;
if (window_ < 1)
window_ = 1;
pcl::console::print_info ("Temporal filtering window size: ");
pcl::console::print_value ("%i\n", window_);
grabber_.enableTemporalFiltering (temporal_filtering_, window_);
}
if (event.getKeyCode () == 't' || event.getKeyCode () == 'T')
{
threshold_ += event.getKeyCode () == 't' ? 1 : -1;
if (threshold_ < 0)
threshold_ = 0;
if (threshold_ > 15)
threshold_ = 15;
pcl::console::print_info ("Confidence threshold: ");
pcl::console::print_value ("%i\n", threshold_);
grabber_.setConfidenceThreshold (threshold_);
}
if (event.getKeyCode () == 'k')
{
pcl::console::print_info ("Temporal filtering: ");
switch (temporal_filtering_)
{
case pcl::RealSenseGrabber::RealSense_None:
{
temporal_filtering_ = pcl::RealSenseGrabber::RealSense_Median;
pcl::console::print_value ("median\n");
break;
}
case pcl::RealSenseGrabber::RealSense_Median:
{
temporal_filtering_ = pcl::RealSenseGrabber::RealSense_Average;
pcl::console::print_value ("average\n");
break;
}
case pcl::RealSenseGrabber::RealSense_Average:
{
temporal_filtering_ = pcl::RealSenseGrabber::RealSense_None;
pcl::console::print_value ("none\n");
break;
}
}
grabber_.enableTemporalFiltering (temporal_filtering_, window_);
}
if (event.getKeyCode () == 's')
{
boost::format fmt ("RS_%s_%u.pcd");
std::string fn = boost::str (fmt % grabber_.getDeviceSerialNumber ().c_str () % last_cloud_->header.stamp);
pcl::io::savePCDFileBinaryCompressed (fn, *last_cloud_);
pcl::console::print_info ("Saved point cloud: ");
pcl::console::print_value (fn.c_str ());
pcl::console::print_info ("\n");
}
displaySettings ();
}
}
void
pointPickingCallback (const pcl::visualization::PointPickingEvent& event, void*)
{
float x, y, z;
event.getPoint (x, y, z);
pcl::console::print_info ("Picked point at ");
pcl::console::print_value ("%.3f", x); pcl::console::print_info (", ");
pcl::console::print_value ("%.3f", y); pcl::console::print_info (", ");
pcl::console::print_value ("%.3f\n", z);
}
void
displaySettings ()
{
const int dx = 5;
const int dy = 14;
const int fs = 10;
boost::format name_fmt ("text%i");
const char* TF[] = {"off", "median", "average"};
std::vector<boost::format> entries;
// Framerate
entries.push_back (boost::format ("framerate: %.1f") % grabber_.getFramesPerSecond ());
// Confidence threshold
entries.push_back (boost::format ("confidence threshold: %i") % threshold_);
// Temporal filter settings
std::string tfs = boost::str (boost::format (", window size %i") % window_);
entries.push_back (boost::format ("temporal filtering: %s%s") % TF[temporal_filtering_] % (temporal_filtering_ == pcl::RealSenseGrabber::RealSense_None ? "" : tfs));
for (size_t i = 0; i < entries.size (); ++i)
{
std::string name = boost::str (name_fmt % i);
std::string entry = boost::str (entries[i]);
if (!viewer_.updateText (entry, dx, dy + i * (fs + 2), fs, 1.0, 1.0, 1.0, name))
viewer_.addText (entry, dx, dy + i * (fs + 2), fs, 1.0, 1.0, 1.0, name);
}
}
void
printMode (const pcl::RealSenseGrabber::Mode& mode)
{
print_info ("Capturing mode: ");
print_value ("%i", mode.fps);
print_info (" Hz ");
print_value ("%dx%d ", mode.depth_width, mode.depth_height);
print_info ("Depth");
if (pcl::traits::has_color<PointT>::value)
{
print_value (" %dx%d ", mode.color_width, mode.color_height);
print_info ("Color");
}
print_value ("\n");
}
pcl::RealSenseGrabber& grabber_;
pcl::visualization::PCLVisualizer viewer_;
boost::signals2::connection connection_;
int window_;
int threshold_;
pcl::RealSenseGrabber::TemporalFilteringType temporal_filtering_;
mutable boost::mutex new_cloud_mutex_;
typename PointCloudT::ConstPtr new_cloud_;
typename PointCloudT::ConstPtr last_cloud_;
};
int
main (int argc, char** argv)
{
print_info ("Viewer for RealSense devices (run with --help for more information)\n", argv[0]);
if (find_switch (argc, argv, "--help") || find_switch (argc, argv, "-h"))
{
printHelp (argc, argv);
return (0);
}
if (find_switch (argc, argv, "--list") || find_switch (argc, argv, "-l"))
{
printDeviceList ();
return (0);
}
unsigned int mode_id = 0;
bool with_mode = find_argument(argc, argv, "--mode") != -1;
parse_argument(argc, argv, "--mode", mode_id);
std::string device_id;
if (argc == 1 || // no arguments
(argc == 3 && with_mode)) // single argument, and it is --mode <id>
{
device_id = "";
print_info ("Creating a grabber for the first available device\n");
}
else
{
device_id = argv[argc - 1];
print_info ("Creating a grabber for device "); print_value ("%s\n", device_id.c_str ());
}
try
{
pcl::RealSenseGrabber grabber (device_id);
std::vector<pcl::RealSenseGrabber::Mode> xyz_modes = grabber.getAvailableModes (true);
std::vector<pcl::RealSenseGrabber::Mode> xyzrgba_modes = grabber.getAvailableModes (false);
if (mode_id == 0)
{
RealSenseViewer<pcl::PointXYZRGBA> viewer (grabber);
viewer.run ();
}
else if (mode_id <= xyz_modes.size ())
{
grabber.setMode (xyz_modes[mode_id - 1], true);
RealSenseViewer<pcl::PointXYZ> viewer (grabber);
viewer.run ();
}
else if (mode_id <= xyz_modes.size () + xyzrgba_modes.size ())
{
grabber.setMode (xyzrgba_modes[mode_id - xyz_modes.size () - 1], true);
RealSenseViewer<pcl::PointXYZRGBA> viewer (grabber);
viewer.run ();
}
else
{
print_error ("Requested a mode (%i) that is not in the list of supported by this device\n", mode_id);
return (1);
}
}
catch (pcl::io::IOException& e)
{
print_error ("Failed to create a grabber: %s\n", e.what ());
return (1);
}
return (0);
}
| 38.126521 | 171 | 0.575175 | [
"vector"
] |
864a30f9d793dd969440e9597496bed9d50ebadb | 37,673 | cpp | C++ | src/las.cpp | Helios-vmg/cppserialization | 01333f20758e3ef62dbb78fd182f86e6b403ff8a | [
"Unlicense"
] | 1 | 2016-04-28T10:03:24.000Z | 2016-04-28T10:03:24.000Z | src/las.cpp | Helios-vmg/cppserialization | 01333f20758e3ef62dbb78fd182f86e6b403ff8a | [
"Unlicense"
] | null | null | null | src/las.cpp | Helios-vmg/cppserialization | 01333f20758e3ef62dbb78fd182f86e6b403ff8a | [
"Unlicense"
] | 1 | 2020-06-27T01:39:14.000Z | 2020-06-27T01:39:14.000Z | #include "stdafx.h"
#include "las.h"
#include "util.h"
#include "variable_formatter.h"
#include "typehash.h"
#include "GenericException.h"
#ifndef HAVE_PRECOMPILED_HEADERS
#include <fstream>
#include <sstream>
#include <array>
#include <iomanip>
#include <cctype>
#endif
std::mt19937_64 rng;
std::uint64_t random_function_name = 0;
void get_randomized_function_name(std::string &name, const char *custom_part){
if (name.size())
return;
if (!random_function_name)
random_function_name = rng();
std::stringstream stream;
stream << custom_part << std::hex << std::setw(16) << std::setfill('0') << random_function_name;
name = stream.str();
}
#define DEFINE_get_X_function_name(x) \
std::string x##_function_name; \
std::string get_##x##_function_name(){ \
get_randomized_function_name(x##_function_name, #x "_"); \
return x##_function_name; \
}
DEFINE_get_X_function_name(get_metadata)
DEFINE_get_X_function_name(allocator)
DEFINE_get_X_function_name(constructor)
DEFINE_get_X_function_name(rollbacker)
DEFINE_get_X_function_name(is_serializable)
DEFINE_get_X_function_name(dynamic_cast)
DEFINE_get_X_function_name(allocate_pointer)
DEFINE_get_X_function_name(categorize_cast)
std::string IntegerType::get_type_string() const{
std::stringstream stream;
stream << (this->signedness ? 's' : 'u') << (8 << this->size);
return stream.str();
}
std::string FloatingPointType::get_type_string() const{
const char *s;
switch (this->precision) {
case FloatingPointPrecision::Float:
s = "float";
break;
case FloatingPointPrecision::Double:
s = "double";
break;
default:
break;
}
return s;
}
std::string ArrayType::get_type_string() const{
std::stringstream stream;
stream << "std::array< " << this->inner->get_type_string() << ", " << this->length << ">";
return stream.str();
}
void ArrayType::generate_deserializer(std::ostream &stream, const char *deserializer_name, const char *pointer_name) const{
stream << "{\n";
this->output(stream);
stream << " *temp = (";
this->output(stream);
stream << " *)" << pointer_name << ";\n"
"for (size_t i = 0; i != " << this->length << "; i++){\n";
this->generate_deserializer(stream, deserializer_name, pointer_name);
stream << "}\n"
"}\n";
}
template <typename T>
void generate_for_collection(variable_formatter &format, const std::string &next_name, const std::initializer_list<T> &list, generate_pointer_enumerator_callback_t &callback){
bool any = false;
std::string accum;
auto subcallback = [&any, &accum, &callback](const std::string &input, CallMode mode) -> std::string{
if (mode == CallMode::TransformAndReturn)
return callback(input, mode);
if (mode == CallMode::AddVerbatim){
any = true;
accum += input;
return std::string();
}
any = true;
accum += callback(input, CallMode::TransformAndReturn);
return std::string();
};
for (auto &i : list)
i->generate_pointer_enumerator(subcallback, next_name);
if (any)
callback(format << "contents" << accum, CallMode::AddVerbatim);
}
void Type::generate_deserializer(std::ostream &stream, const char *deserializer_name, const char *pointer_name) const{
stream << "{\n";
this->output(stream);
stream << " *temp = (";
this->output(stream);
stream << " *)" << pointer_name << ";\n"
"new (temp) ";
this->output(stream);
stream << ";\n"
<< deserializer_name << ".deserialize(*temp);\n"
"}\n";
}
void Type::generate_rollbacker(std::ostream &stream, const char *pointer_name) const{
stream << "{}";
}
void Type::generate_is_serializable(std::ostream &stream) const{
stream << "return " << (this->get_is_serializable() ? "true" : "false") << ";\n";
}
void ArrayType::generate_pointer_enumerator(generate_pointer_enumerator_callback_t &callback, const std::string &this_name) const{
static const char *format =
"for (size_t {index} = 0; {index} != {length}; {index}++){{"
"{contents}"
"}}";
variable_formatter vf(format);
auto index = get_unique_varname();
vf << "index" << index << "length" << this->length;
std::string next_name = variable_formatter("({name})[{index}]") << "name" << this_name << "index" << index;
generate_for_collection(vf, next_name, { this->inner }, callback);
}
void PointerType::generate_pointer_enumerator(generate_pointer_enumerator_callback_t &callback, const std::string &this_name) const{
std::stringstream stream;
if (!this->inner->is_serializable())
stream << "::get_object_node(" << this_name << ", static_get_type_id<" << this->inner << ">::value)";
else
stream << "::get_object_node((Serializable *)" << this_name << ")";
callback(stream.str(), CallMode::TransformAndAdd);
}
void StdSmartPtrType::generate_pointer_enumerator(generate_pointer_enumerator_callback_t &callback, const std::string &this_name) const{
std::stringstream stream;
if (!this->inner->is_serializable())
stream << "::get_object_node((" << this_name << ").get(), static_get_type_id<" << this->inner << ">::value)";
else
stream << "::get_object_node((Serializable *)(" << this_name << ").get())";
callback(stream.str(), CallMode::TransformAndAdd);
}
void SequenceType::generate_pointer_enumerator(generate_pointer_enumerator_callback_t &callback, const std::string &this_name) const{
static const char *format =
"for (const auto &{index} : {name}){{"
"{contents}"
"}}";
variable_formatter vf(format);
auto index = get_unique_varname();
vf << "index" << index << "name" << this_name;
generate_for_collection(vf, index, { this->inner }, callback);
}
void AssociativeArrayType::generate_pointer_enumerator(generate_pointer_enumerator_callback_t &callback, const std::string &this_name) const{
static const char *format =
"for (const auto &{index} : {name}){{"
"{contents}"
"}}";
variable_formatter vf(format);
auto index = get_unique_varname();
vf << "index" << index << "name" << this_name;
generate_for_collection(vf, index, { this->first, this->second }, callback);
}
unsigned UserClass::next_type_id = 0;
struct autoset{
bool &b;
autoset(bool &b): b(b){
b = true;
}
~autoset(){
this->b = false;
}
};
void UserClass::add_headers(std::set<std::string> &set){
if (this->adding_headers)
return;
autoset b(this->adding_headers);
for (auto &bc : this->base_classes)
bc.Class->add_headers(set);
for (auto &e : this->elements){
auto member = std::dynamic_pointer_cast<ClassMember>(e);
if (!member)
continue;
member->add_headers(set);
}
}
void UserClass::generate_header(std::ostream &stream) const{
stream << "class " << this->name << " : ";
if (this->base_classes.size() > 0){
bool first = true;
for (auto &base : this->base_classes){
if (!first)
stream << ", ";
else
first = false;
stream << "public ";
if (base.Virtual)
stream << "virtual ";
stream << base.Class->name;
}
}else{
stream << "public ";
if (this->inherit_Serializable_virtually)
stream << "virtual ";
stream << "Serializable";
}
stream << "{\n";
for (auto &el : this->elements)
stream << "" << el << (el->needs_semicolon() ? ";\n" : "\n");
static const char *format =
"public:\n"
"{name}(DeserializerStream &);\n"
"virtual ~{name}();\n"
"virtual void get_object_node(std::vector<ObjectNode> &) const override;\n"
"virtual void serialize(SerializerStream &) const override;\n"
"virtual std::uint32_t get_type_id() const override;\n"
"virtual TypeHash get_type_hash() const override;\n"
"virtual std::shared_ptr<SerializableMetadata> get_metadata() const override;\n"
"static std::shared_ptr<SerializableMetadata> static_get_metadata();\n"
"virtual void rollback_deserialization() override;\n"
"}};\n";
stream << (std::string)(variable_formatter(format) << "name" << this->name);
}
template <typename T>
size_t string_length(const T *str){
size_t ret = 0;
for (; str[ret]; ret++);
return ret;
}
template <typename T>
size_t string_length(const std::basic_string<T> &str){
return str.size();
}
template <typename T, typename T2, typename T3>
std::basic_string<T> replace_all(std::basic_string<T> s, const T2 &search, const T3 &replacement){
size_t pos = 0;
auto length = string_length(search);
while ((pos = s.find(search)) != s.npos){
auto s2 = s.substr(0, pos);
s2 += replacement;
s2 += s.substr(pos + length);
s = s2;
}
return s;
}
void UserClass::generate_get_object_node2(std::ostream &stream) const{
for (auto &i : this->base_classes)
stream << i.Class->get_name() << "::get_object_node(v);\n";
auto callback = [&stream](const std::string &s, CallMode mode){
std::string addend;
if (mode != CallMode::AddVerbatim){
auto replaced = replace_all(s, "(*this).", "this->");
addend = variable_formatter("v.push_back({0});\n") << "0" << replaced;
if (mode == CallMode::TransformAndReturn)
return addend;
}else
addend = s;
stream << addend;
return std::string();
};
this->generate_pointer_enumerator(callback, "*this");
}
void UserClass::generate_pointer_enumerator(generate_pointer_enumerator_callback_t &callback, const std::string &this_name) const{
auto next_name = "(" + this_name + ").";
for (auto &e : this->elements){
auto casted = std::dynamic_pointer_cast<ClassMember>(e);
if (!casted)
continue;
auto type = casted->get_type();
type->generate_pointer_enumerator(callback, next_name + casted->get_name());
}
}
void UserClass::generate_serialize(std::ostream &stream) const{
for (auto &b : this->base_classes)
stream << b.Class->get_name() << "::serialize(ss);\n";
for (auto &e : this->elements){
auto casted = std::dynamic_pointer_cast<ClassMember>(e);
if (!casted)
continue;
stream << "ss.serialize(this->" << casted->get_name() << ");\n";
}
}
void UserClass::generate_get_type_hash(std::ostream &stream) const{
stream << "return " << this->root->get_name() << "_id_hashes[" << (this->get_type_id() - 1) << "].second;";
}
void UserClass::generate_get_metadata(std::ostream &stream) const{
stream << "return " << get_get_metadata_function_name() << "();\n";
}
void UserClass::generate_deserializer(std::ostream &stream) const{
bool first = true;
for (auto &b : this->base_classes){
if (!first)
stream << ", ";
else{
stream << ": ";
first = false;
}
stream << b.Class->get_name() << "(ds)\n";
}
for (auto &e : this->elements){
auto casted = std::dynamic_pointer_cast<ClassMember>(e);
if (!casted)
continue;
if (!first)
stream << ", ";
else{
stream << ": ";
first = false;
}
stream << casted->get_name() << "(";
auto type = casted->get_type();
if (std::dynamic_pointer_cast<UserClass>(type))
stream << "ds";
else
stream << "proxy_constructor<" << type << ">(ds)";
stream << ")\n";
}
stream << "{}";
}
void UserClass::generate_deserializer(std::ostream &stream, const char *deserializer_name, const char *pointer_name) const{
stream << "{\n";
this->output(stream);
stream << " *temp = (";
this->output(stream);
stream << " *)" << pointer_name << ";\n"
"new (temp) ";
this->output(stream);
stream << "(" << deserializer_name << ");\n"
"}\n";
}
void UserClass::generate_rollbacker(std::ostream &stream, const char *pointer_name) const{
stream << "{\n";
this->output(stream);
stream << " *temp = (";
this->output(stream);
stream << " *)" << pointer_name << ";\n"
"temp->rollback_deserialization();\n"
"}\n";
}
bool UserClass::get_is_serializable() const{
return true;
}
void UserClass::generate_source(std::ostream &stream) const{
static const char *format =
"{name}::{name}(DeserializerStream &ds)\n"
"{ctor}"
"\n"
"\n"
"void {name}::get_object_node(std::vector<ObjectNode> &v) const{{\n"
"{gon}"
"}}\n"
"\n"
"void {name}::serialize(SerializerStream &ss) const{{\n"
"{ser}"
"}}\n"
"\n"
"std::uint32_t {name}::get_type_id() const{{\n"
"{gti}"
"}}\n"
"\n"
"TypeHash {name}::get_type_hash() const{{\n"
"{gth}"
"}}\n"
"\n"
"std::shared_ptr<SerializableMetadata> {name}::get_metadata() const{{\n"
"return this->static_get_metadata();\n"
"}}\n"
"\n"
"std::shared_ptr<SerializableMetadata> {name}::static_get_metadata(){{\n"
"{gmd}"
"}}\n"
"\n";
variable_formatter vf(format);
vf
<< "name" << this->name
<< "ctor" << this->generate_deserializer()
<< "gon" << this->generate_get_object_node2()
<< "ser" << this->generate_serialize()
<< "gti" << ("return " + utoa(this->get_type_id()) + ";")
<< "gth" << this->generate_get_type_hash()
<< "gmd" << this->generate_get_metadata();
stream << (std::string)vf;
}
void UserClass::iterate_internal(iterate_callback_t &callback, std::set<Type *> &visited){
for (auto &b : this->base_classes)
b.Class->iterate(callback, visited);
for (auto &e : this->elements){
auto casted = std::dynamic_pointer_cast<ClassMember>(e);
if (!casted)
continue;
casted->get_type()->iterate(callback, visited);
}
Type::iterate_internal(callback, visited);
}
void UserClass::iterate_only_public_internal(iterate_callback_t &callback, std::set<Type *> &visited, bool do_not_ignore){
for (auto &b : this->base_classes)
b.Class->iterate_only_public(callback, visited, false);
for (auto &e : this->elements){
auto casted = std::dynamic_pointer_cast<ClassMember>(e);
if (!casted)
continue;
casted->get_type()->iterate_only_public(callback, visited, false);
}
Type::iterate_only_public_internal(callback, visited, true);
}
std::string UserClass::base_get_type_string() const{
std::stringstream stream;
stream << '{' << this->name;
for (auto &b : this->base_classes)
stream << ':' << b.Class->base_get_type_string();
stream << '(';
bool first = true;
for (auto &e : this->elements){
auto casted = std::dynamic_pointer_cast<ClassMember>(e);
if (!casted)
continue;
if (!first)
stream << ',';
else
first = false;
stream << '(' << (int)casted->get_accessibility() << ',' << casted->get_type()->get_type_string() << ',' << casted->get_name() << ')';
}
stream << ")}";
return stream.str();
}
void UserClass::walk_class_hierarchy(const std::function<bool(UserClass &)> &callback){
if (!callback(*this))
return;
for (auto &p : this->base_classes)
p.Class->walk_class_hierarchy(callback);
}
void UserClass::mark_virtual_inheritances(std::uint32_t serializable_type_id){
if (this->base_classes.size() < 2)
return;
std::vector<unsigned> counts;
for (auto &bc : this->base_classes){
auto &abs = bc.Class->get_all_base_classes();
for (auto c : abs){
auto id = !c ? serializable_type_id : c->get_type_id();
if (counts.size() <= id)
counts.resize(id + 1);
counts[id]++;
}
}
std::vector<std::uint32_t> virtual_classes;
for (size_t i = 0; i < counts.size(); i++)
if (counts[i] > 1)
virtual_classes.push_back(i);
this->mark_virtual_inheritances(serializable_type_id, virtual_classes);
}
void UserClass::mark_virtual_inheritances(std::uint32_t serializable_type_id, const std::vector<std::uint32_t> &virtual_classes){
auto b = virtual_classes.begin();
auto e = virtual_classes.end();
if (!this->base_classes.size()){
auto it = std::lower_bound(b, e, serializable_type_id);
if (it == e || *it != serializable_type_id)
return;
this->inherit_Serializable_virtually = true;
return;
}
for (auto &bc : this->base_classes){
bc.Class->mark_virtual_inheritances(serializable_type_id, virtual_classes);
auto it = std::lower_bound(b, e, bc.Class->get_type_id());
if (it == e || *it != bc.Class->get_type_id())
continue;
bc.Virtual = true;
}
}
bool UserClass::is_subclass_of(const UserClass &other) const{
if (this->get_type_id() == other.get_type_id())
return true;
for (auto &c : this->base_classes)
if (c.Class->is_subclass_of(other))
return true;
return false;
}
bool less_than(UserClass *a, UserClass *b){
if (!b)
return false;
if (!a)
return true;
return a->get_type_id() < b->get_type_id();
}
const std::vector<UserClass *> &UserClass::get_all_base_classes(){
auto &tabs = this->all_base_classes;
if (!tabs.size()){
tabs.push_back(this);
if (!this->base_classes.size())
tabs.push_back(nullptr);
for (auto &bs : this->base_classes){
auto &abs = bs.Class->get_all_base_classes();
decltype(this->all_base_classes) temp(this->all_base_classes.size() + abs.size());
auto it = std::set_union(tabs.begin(), tabs.end(), abs.begin(), abs.end(), temp.begin(), less_than);
temp.resize(it - temp.begin());
tabs = std::move(temp);
}
}
return this->all_base_classes;
}
bool UserClass::is_trivial_class(){
if (this->trivial_class < 0){
if (!this->base_classes.size())
this->trivial_class = 1;
else if (this->base_classes.size() > 1 || this->base_classes.front().Virtual)
this->trivial_class = 0;
else
this->trivial_class = this->base_classes.front().Class->is_trivial_class();
}
return !!this->trivial_class;
}
CppVersion UserClass::minimum_cpp_version() const{
auto ret = CppVersion::Cpp1998;
for (auto &base : this->base_classes){
auto v = base.Class->minimum_cpp_version();
if ((long)v > (long)ret)
ret = v;
}
for (auto &element : this->elements){
auto v = element->minimum_cpp_version();
if ((long)v > (long)ret)
ret = v;
}
return ret;
}
std::uint32_t CppFile::assign_type_ids(){
std::uint32_t id = 1;
if (!this->type_map.size()){
std::map<TypeHash, std::pair<unsigned, Type *>> type_map;
auto callback = [&type_map, &id](Type &t, std::uint32_t &type_id){
auto &hash = t.get_type_hash();
auto it = type_map.find(hash);
if (it != type_map.end())
return;
type_id = id;
type_map[hash] = std::make_pair(id, &t);
id++;
};
for (auto &e : this->elements){
auto Class = std::dynamic_pointer_cast<UserClass>(e);
if (!Class)
continue;
Class->iterate_only_public(callback);
}
for (auto &kv : type_map)
this->type_map[kv.second.first] = kv.second.second;
}else{
for (auto &kv : this->type_map)
id = std::max(id, kv.first);
id++;
}
return id;
}
std::string filename_to_macro(std::string ret){
for (auto &c : ret)
if (c == '.')
c = '_';
else
c = toupper(c);
return ret;
}
CppVersion CppFile::minimum_cpp_version() const{
CppVersion ret = CppVersion::Cpp1998;
for (auto &c : this->classes){
auto v = c.second->minimum_cpp_version();
if ((long)v > (long)ret)
ret = v;
}
return ret;
}
const char *to_string(CppVersion version){
switch (version){
case CppVersion::Undefined:
return "C++??";
case CppVersion::Cpp1998:
return "C++98";
case CppVersion::Cpp2011:
return "C++11";
case CppVersion::Cpp2014:
return "C++14";
case CppVersion::Cpp2017:
return "C++17";
case CppVersion::Cpp2020:
return "C++20";
default:
throw GenericException("Invalid switch for CppVersion");
}
}
void require_cpp(std::ostream &s, CppVersion version){
s <<
"#ifndef __cplusplus\n"
"#error No C++?\n"
"#endif\n"
"\n";
if (version == CppVersion::Undefined)
return;
s <<
"#if __cplusplus < " << (int)version << "\n"
"#error " << to_string(version) << " or newer is required to compile this.\n"
"#endif\n"
"\n";
}
void CppFile::generate_header(){
this->assign_type_ids();
auto filename = this->get_name() + ".generated.h";
auto macro = filename_to_macro(filename);
std::ofstream file(filename.c_str());
file <<
"#pragma once\n"
"\n"
;
require_cpp(file, this->minimum_cpp_version());
std::set<std::string> includes;
for (auto &c : this->classes)
c.second->add_headers(includes);
for (auto &h : includes)
file << "#include " << h << std::endl;
file <<
"#include \"" << this->name << ".aux.h\"\n"
"#include \"serialization_utils.h\"\n"
"#include \"Serializable.h\"\n"
"#include \"SerializerStream.h\"\n"
"#include \"DeserializerStream.h\"\n"
"#include \"serialization_utils.inl\"\n"
"\n";
for (auto &e : this->elements){
auto Class = std::dynamic_pointer_cast<UserClass>(e);
if (Class)
file << "class " << Class->get_name() << ";\n";
}
file << std::endl;
for (auto &e : this->elements){
auto Class = std::dynamic_pointer_cast<UserClass>(e);
if (Class){
Class->generate_header(file);
auto ts = Class->base_get_type_string();
std::cout << ts << std::endl
<< TypeHash(ts).to_string() << std::endl;
}else
file << e;
file << std::endl;
}
file << "\n";
}
std::string generate_get_metadata_signature(){
return "std::shared_ptr<SerializableMetadata> " + get_get_metadata_function_name() + "()";
}
void CppFile::generate_source(){
this->assign_type_ids();
std::ofstream file((this->get_name() + ".generated.cpp").c_str());
file << "#include \"" << this->get_name() << ".generated.h\"\n"
"#include <utility>\n"
"\n"
"extern std::pair<std::uint32_t, TypeHash> " << this->get_name() << "_id_hashes[];\n"
"\n"
<< generate_get_metadata_signature() << ";\n"
"\n";
for (auto &kv : this->type_map){
file <<
"template <>\n"
"struct static_get_type_id<" << *kv.second << ">{\n"
"static const std::uint32_t value = " << kv.second->get_type_id() << ";\n"
"};\n"
"\n";
}
for (auto &e : this->elements){
auto Class = std::dynamic_pointer_cast<UserClass>(e);
if (!Class)
continue;
Class->generate_source(file);
file << std::endl;
}
}
void CppFile::generate_allocator(std::ostream &stream){
stream << "void *" << get_allocator_function_name() << "(std::uint32_t type){\n"
"static const size_t sizes[] = { ";
for (auto &kv : this->type_map){
if (kv.second->is_abstract()){
stream << "0, ";
continue;
}
stream << "sizeof(";
kv.second->output(stream);
stream << "), ";
}
stream << "};\n"
"type--;\n"
"if (!sizes[type]) return nullptr;\n"
"return ::operator new (sizes[type]);\n"
"}\n";
}
void CppFile::generate_constructor(std::ostream &stream){
stream << "void " << get_constructor_function_name() << "(std::uint32_t type, void *s, DeserializerStream &ds){\n"
"typedef void (*constructor_f)(void *, DeserializerStream &);\n"
"static const constructor_f constructors[] = {\n";
for (auto &kv : this->type_map){
if (kv.second->is_abstract()){
stream << "nullptr,\n";
continue;
}
stream << "[](void *s, DeserializerStream &ds)";
kv.second->generate_deserializer(stream, "ds", "s");
stream << ",\n";
}
stream << "};\n"
"type--;\n"
"if (!constructors[type]) return;\n"
"return constructors[type](s, ds);\n"
"}\n";
}
void CppFile::generate_rollbacker(std::ostream &stream){
stream << "void " << get_rollbacker_function_name() << "(std::uint32_t type, void *s){\n"
"typedef void (*rollbacker_f)(void *);\n"
"static const rollbacker_f rollbackers[] = {\n";
for (auto &kv : this->type_map) {
if (kv.second->is_abstract()) {
stream << "nullptr,\n";
continue;
}
stream << "[](void *s)";
kv.second->generate_rollbacker(stream, "s");
stream << ",\n";
}
stream << "};\n"
"type--;\n"
"if (!rollbackers[type]) return;\n"
"return rollbackers[type](s);\n"
"}\n";
}
void CppFile::generate_is_serializable(std::ostream &stream){
std::vector<std::uint32_t> flags;
int bit = 0;
int i = 0;
for (auto &kv : this->type_map){
std::uint32_t u = kv.second->get_is_serializable();
if (kv.second->get_type_id() != ++i)
throw GenericException("Unknown program state!");
u <<= bit;
if (!bit)
flags.push_back(u);
else
flags.back() |= u;
bit = (bit + 1) % 32;
}
const char *format =
"bool {function_name}(std::uint32_t type){{\n"
"static const std::uint32_t is_serializable[] = {{ {array} }};\n"
"type--;\n"
"return (is_serializable[type / 32] >> (type & 31)) & 1;\n"
"}}\n";
variable_formatter vf(format);
std::stringstream temp;
for (auto u : flags)
temp << "0x" << std::hex << std::setw(8) << std::setfill('0') << (int)u << ", ";
vf
<< "function_name" << get_is_serializable_function_name()
<< "array" << temp.str();
stream << (std::string)vf;
}
#if 0
void CppFile::generate_cast_offsets(std::ostream &stream){
std::vector<std::pair<std::uint32_t, std::uint32_t>> valid_casts;
for (auto &kv1 : this->type_map){
if (!kv1.second->is_serializable())
continue;
auto uc1 = static_cast<UserClass *>(kv1.second);
for (auto &kv2 : this->type_map){
if (!kv2.second->is_serializable())
continue;
auto uc2 = static_cast<UserClass *>(kv2.second);
if (uc1->is_subclass_of(*uc2))
valid_casts.push_back(std::make_pair(kv1.first, kv2.first));
}
}
std::sort(valid_casts.begin(), valid_casts.end());
const char *format =
"std::vector<std::tuple<std::uint32_t, std::uint32_t, int>> {function_name}(){{\n"
"const auto k = std::numeric_limits<intptr_t>::max() / 4;\n"
"std::vector<std::tuple<std::uint32_t, std::uint32_t, int>> ret;\n"
"ret.reserve({size});\n"
"{ret_init}"
"return ret;\n"
"}}\n";
variable_formatter vf(format);
std::stringstream temp;
for (auto &kv : valid_casts){
temp <<
"ret.push_back("
"std::make_tuple("
"(std::uint32_t)" << kv.first << ", "
"(std::uint32_t)" << kv.second << ", ";
if (kv.first != kv.second){
temp << "(int)((intptr_t)static_cast<";
this->type_map[kv.second]->output(temp);
temp << " *>((";
this->type_map[kv.first]->output(temp);
temp << " *)k) - k)";
}else
temp << "0";
temp << "));\n";
}
vf
<< "function_name" << get_cast_offsets_function_name()
<< "size" << valid_casts.size()
<< "ret_init" << temp.str();
stream << (std::string)vf;
}
#endif
void CppFile::generate_dynamic_cast(std::ostream &stream){
stream << "Serializable *" << get_dynamic_cast_function_name() << "(void *src, std::uint32_t type){\n"
" typedef Serializable *(*cast_f)(void *);\n"
" static const cast_f casts[] = {\n";
for (auto &kv : this->type_map){
if (!kv.second->is_serializable()){
stream << " nullptr,\n";
continue;
}
stream << " [](void *p){ return dynamic_cast<Serializable *>((";
kv.second->output(stream);
stream << " *)p); },\n";
}
stream <<
" };\n"
" type--;\n"
" if (!casts[type])\n"
" return nullptr;\n"
" return casts[type](src);\n"
"}\n";
}
void CppFile::generate_generic_pointer_classes(std::ostream &stream){
for (auto &kv1 : this->type_map){
if (!kv1.second->is_serializable())
continue;
auto uc1 = static_cast<UserClass *>(kv1.second);
auto name = uc1->get_name();
stream <<
"class RawPointer" << name << " : public GenericPointer{\n"
" std::unique_ptr<" << name << " *> real_pointer;\n"
"public:\n"
" RawPointer" << name << "(void *p){\n"
" this->real_pointer.reset(new " << name << "*((" << name << " *)p));\n"
" this->pointer = this->real_pointer.get();\n"
" }\n"
" ~RawPointer" << name << "() = default;\n"
" void release() override{}\n"
" std::unique_ptr<GenericPointer> cast(std::uint32_t type) override;\n"
"};\n"
"\n"
;
stream <<
"class SharedPtr" << name << " : public GenericPointer{\n"
" std::unique_ptr<std::shared_ptr<" << name << ">> real_pointer;\n"
"public:\n"
" SharedPtr" << name << "(void *p){\n"
" this->real_pointer.reset(new std::shared_ptr<" << name << ">((" << name << " *)p, conditional_deleter<" << name << ">()));\n"
" this->pointer = this->real_pointer.get();\n"
" }\n"
" template <typename T>\n"
" SharedPtr" << name << "(const std::shared_ptr<T> &p){\n"
" this->real_pointer.reset(new std::shared_ptr<" << name <<">(std::static_pointer_cast<" << name << ">(p)));\n"
" this->pointer = this->real_pointer.get();\n"
" }\n"
" ~SharedPtr" << name << "() = default;\n"
" void release() override{\n"
" std::get_deleter<conditional_deleter<" << name << ">> (*this->real_pointer)->disable();\n"
" }\n"
" std::unique_ptr<GenericPointer> cast(std::uint32_t type) override;\n"
"};\n"
"\n"
;
stream <<
"class UniquePtr" << name << " : public GenericPointer{\n"
" std::unique_ptr<std::unique_ptr<" << name << ">> real_pointer;\n"
"public:\n"
" UniquePtr" << name << "(void *p){\n"
" this->real_pointer.reset(new std::unique_ptr<" << name << ">((" << name << " *)p));\n"
" this->pointer = this->real_pointer.get();\n"
" }\n"
" ~UniquePtr" << name << "() = default;\n"
" void release() override{\n"
" this->real_pointer->release();\n"
" }\n"
" std::unique_ptr<GenericPointer> cast(std::uint32_t type) override;\n"
"};\n"
"\n"
;
}
}
void CppFile::generate_generic_pointer_class_implementations(std::ostream &stream){
for (auto &kv1 : this->type_map){
if (!kv1.second->is_serializable())
continue;
auto uc1 = static_cast<UserClass *>(kv1.second);
auto name = uc1->get_name();
//RawPointer
stream <<
"std::unique_ptr<GenericPointer> RawPointer" << name << "::cast(std::uint32_t type){\n"
" switch (type){\n";
for (auto &kv2 : this->type_map){
if (!kv2.second->is_serializable())
continue;
auto uc2 = static_cast<UserClass *>(kv2.second);
if (!uc1->is_subclass_of(*uc2))
continue;
stream <<
" case " << uc2->get_type_id() << ":\n"
" return std::unique_ptr<GenericPointer>(new RawPointer" << uc2->get_name() << "(*this->real_pointer));\n";
}
stream <<
" default:\n"
" return std::unique_ptr<GenericPointer>();\n"
" }\n"
"}\n";
//SharedPtr
stream <<
"std::unique_ptr<GenericPointer> SharedPtr" << name << "::cast(std::uint32_t type){\n"
" switch (type){\n";
for (auto &kv2 : this->type_map){
if (!kv2.second->is_serializable())
continue;
auto uc2 = static_cast<UserClass *>(kv2.second);
if (!uc1->is_subclass_of(*uc2))
continue;
stream <<
" case " << uc2->get_type_id() << ":\n"
" return std::unique_ptr<GenericPointer>(new SharedPtr" << uc2->get_name() << "(*this->real_pointer));\n";
}
stream <<
" default:\n"
" return std::unique_ptr<GenericPointer>();\n"
" }\n"
"}\n";
//UniquePtr
stream <<
"std::unique_ptr<GenericPointer> UniquePtr" << name << "::cast(std::uint32_t type){\n"
" switch (type){\n";
for (auto &kv2 : this->type_map){
if (!kv2.second->is_serializable())
continue;
auto uc2 = static_cast<UserClass *>(kv2.second);
if (!uc1->is_subclass_of(*uc2))
continue;
stream <<
" case " << uc2->get_type_id() << ":\n"
" throw std::runtime_error(\"Multiple unique pointers to single object detected.\");\n";
}
stream <<
" default:\n"
" return std::unique_ptr<GenericPointer>();\n"
" }\n"
"}\n";
}
}
void CppFile::generate_pointer_allocator(std::ostream &stream){
stream <<
"std::unique_ptr<GenericPointer> " << get_allocate_pointer_function_name() << "(std::uint32_t type, PointerType pointer_type, void *p){\n"
" switch (pointer_type){\n"
" case PointerType::RawPointer:\n"
" switch (type){\n"
;
for (auto &kv : this->type_map){
if (!kv.second->is_serializable())
continue;
auto uc = static_cast<UserClass *>(kv.second);
auto name = uc->get_name();
stream <<
" case " << uc->get_type_id() << ":\n"
" return std::unique_ptr<GenericPointer>(new RawPointer" << name << "(p));\n";
}
stream <<
" default:\n"
" return std::unique_ptr<GenericPointer>();\n"
" }\n"
" break;\n"
" case PointerType::SharedPtr:\n"
" switch (type){\n"
;
for (auto &kv : this->type_map){
if (!kv.second->is_serializable())
continue;
auto uc = static_cast<UserClass *>(kv.second);
auto name = uc->get_name();
stream <<
" case " << uc->get_type_id() << ":\n"
" return std::unique_ptr<GenericPointer>(new SharedPtr" << name << "(p));\n";
}
stream <<
" default:\n"
" return std::unique_ptr<GenericPointer>();\n"
" }\n"
" break;\n"
" case PointerType::UniquePtr:\n"
" switch (type){\n"
;
for (auto &kv : this->type_map){
if (!kv.second->is_serializable())
continue;
auto uc = static_cast<UserClass *>(kv.second);
auto name = uc->get_name();
stream <<
" case " << uc->get_type_id() << ":\n"
" return std::unique_ptr<GenericPointer>(new UniquePtr" << name << "(p));\n";
}
stream <<
" default:\n"
" return std::unique_ptr<GenericPointer>();\n"
" }\n"
" break;\n"
" default:\n"
" throw std::runtime_error(\"Internal error. Unknown pointer type.\");\n"
" }\n"
"}\n"
;
}
void CppFile::generate_cast_categorizer(std::ostream &stream){
unsigned max_type = 0;
for (auto &kv : this->type_map)
max_type = std::max(max_type, kv.first);
stream <<
"CastCategory " << get_categorize_cast_function_name() << "(std::uint32_t src_type, std::uint32_t dst_type){\n"
" if (src_type < 1 || dst_type < 1 || src_type > " << max_type << " || dst_type > " << max_type << ")\n"
" return CastCategory::Invalid;\n"
" if (src_type == dst_type)\n"
" return CastCategory::Trivial;\n"
" static const CastCategory categories[] = {\n"
;
for (unsigned src = 1; src <= max_type; src++){
for (unsigned dst = 1; dst <= max_type; dst++){
if (src == dst){
stream << " CastCategory::Trivial,\n";
continue;
}
auto src_t = this->type_map[src];
auto dst_t = this->type_map[dst];
if (!src_t->is_serializable() || !dst_t->is_serializable()){
stream << " CastCategory::Invalid,\n";
continue;
}
auto src_class = static_cast<UserClass *>(src_t);
auto dst_class = static_cast<UserClass *>(dst_t);
if (!src_class->is_subclass_of(*dst_class)){
stream << " CastCategory::Invalid,\n";
continue;
}
if (src_class->is_trivial_class()){
stream << " CastCategory::Trivial,\n";
continue;
}
stream << " CastCategory::Complex,\n";
}
}
stream <<
" };\n"
" src_type--;\n"
" dst_type--;\n"
" return categories[dst_type + src_type * " << max_type << "];\n"
"}\n"
;
}
void CppFile::generate_aux(){
this->assign_type_ids();
std::ofstream file((this->get_name() + ".aux.generated.cpp").c_str());
std::string array_name = this->get_name() + "_id_hashes";
file <<
"#include \"Serializable.h\"\n"
"#include \"" << this->name << ".generated.h\"\n"
"#include <utility>\n"
"#include <cstdint>\n"
"#include <memory>\n"
"\n";
for (auto &kv : this->type_map)
file << "// " << kv.first << ": " << kv.second << std::endl;
file <<
"\n"
"std::pair<std::uint32_t, TypeHash> " << array_name << "[] = {\n";
for (auto &i : this->type_map){
auto type = i.second;
auto ts = type->get_type_string();
if (dynamic_cast<UserClass *>(type))
ts = static_cast<UserClass *>(type)->base_get_type_string();
file
<< "// " << ts << "\n"
<< "{ " << i.first << ", TypeHash(" << type->get_type_hash().to_string() << ")},\n";
}
file <<
"};\n"
"\n";
this->generate_allocator(file);
file << "\n";
this->generate_constructor(file);
file << "\n";
this->generate_rollbacker(file);
file << "\n";
this->generate_is_serializable(file);
file << "\n";
this->generate_dynamic_cast(file);
file << "\n";
this->generate_generic_pointer_classes(file);
file << "\n";
this->generate_generic_pointer_class_implementations(file);
file << "\n";
this->generate_pointer_allocator(file);
file << "\n";
this->generate_cast_categorizer(file);
file <<
"\n"
<< generate_get_metadata_signature() << "{\n"
"std::shared_ptr<SerializableMetadata> ret(new SerializableMetadata);\n"
"ret->set_functions("
<< get_allocator_function_name() << ", "
<< get_constructor_function_name() << ", "
<< get_rollbacker_function_name() << ", "
<< get_is_serializable_function_name() << ", "
<< get_dynamic_cast_function_name() << ", "
<< get_allocate_pointer_function_name() << ", "
<< get_categorize_cast_function_name()
<<");\n"
"for (auto &p : " << array_name << ")\n"
"ret->add_type(p.first, p.second);\n"
"return ret;\n"
"}\n";
}
void CppFile::mark_virtual_inheritances(){
auto serializable_type_id = this->assign_type_ids();
for (auto &uc : this->classes)
uc.second->mark_virtual_inheritances(serializable_type_id);
}
| 30.553933 | 176 | 0.604252 | [
"object",
"vector"
] |
8650c177f67ea2395b17d0dd1cc72c1ce48a8330 | 6,331 | cc | C++ | src/Foundational/iwbits/tbic.cc | michaelweiss092/LillyMol | a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9 | [
"Apache-2.0"
] | 53 | 2018-06-01T13:16:15.000Z | 2022-02-23T21:04:28.000Z | src/Foundational/iwbits/tbic.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | 19 | 2018-08-14T13:43:18.000Z | 2021-09-24T12:53:11.000Z | src/Foundational/iwbits/tbic.cc | IanAWatson/LillyMol-4.0-Bazel | f38f23a919c622c31280222f8a90e6ab7d871b93 | [
"Apache-2.0"
] | 19 | 2018-10-23T19:41:01.000Z | 2022-02-17T08:14:00.000Z | /*
Mostly a timing tester for bits in common
*/
#include <stdlib.h>
#include <values.h>
#ifdef linux
#else
#include <limits.h>
#endif
#include <iomanip>
#include "cmdline.h"
#include "iwbits.h"
#include "iwrandom.h"
static int verbose = 0;
/*
To replicate bit densities encountered in real life, we may want to
increase or lower the bits set randomly
*/
static float desired_density = 0.0;
static int default_nbits = 512;
static int default_iterations = 2000;
static void
usage (int rc)
{
cerr << "Tester for bits in common\n";
cerr << " -n <iterations> perform the tests <iterations> times (default " << default_iterations << ")\n";
cerr << " -b <nbits> size of bit vectors to use (default " << default_nbits << ")\n";
cerr << " -d <density> desired bit density\n";
cerr << " -v verbose output\n";
exit (rc);
}
/*
We have adjusted the density of a bit vector to the desired range. Copy
the bits to a vector.
*/
static void
copy_bits (IW_Bits_Base & b, unsigned char * r)
{
const unsigned char * x = reinterpret_cast<const unsigned char *> (b.bits ());
int nb = b.nbits () / IW_BITS_PER_BYTE;
for (int i = 0; i < nb; i++)
{
r[i] = x[i];
}
return;
}
static void
adjust_density_upwards (IW_Bits_Base & b, unsigned char * r)
{
int nset = b.nset ();
if (nset == b.nbits ())
{
cerr << "Cannot adjust density upwards, all bits set\n";
return;
}
while (1)
{
int i = intbtwij (0, b.nbits () - 1);
if (b.is_set (i))
continue;
b.set (i, 1);
nset++;
float density = static_cast<float> (nset) / static_cast<float> (b.nbits ());
if (density < desired_density)
continue;
assert (nset == b.nset ());
copy_bits (b, r);
return;
}
}
static void
adjust_density_downwards (IW_Bits_Base & b, unsigned char * r)
{
int nset = b.nset ();
if (0 == nset)
{
cerr << "Cannot adjust density downwards, all bits unset\n";
return;
}
while (1)
{
int i = intbtwij (0, b.nbits () - 1);
if (! b.is_set (i))
continue;
b.set (i, 0);
nset--;
float density = static_cast<float> (nset) / static_cast<float> (b.nbits ());
if (density > desired_density)
continue;
assert (nset == b.nset ());
copy_bits (b, r);
return;
}
}
static void
adjust_density (IW_Bits_Base & b, unsigned char * r)
{
if (0.0 == desired_density)
return;
float density = static_cast<float> (b.nset ()) / static_cast<float> (b.nbits ());
if (verbose > 1)
cerr << "Initial nset " << b.nset () << " density " << density << endl;
if (density == desired_density)
return;
if (density < desired_density)
adjust_density_upwards (b, r);
else
adjust_density_downwards (b, r);
return;
}
static int
tbic (int iterations, int nbits,
int s, // the number of double's in r1 and r2
random_number_t * r1,
random_number_t * r2)
{
iw_random_seed ();
IW_Bits_Base b1 (nbits), b2 (nbits);
for (int i = 0; i < iterations; i++)
{
for (int j = 0; j < s; j++)
{
r1[j] = DBL_MAX * iwrandom ();
r2[j] = DBL_MAX * iwrandom ();
if (iwrandom () < 0.5)
r2[j] = - r2[j];
// cerr << "j = " << j << " r1 = " << r1[j] << " r2 = " << r2[j] << endl;
}
b1.construct_from_array_of_bits (reinterpret_cast<const unsigned char *> (r1), nbits);
adjust_density (b1, reinterpret_cast<unsigned char *> (r1));
b2.construct_from_array_of_bits (reinterpret_cast<const unsigned char *> (r2), nbits);
adjust_density (b2, reinterpret_cast<unsigned char *> (r2));
for (int j = 0; j < 100; j++)
{
if (b1.bits_in_common (b2) != b2.bits_in_common (b1))
{
cerr << "Yipes, asymmetry, " << b1.bits_in_common (b2) << " vs " << b2.bits_in_common (b1) << endl;
return 0;
}
if (b1.bits_in_common (b1) != b1.nset ())
{
cerr << "Yipes, nset error, bits in common self " << b1.bits_in_common (b1) << " vs nset " << b1.nset () << ", nbits " << b1.nbits() << endl;
return 0;
}
// Shuffle r2
random_number_t rsave = r2[0];
for (int k = 0; k < s - 1; k++)
{
r2[k] = r2[k + 1];
}
r1[s - 1] = rsave;
b2.construct_from_array_of_bits (reinterpret_cast<const unsigned char *> (r2), nbits);
}
}
return 1;
}
/*
Allocate two arrays for holding random numbers
*/
static int
tbic (int iterations, int nbits)
{
int s = (nbits + IW_BITS_PER_BYTE) / IW_BITS_PER_BYTE / sizeof (random_number_t);
random_number_t * r1 = new random_number_t[s];
random_number_t * r2 = new random_number_t[s];
int rc = tbic (iterations, nbits, s, r1, r2);
delete r1;
delete r2;
return rc;
}
int
tbic (int argc, char ** argv)
{
Command_Line cl (argc, argv, "vn:b:d:h");
if (cl.unrecognised_options_encountered ())
{
cerr << "Unrecognised options encountered\n";
usage (1);
}
verbose = cl.option_count ('v');
if (cl.option_present ('h'))
{
usage (3);
}
int iterations = default_iterations;
if (cl.option_present ('n'))
{
if (! cl.value ('n', iterations) || iterations < 1)
{
cerr << "The iteration count (-n) option must be followed by a whole positive number\n";
usage (3);
}
if (verbose)
cerr << "Will do " << iterations << " iterations\n";
}
else if (verbose)
cerr << "Default iteration count " << iterations << endl;
int nbits = default_nbits;
if (cl.option_present ('b'))
{
if (! cl.value ('b', nbits) || nbits < 1)
{
cerr << "The number of bits (-b) option must be followed by a whole positive number\n";
usage (5);
}
if (verbose)
cerr << "Will test with bit vectors with " << nbits << " bits\n";
}
else if (verbose)
cerr << "Default nbits " << nbits << endl;
if (cl.option_present ('d'))
{
if (! cl.value ('d', desired_density) || desired_density <= 0.0 || desired_density >= 1.0)
{
cerr << "The desired density (-d) option must be followed by a valid density\n";
usage (7);
}
if (verbose)
cerr << "Desired bit density " << desired_density << endl;
}
(void) tbic (iterations, nbits);
return 0;
}
int
main (int argc, char ** argv)
{
int rc = tbic (argc, argv);
return rc;
}
| 21.033223 | 149 | 0.583162 | [
"vector"
] |
865936e2ed751addbc7a42854973e66718948d67 | 10,975 | cxx | C++ | panda/src/android/android_main.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/android/android_main.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/android/android_main.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file android_main.cxx
* @author rdb
* @date 2013-01-12
*/
#include "config_android.h"
#include "config_putil.h"
#include "virtualFileMountAndroidAsset.h"
#include "virtualFileSystem.h"
#include "filename.h"
#include "thread.h"
#include "urlSpec.h"
#include "config_display.h"
// #define OPENGLES_1 #include "config_androiddisplay.h"
#include <android_native_app_glue.h>
#include <sys/socket.h>
#include <arpa/inet.h>
// struct android_app* panda_android_app = NULL;
extern int main(int argc, const char **argv);
/**
* This function is called by native_app_glue to initialize the program. It
* simply stores the android_app object and calls main() normally.
*
* Note that this does not run in the main thread, but in a thread created
* specifically for this activity by android_native_app_glue.
*/
void android_main(struct android_app* app) {
panda_android_app = app;
// Attach the app thread to the Java VM.
JNIEnv *env;
ANativeActivity* activity = app->activity;
int status = activity->vm->AttachCurrentThread(&env, nullptr);
if (status < 0 || env == nullptr) {
android_cat.error() << "Failed to attach thread to JVM!\n";
return;
}
jclass activity_class = env->GetObjectClass(activity->clazz);
// Get the current Java thread name. This just helps with debugging.
jmethodID methodID = env->GetStaticMethodID(activity_class, "getCurrentThreadName", "()Ljava/lang/String;");
jstring jthread_name = (jstring) env->CallStaticObjectMethod(activity_class, methodID);
string thread_name;
if (jthread_name != nullptr) {
const char *c_str = env->GetStringUTFChars(jthread_name, nullptr);
thread_name.assign(c_str);
env->ReleaseStringUTFChars(jthread_name, c_str);
}
// Before we make any Panda calls, we must make the thread known to Panda.
// This will also cause the JNIEnv pointer to be stored on the thread.
// Note that we must keep a reference to this thread around.
PT(Thread) current_thread = Thread::bind_thread(thread_name, "android_app");
android_cat.info()
<< "New native activity started on " << *current_thread << "\n";
// Were we given an optional location to write the stdout/stderr streams?
methodID = env->GetMethodID(activity_class, "getIntentOutputUri", "()Ljava/lang/String;");
jstring joutput_uri = (jstring) env->CallObjectMethod(activity->clazz, methodID);
if (joutput_uri != nullptr) {
const char *output_uri = env->GetStringUTFChars(joutput_uri, nullptr);
if (output_uri != nullptr && output_uri[0] != 0) {
URLSpec spec(output_uri);
if (spec.get_scheme() == "file") {
string path = spec.get_path();
int fd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY);
if (fd != -1) {
android_cat.info()
<< "Writing standard output to file " << path << "\n";
dup2(fd, 1);
dup2(fd, 2);
} else {
android_cat.error()
<< "Failed to open output path " << path << "\n";
}
} else if (spec.get_scheme() == "tcp") {
string host = spec.get_server();
int fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr = {0};
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(spec.get_port());
serv_addr.sin_addr.s_addr = inet_addr(host.c_str());
if (connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == 0) {
android_cat.info()
<< "Writing standard output to socket "
<< spec.get_server_and_port() << "\n";
dup2(fd, 1);
dup2(fd, 2);
} else {
android_cat.error()
<< "Failed to open output socket "
<< spec.get_server_and_port() << "\n";
}
close(fd);
} else {
android_cat.error()
<< "Unsupported scheme in output URI: " << output_uri << "\n";
}
env->ReleaseStringUTFChars(joutput_uri, output_uri);
}
}
// Fetch the data directory.
jmethodID get_appinfo = env->GetMethodID(activity_class, "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;");
jobject appinfo = env->CallObjectMethod(activity->clazz, get_appinfo);
jclass appinfo_class = env->GetObjectClass(appinfo);
// Fetch the path to the data directory.
jfieldID datadir_field = env->GetFieldID(appinfo_class, "dataDir", "Ljava/lang/String;");
jstring datadir = (jstring) env->GetObjectField(appinfo, datadir_field);
const char *data_path = env->GetStringUTFChars(datadir, nullptr);
if (data_path != nullptr) {
Filename::_internal_data_dir = data_path;
android_cat.info() << "Path to data: " << data_path << "\n";
env->ReleaseStringUTFChars(datadir, data_path);
}
// Fetch the path to the library directory.
if (ExecutionEnvironment::get_dtool_name().empty()) {
jfieldID libdir_field = env->GetFieldID(appinfo_class, "nativeLibraryDir", "Ljava/lang/String;");
jstring libdir = (jstring) env->GetObjectField(appinfo, libdir_field);
const char *lib_path = env->GetStringUTFChars(libdir, nullptr);
if (lib_path != nullptr) {
string dtool_name = string(lib_path) + "/libp3dtool.so";
ExecutionEnvironment::set_dtool_name(dtool_name);
android_cat.info() << "Path to dtool: " << dtool_name << "\n";
env->ReleaseStringUTFChars(libdir, lib_path);
}
}
// Get the cache directory. Set the model-path to this location.
methodID = env->GetMethodID(activity_class, "getCacheDirString", "()Ljava/lang/String;");
jstring jcache_dir = (jstring) env->CallObjectMethod(activity->clazz, methodID);
if (jcache_dir != nullptr) {
const char *cache_dir;
cache_dir = env->GetStringUTFChars(jcache_dir, nullptr);
android_cat.info() << "Path to cache: " << cache_dir << "\n";
ConfigVariableFilename model_cache_dir("model-cache-dir", Filename());
model_cache_dir.set_value(cache_dir);
env->ReleaseStringUTFChars(jcache_dir, cache_dir);
}
// Get the path to the APK.
methodID = env->GetMethodID(activity_class, "getPackageCodePath", "()Ljava/lang/String;");
jstring code_path = (jstring) env->CallObjectMethod(activity->clazz, methodID);
const char* apk_path;
apk_path = env->GetStringUTFChars(code_path, nullptr);
// We're going to set this as binary name, which is better than the
// default (which refers to the zygote). Or should we set it to the
// native library? How do we get the path to that?
android_cat.info() << "Path to APK: " << apk_path << "\n";
ExecutionEnvironment::set_binary_name(apk_path);
// Mount the assets directory.
Filename apk_fn(apk_path);
PT(VirtualFileMountAndroidAsset) asset_mount;
asset_mount = new VirtualFileMountAndroidAsset(app->activity->assetManager, apk_fn);
VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
//Filename asset_dir(apk_fn.get_dirname(), "assets");
Filename asset_dir("/android_asset");
vfs->mount(asset_mount, asset_dir, 0);
// Release the apk_path.
env->ReleaseStringUTFChars(code_path, apk_path);
// Now add the asset directory to the model-path.
//TODO: prevent it from adding the directory multiple times.
get_model_path().append_directory(asset_dir);
// Now load the configuration files.
vector<ConfigPage *> pages;
ConfigPageManager *cp_mgr;
AAssetDir *etc = AAssetManager_openDir(app->activity->assetManager, "etc");
if (etc != nullptr) {
cp_mgr = ConfigPageManager::get_global_ptr();
const char *filename = AAssetDir_getNextFileName(etc);
while (filename != nullptr) {
// Does it match any of the configured prc patterns?
for (size_t i = 0; i < cp_mgr->get_num_prc_patterns(); ++i) {
GlobPattern pattern = cp_mgr->get_prc_pattern(i);
if (pattern.matches(filename)) {
Filename prc_fn("etc", filename);
istream *in = asset_mount->open_read_file(prc_fn);
if (in != nullptr) {
ConfigPage *page = cp_mgr->make_explicit_page(Filename("/android_asset", prc_fn));
page->read_prc(*in);
pages.push_back(page);
}
break;
}
}
filename = AAssetDir_getNextFileName(etc);
}
AAssetDir_close(etc);
}
// Also read the intent filename.
methodID = env->GetMethodID(activity_class, "getIntentDataPath", "()Ljava/lang/String;");
jstring filename = (jstring) env->CallObjectMethod(activity->clazz, methodID);
const char *filename_str = nullptr;
if (filename != nullptr) {
filename_str = env->GetStringUTFChars(filename, nullptr);
android_cat.info() << "Got intent filename: " << filename_str << "\n";
Filename fn(filename_str);
if (!fn.exists()) {
// Show a toast with the failure message.
android_show_toast(activity, string("Unable to access ") + filename_str, 1);
}
}
// Create bogus argc and argv for calling the main function.
const char *argv[] = {"pview", nullptr, nullptr};
int argc = 1;
if (filename_str != nullptr) {
argv[1] = filename_str;
++argc;
}
while (!app->destroyRequested) {
// Call the main function. This will not return until the app is done.
android_cat.info() << "Calling main()\n";
main(argc, argv);
if (app->destroyRequested) {
// The app closed responding to a destroy request.
break;
}
// Ask Android to clean up the activity.
android_cat.info() << "Exited from main(), finishing activity\n";
ANativeActivity_finish(activity);
// We still need to keep an event loop going until Android gives us leave
// to end the process.
int looper_id;
int events;
struct android_poll_source *source;
while ((looper_id = ALooper_pollAll(-1, nullptr, &events, (void**)&source)) >= 0) {
// Process this event, but intercept application command events.
if (looper_id == LOOPER_ID_MAIN) {
int8_t cmd = android_app_read_cmd(app);
android_app_pre_exec_cmd(app, cmd);
android_app_post_exec_cmd(app, cmd);
// I don't think we can get a resume command after we call finish(),
// but let's handle it just in case.
if (cmd == APP_CMD_RESUME ||
cmd == APP_CMD_DESTROY) {
break;
}
} else if (source != nullptr) {
source->process(app, source);
}
}
}
android_cat.info() << "Destroy requested, exiting from android_main\n";
for (ConfigPage *page : pages) {
cp_mgr->delete_explicit_page(page);
}
vfs->unmount(asset_mount);
if (filename_str != nullptr) {
env->ReleaseStringUTFChars(filename, filename_str);
}
close(1);
close(2);
// Detach the thread before exiting.
activity->vm->DetachCurrentThread();
}
| 35.983607 | 123 | 0.66861 | [
"object",
"vector",
"model",
"3d"
] |
865c4e2f956bd65bd993e4f95e46fb5f5d106695 | 2,667 | hpp | C++ | ppcnn/ppcnn_server/cnn/load_model.hpp | mt-st1/PP-CNN2 | a35caf4aa3081342b48556305f2b0574a3d68800 | [
"Apache-2.0"
] | 19 | 2020-09-28T20:53:20.000Z | 2022-03-14T06:22:26.000Z | ppcnn/ppcnn_server/cnn/load_model.hpp | mt-st1/PP-CNN2 | a35caf4aa3081342b48556305f2b0574a3d68800 | [
"Apache-2.0"
] | null | null | null | ppcnn/ppcnn_server/cnn/load_model.hpp | mt-st1/PP-CNN2 | a35caf4aa3081342b48556305f2b0574a3d68800 | [
"Apache-2.0"
] | 8 | 2020-09-28T20:53:26.000Z | 2022-02-15T13:52:41.000Z | /*
* Copyright 2020 Yamana Laboratory, Waseda University
* Supported by JST CREST Grant Number JPMJCR1503, Japan.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE‐2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "layer.hpp"
#include "picojson.h"
picojson::array loadLayers(const string& model_structure_path);
Layer* buildLayer(picojson::object& layer, const string& layer_class_name,
const string& model_weights_path, OptOption& option);
Layer* buildLayer(picojson::object& layer, picojson::object& next_layer,
const string& layer_class_name,
const string& model_weight_path,
picojson::array::const_iterator& layers_itrator,
OptOption& option);
Layer* buildConv2D(picojson::object& layer_info,
const string& model_weights_path, OptOption& option);
Layer* buildAveragePooling2D(picojson::object& layer_info,
const string& model_weights_path,
OptOption& option);
Layer* buildBatchNormalization(picojson::object& layer_info,
const string& model_weights_path,
OptOption& option);
Layer* buildFlatten(picojson::object& layer_info,
const string& model_weights_path, OptOption& option);
Layer* buildDense(picojson::object& layer_info,
const string& model_weights_path, OptOption& option);
Layer* buildActivation(picojson::object& layer_info,
const string& model_weights_path, OptOption& option);
Layer* buildGlobalAveragePooling2D(picojson::object& layer_info,
const string& model_weights_path,
OptOption& option);
Layer* buildConv2DFusedBN(picojson::object& conv2d_layer_info,
picojson::object& bn_layer_info,
const string& model_weights_path, OptOption& option);
Layer* buildDenseFusedBN(picojson::object& dense_layer_info,
picojson::object& bn_layer_info,
const string& model_weights_path, OptOption& option);
| 41.030769 | 79 | 0.657293 | [
"object"
] |
865fec785664cca9015ee22d1cf4a8f6c847cc7c | 2,768 | cpp | C++ | uva/volume-003/mapmaker.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | uva/volume-003/mapmaker.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | uva/volume-003/mapmaker.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
struct Array
{
unsigned int base_address;
unsigned int dimensions;
unsigned int element_size;
vector<int> lower;
vector<int> upper;
vector<int> constants;
void calculate_constants()
{
constants.resize(dimensions + 1);
constants.back() = element_size;
for (unsigned int i {dimensions - 1}; i > 0; --i)
{
constants[i] = constants[i + 1] * (upper[i] - lower[i] + 1);
}
constants.front() = base_address;
for (unsigned int i {1}; i <= dimensions; ++i)
{
constants.front() -= constants[i] * lower[i - 1];
}
}
};
istream& operator>>(istream& in, Array& array)
{
in >> array.base_address
>> array.element_size
>> array.dimensions;
array.lower.resize(array.dimensions);
array.upper.resize(array.dimensions);
for (unsigned int i {0}; i < array.dimensions; ++i)
{
cin >> array.lower[i] >> array.upper[i];
}
array.calculate_constants();
return in;
}
struct Reference
{
string array;
vector<int> indices;
};
istream& operator>>(istream& in, Reference& reference)
{
in >> reference.array;
string rest;
getline(in, rest);
istringstream indices {rest};
for (int index; indices >> index; )
{
reference.indices.push_back(index);
}
}
void read_input(map<string, Array>& arrays, vector<Reference>& references)
{
unsigned int arrays_count;
unsigned int references_count;
cin >> arrays_count >> references_count;
for (unsigned int i {0}; i < arrays_count; ++i)
{
string name;
Array array;
cin >> name >> array;
arrays[name] = array;
}
references.resize(references_count);
for (auto& reference : references)
{
cin >> reference;
}
}
int main()
{
use_io_optimizations();
map<string, Array> arrays;
vector<Reference> references;
read_input(arrays, references);
for (const auto& reference : references)
{
auto array = arrays[reference.array];
auto physical_address = array.constants.front();
cout << reference.array << '[';
for (unsigned int i {0}; i < array.dimensions; ++i)
{
if (i != 0)
{
cout << ", ";
}
cout << reference.indices[i];
physical_address += array.constants[i + 1] * reference.indices[i];
}
cout << "] = " << physical_address << '\n';
}
return 0;
}
| 19.356643 | 78 | 0.569725 | [
"vector"
] |
8661bfb50d529a2b9fcc894275b392bbb222767d | 1,113 | cpp | C++ | main.cpp | ArionasMC/Asteroids | b5a81f833af1615ede2706bfe41baa8b661fa209 | [
"Apache-2.0"
] | null | null | null | main.cpp | ArionasMC/Asteroids | b5a81f833af1615ede2706bfe41baa8b661fa209 | [
"Apache-2.0"
] | null | null | null | main.cpp | ArionasMC/Asteroids | b5a81f833af1615ede2706bfe41baa8b661fa209 | [
"Apache-2.0"
] | null | null | null | #include "SDL.h"
#include "Game.h"
#include <iostream>
#include <fstream>
#include <sys/stat.h>
using namespace std;
bool fileExists(const std::string& file);
Game *game = NULL;
const char* version = "v0.3";
const char* name = "Asteroids ";
int main(int argc, char *argv[])
{
const int FPS = 60;
const int frameDelay = 1000 / FPS;
Uint32 frameStart;
int frameTime;
string title = string(name)+string(version);
game = new Game();
game->init(title.c_str(), 600, 800, false);
// Creating hiscore file
if(!fileExists("saves/hiscore.score")) {
ofstream file("saves/hiscore.score");
file << 0;
file.close();
}
while (game->running())
{
frameStart = SDL_GetTicks();
game->handleEvents();
game->update();
game->render();
frameTime = SDL_GetTicks() - frameStart;
if(frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
game->clean();
return 0;
}
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}
| 19.189655 | 49 | 0.592992 | [
"render"
] |
8665f8356c735a4ce6a6c2685bc96e6c91c18153 | 13,530 | cpp | C++ | imagesearch-20200212/cpp/src/image_search_20200212.cpp | alibabacloud-sdk-swift/alibabacloud-sdk | afd43b41530abb899076a34ceb96bdef55f74460 | [
"Apache-2.0"
] | null | null | null | imagesearch-20200212/cpp/src/image_search_20200212.cpp | alibabacloud-sdk-swift/alibabacloud-sdk | afd43b41530abb899076a34ceb96bdef55f74460 | [
"Apache-2.0"
] | null | null | null | imagesearch-20200212/cpp/src/image_search_20200212.cpp | alibabacloud-sdk-swift/alibabacloud-sdk | afd43b41530abb899076a34ceb96bdef55f74460 | [
"Apache-2.0"
] | null | null | null | // This file is auto-generated, don't edit it. Thanks.
#include <alibabacloud/image_search_20200212.hpp>
#include <alibabacloud/endpoint_util.hpp>
#include <alibabacloud/open_platform_20191219.hpp>
#include <alibabacloud/oss.hpp>
#include <alibabacloud/ossutil.hpp>
#include <alibabacloud/rpc.hpp>
#include <alibabacloud/rpcutil.hpp>
#include <boost/any.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/file_form.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
using namespace Alibabacloud_ImageSearch20200212;
Alibabacloud_ImageSearch20200212::Client::Client(const shared_ptr<Alibabacloud_RPC::Config>& config) : Alibabacloud_RPC::Client(config) {
_endpointRule = make_shared<string>("");
checkConfig(config);
_endpoint = make_shared<string>(getEndpoint(make_shared<string>("imagesearch"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint));
};
SearchImageByNameResponse Alibabacloud_ImageSearch20200212::Client::searchImageByName(shared_ptr<SearchImageByNameRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
return SearchImageByNameResponse(doRequest(make_shared<string>("SearchImageByName"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("2020-02-12"), make_shared<string>("AK"), nullptr, make_shared<map<string, boost::any>>(request->toMap()), runtime));
}
SearchImageByPicResponse Alibabacloud_ImageSearch20200212::Client::searchImageByPic(shared_ptr<SearchImageByPicRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
return SearchImageByPicResponse(doRequest(make_shared<string>("SearchImageByPic"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("2020-02-12"), make_shared<string>("AK"), nullptr, make_shared<map<string, boost::any>>(request->toMap()), runtime));
}
SearchImageByPicResponse Alibabacloud_ImageSearch20200212::Client::searchImageByPicAdvance(shared_ptr<SearchImageByPicAdvanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
// Step 0: init client
shared_ptr<string> accessKeyId = make_shared<string>(_credential->getAccessKeyId());
shared_ptr<string> accessKeySecret = make_shared<string>(_credential->getAccessKeySecret());
shared_ptr<Alibabacloud_RPC::Config> authConfig = make_shared<Alibabacloud_RPC::Config>(map<string, boost::any>({
{"accessKeyId", !accessKeyId ? boost::any() : boost::any(*accessKeyId)},
{"accessKeySecret", !accessKeySecret ? boost::any() : boost::any(*accessKeySecret)},
{"type", boost::any(string("access_key"))},
{"endpoint", boost::any(string("openplatform.aliyuncs.com"))},
{"protocol", !_protocol ? boost::any() : boost::any(*_protocol)},
{"regionId", !_regionId ? boost::any() : boost::any(*_regionId)}
}));
shared_ptr<Alibabacloud_OpenPlatform20191219::Client> authClient = make_shared<Alibabacloud_OpenPlatform20191219::Client>(authConfig);
shared_ptr<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadRequest> authRequest = make_shared<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadRequest>(map<string, boost::any>({
{"product", boost::any(string("ImageSearch"))},
{"regionId", !_regionId ? boost::any() : boost::any(*_regionId)}
}));
shared_ptr<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadResponse> authResponse = make_shared<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadResponse>();
shared_ptr<Alibabacloud_OSS::Config> ossConfig = make_shared<Alibabacloud_OSS::Config>(map<string, boost::any>({
{"accessKeySecret", !accessKeySecret ? boost::any() : boost::any(*accessKeySecret)},
{"type", boost::any(string("access_key"))},
{"protocol", !_protocol ? boost::any() : boost::any(*_protocol)},
{"regionId", !_regionId ? boost::any() : boost::any(*_regionId)}
}));
shared_ptr<Alibabacloud_OSS::Client> ossClient;
shared_ptr<Darabonba_FileForm::FileField> fileObj = make_shared<Darabonba_FileForm::FileField>();
shared_ptr<Alibabacloud_OSS::PostObjectRequestHeader> ossHeader = make_shared<Alibabacloud_OSS::PostObjectRequestHeader>();
shared_ptr<Alibabacloud_OSS::PostObjectRequest> uploadRequest = make_shared<Alibabacloud_OSS::PostObjectRequest>();
shared_ptr<Alibabacloud_OSSUtil::RuntimeOptions> ossRuntime = make_shared<Alibabacloud_OSSUtil::RuntimeOptions>();
Alibabacloud_RPCUtil::Client::convert(runtime, ossRuntime);
shared_ptr<SearchImageByPicRequest> searchImageByPicreq = make_shared<SearchImageByPicRequest>();
Alibabacloud_RPCUtil::Client::convert(request, searchImageByPicreq);
authResponse = make_shared<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadResponse>(authClient->authorizeFileUploadWithOptions(authRequest, runtime));
ossConfig->accessKeyId = authResponse->accessKeyId;
ossConfig->endpoint = make_shared<string>(Alibabacloud_RPCUtil::Client::getEndpoint(authResponse->endpoint, authResponse->useAccelerate, _endpointType));
ossClient = make_shared<Alibabacloud_OSS::Client>(ossConfig);
fileObj = make_shared<Darabonba_FileForm::FileField>(map<string, boost::any>({
{"filename", !authResponse->objectKey ? boost::any() : boost::any(*authResponse->objectKey)},
{"content", !request->picContentObject ? boost::any() : boost::any(*request->picContentObject)},
{"contentType", boost::any(string(""))}
}));
ossHeader = make_shared<Alibabacloud_OSS::PostObjectRequestHeader>(map<string, boost::any>({
{"accessKeyId", !authResponse->accessKeyId ? boost::any() : boost::any(*authResponse->accessKeyId)},
{"policy", !authResponse->encodedPolicy ? boost::any() : boost::any(*authResponse->encodedPolicy)},
{"signature", !authResponse->signature ? boost::any() : boost::any(*authResponse->signature)},
{"key", !authResponse->objectKey ? boost::any() : boost::any(*authResponse->objectKey)},
{"file", !fileObj ? boost::any() : boost::any(*fileObj)},
{"successActionStatus", boost::any(string("201"))}
}));
uploadRequest = make_shared<Alibabacloud_OSS::PostObjectRequest>(map<string, boost::any>({
{"bucketName", !authResponse->bucket ? boost::any() : boost::any(*authResponse->bucket)},
{"header", !ossHeader ? boost::any() : boost::any(*ossHeader)}
}));
ossClient->postObject(uploadRequest, ossRuntime);
searchImageByPicreq->picContent = make_shared<string>(string("http://") + string(*authResponse->bucket) + string(".") + string(*authResponse->endpoint) + string("/") + string(*authResponse->objectKey));
shared_ptr<SearchImageByPicResponse> searchImageByPicResp = make_shared<SearchImageByPicResponse>(searchImageByPic(searchImageByPicreq, runtime));
return *searchImageByPicResp;
}
DeleteImageResponse Alibabacloud_ImageSearch20200212::Client::deleteImage(shared_ptr<DeleteImageRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
return DeleteImageResponse(doRequest(make_shared<string>("DeleteImage"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("2020-02-12"), make_shared<string>("AK"), nullptr, make_shared<map<string, boost::any>>(request->toMap()), runtime));
}
AddImageResponse Alibabacloud_ImageSearch20200212::Client::addImage(shared_ptr<AddImageRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
return AddImageResponse(doRequest(make_shared<string>("AddImage"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("2020-02-12"), make_shared<string>("AK"), nullptr, make_shared<map<string, boost::any>>(request->toMap()), runtime));
}
AddImageResponse Alibabacloud_ImageSearch20200212::Client::addImageAdvance(shared_ptr<AddImageAdvanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
// Step 0: init client
shared_ptr<string> accessKeyId = make_shared<string>(_credential->getAccessKeyId());
shared_ptr<string> accessKeySecret = make_shared<string>(_credential->getAccessKeySecret());
shared_ptr<Alibabacloud_RPC::Config> authConfig = make_shared<Alibabacloud_RPC::Config>(map<string, boost::any>({
{"accessKeyId", !accessKeyId ? boost::any() : boost::any(*accessKeyId)},
{"accessKeySecret", !accessKeySecret ? boost::any() : boost::any(*accessKeySecret)},
{"type", boost::any(string("access_key"))},
{"endpoint", boost::any(string("openplatform.aliyuncs.com"))},
{"protocol", !_protocol ? boost::any() : boost::any(*_protocol)},
{"regionId", !_regionId ? boost::any() : boost::any(*_regionId)}
}));
shared_ptr<Alibabacloud_OpenPlatform20191219::Client> authClient = make_shared<Alibabacloud_OpenPlatform20191219::Client>(authConfig);
shared_ptr<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadRequest> authRequest = make_shared<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadRequest>(map<string, boost::any>({
{"product", boost::any(string("ImageSearch"))},
{"regionId", !_regionId ? boost::any() : boost::any(*_regionId)}
}));
shared_ptr<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadResponse> authResponse = make_shared<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadResponse>();
shared_ptr<Alibabacloud_OSS::Config> ossConfig = make_shared<Alibabacloud_OSS::Config>(map<string, boost::any>({
{"accessKeySecret", !accessKeySecret ? boost::any() : boost::any(*accessKeySecret)},
{"type", boost::any(string("access_key"))},
{"protocol", !_protocol ? boost::any() : boost::any(*_protocol)},
{"regionId", !_regionId ? boost::any() : boost::any(*_regionId)}
}));
shared_ptr<Alibabacloud_OSS::Client> ossClient;
shared_ptr<Darabonba_FileForm::FileField> fileObj = make_shared<Darabonba_FileForm::FileField>();
shared_ptr<Alibabacloud_OSS::PostObjectRequestHeader> ossHeader = make_shared<Alibabacloud_OSS::PostObjectRequestHeader>();
shared_ptr<Alibabacloud_OSS::PostObjectRequest> uploadRequest = make_shared<Alibabacloud_OSS::PostObjectRequest>();
shared_ptr<Alibabacloud_OSSUtil::RuntimeOptions> ossRuntime = make_shared<Alibabacloud_OSSUtil::RuntimeOptions>();
Alibabacloud_RPCUtil::Client::convert(runtime, ossRuntime);
shared_ptr<AddImageRequest> addImagereq = make_shared<AddImageRequest>();
Alibabacloud_RPCUtil::Client::convert(request, addImagereq);
authResponse = make_shared<Alibabacloud_OpenPlatform20191219::AuthorizeFileUploadResponse>(authClient->authorizeFileUploadWithOptions(authRequest, runtime));
ossConfig->accessKeyId = authResponse->accessKeyId;
ossConfig->endpoint = make_shared<string>(Alibabacloud_RPCUtil::Client::getEndpoint(authResponse->endpoint, authResponse->useAccelerate, _endpointType));
ossClient = make_shared<Alibabacloud_OSS::Client>(ossConfig);
fileObj = make_shared<Darabonba_FileForm::FileField>(map<string, boost::any>({
{"filename", !authResponse->objectKey ? boost::any() : boost::any(*authResponse->objectKey)},
{"content", !request->picContentObject ? boost::any() : boost::any(*request->picContentObject)},
{"contentType", boost::any(string(""))}
}));
ossHeader = make_shared<Alibabacloud_OSS::PostObjectRequestHeader>(map<string, boost::any>({
{"accessKeyId", !authResponse->accessKeyId ? boost::any() : boost::any(*authResponse->accessKeyId)},
{"policy", !authResponse->encodedPolicy ? boost::any() : boost::any(*authResponse->encodedPolicy)},
{"signature", !authResponse->signature ? boost::any() : boost::any(*authResponse->signature)},
{"key", !authResponse->objectKey ? boost::any() : boost::any(*authResponse->objectKey)},
{"file", !fileObj ? boost::any() : boost::any(*fileObj)},
{"successActionStatus", boost::any(string("201"))}
}));
uploadRequest = make_shared<Alibabacloud_OSS::PostObjectRequest>(map<string, boost::any>({
{"bucketName", !authResponse->bucket ? boost::any() : boost::any(*authResponse->bucket)},
{"header", !ossHeader ? boost::any() : boost::any(*ossHeader)}
}));
ossClient->postObject(uploadRequest, ossRuntime);
addImagereq->picContent = make_shared<string>(string("http://") + string(*authResponse->bucket) + string(".") + string(*authResponse->endpoint) + string("/") + string(*authResponse->objectKey));
shared_ptr<AddImageResponse> addImageResp = make_shared<AddImageResponse>(addImage(addImagereq, runtime));
return *addImageResp;
}
string Alibabacloud_ImageSearch20200212::Client::getEndpoint(shared_ptr<string> productId,
shared_ptr<string> regionId,
shared_ptr<string> endpointRule,
shared_ptr<string> network,
shared_ptr<string> suffix,
shared_ptr<map<string, string>> endpointMap,
shared_ptr<string> endpoint) {
if (!Darabonba_Util::Client::empty(endpoint)) {
return *endpoint;
}
if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)[*regionId]))) {
return (*endpointMap)[*regionId];
}
return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix);
}
| 73.934426 | 283 | 0.741981 | [
"vector"
] |
86684e254f00685024e8fc8ab430d48903790557 | 1,254 | hpp | C++ | src/percept/mesh/mod/smoother/SpacingFieldUtil.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 3 | 2017-08-08T21:06:02.000Z | 2020-01-08T13:23:36.000Z | src/percept/mesh/mod/smoother/SpacingFieldUtil.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2016-12-17T00:18:56.000Z | 2019-08-09T15:29:25.000Z | src/percept/mesh/mod/smoother/SpacingFieldUtil.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2017-11-30T07:02:41.000Z | 2019-08-05T17:07:04.000Z | // Copyright 2002 - 2008, 2010, 2011 National Technology Engineering
// Solutions of Sandia, LLC (NTESS). Under the terms of Contract
// DE-NA0003525 with NTESS, the U.S. Government retains certain rights
// in this software.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef SpacingFieldUtil_hpp
#define SpacingFieldUtil_hpp
#include <percept/Percept.hpp>
#if !defined(NO_GEOM_SUPPORT)
#include <percept/PerceptMesh.hpp>
namespace percept {
class SpacingFieldUtil
{
public:
/// either average or take max of spacing to the nodes
enum SpacingType { SPACING_AVE, SPACING_MAX };
SpacingFieldUtil(PerceptMesh& eMesh, SpacingType type=SPACING_AVE) : m_eMesh(eMesh), m_type(type) {}
/// computes an approximation of the spacing field in x,y,z directions - not rotationally invariant
void compute_spacing_field();
/// find spacing in unit vector dir direction (local computation - is rotationally invariant)
double spacing_at_node_in_direction(const double dir[3], stk::mesh::Entity node, stk::mesh::Selector *element_selector=0);
private:
PerceptMesh& m_eMesh;
const SpacingType m_type;
};
}
#endif
#endif
| 30.585366 | 128 | 0.725678 | [
"mesh",
"vector"
] |
866a5c5c3437b5de9c3ebc4486d89a39ff053ed3 | 4,680 | cc | C++ | src/camera/lib/fake_camera/fake_camera_impl.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | src/camera/lib/fake_camera/fake_camera_impl.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | src/camera/lib/fake_camera/fake_camera_impl.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/camera/lib/fake_camera/fake_camera_impl.h"
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
#include <lib/fit/function.h>
#include <lib/syslog/cpp/logger.h>
#include <zircon/errors.h>
#include "src/camera/lib/fake_stream/fake_stream_impl.h"
namespace camera {
fit::result<std::unique_ptr<FakeCamera>, zx_status_t> FakeCamera::Create(
std::string identifier, std::vector<FakeConfiguration> configurations) {
auto result = FakeCameraImpl::Create(std::move(identifier), std::move(configurations));
if (result.is_error()) {
return fit::error(result.error());
}
return fit::ok(result.take_value());
}
FakeCameraImpl::FakeCameraImpl() : loop_(&kAsyncLoopConfigNoAttachToCurrentThread) {}
FakeCameraImpl::~FakeCameraImpl() {
async::PostTask(loop_.dispatcher(), fit::bind_member(this, &FakeCameraImpl::OnDestruction));
loop_.Quit();
loop_.JoinThreads();
}
static zx_status_t Validate(const std::vector<FakeConfiguration>& configurations) {
zx_status_t status = ZX_OK;
if (configurations.empty()) {
status = ZX_ERR_INVALID_ARGS;
FX_PLOGS(ERROR, status) << "Configurations must not be empty.";
}
for (const auto& configuration : configurations) {
if (configuration.empty()) {
status = ZX_ERR_INVALID_ARGS;
FX_PLOGS(ERROR, status) << "Configuration must not be empty.";
}
for (const auto& stream : configuration) {
if (!stream) {
status = ZX_ERR_INVALID_ARGS;
FX_PLOGS(ERROR, status) << "Stream must be non-null.";
}
}
}
return status;
}
fit::result<std::unique_ptr<FakeCameraImpl>, zx_status_t> FakeCameraImpl::Create(
std::string identifier, std::vector<FakeConfiguration> configurations) {
auto camera = std::make_unique<FakeCameraImpl>();
zx_status_t status = Validate(configurations);
if (status != ZX_OK) {
FX_PLOGS(ERROR, status) << "Configurations failed validation.";
return fit::error(status);
}
camera->identifier_ = std::move(identifier);
camera->configurations_ = std::move(configurations);
for (auto& configuration : camera->configurations_) {
fuchsia::camera3::Configuration real_configuration;
for (auto& stream : configuration) {
auto stream_impl = reinterpret_cast<FakeStreamImpl*>(stream.get());
real_configuration.streams.push_back(stream_impl->properties_);
}
camera->real_configurations_.push_back(std::move(real_configuration));
}
ZX_ASSERT(camera->loop_.StartThread("Fake Camera Loop") == ZX_OK);
return fit::ok(std::move(camera));
}
fidl::InterfaceRequestHandler<fuchsia::camera3::Device> FakeCameraImpl::GetHandler() {
return fit::bind_member(this, &FakeCameraImpl::OnNewRequest);
}
void FakeCameraImpl::SetHardwareMuteState(bool muted) { bindings_.CloseAll(ZX_ERR_NOT_SUPPORTED); }
void FakeCameraImpl::OnNewRequest(fidl::InterfaceRequest<fuchsia::camera3::Device> request) {
if (bindings_.size() > 0) {
request.Close(ZX_ERR_ALREADY_BOUND);
return;
}
bindings_.AddBinding(this, std::move(request), loop_.dispatcher());
}
void FakeCameraImpl::OnDestruction() { bindings_.CloseAll(ZX_ERR_IO_NOT_PRESENT); }
template <class T>
void FakeCameraImpl::SetDisconnectErrorHandler(fidl::InterfacePtr<T>& p) {
p.set_error_handler([this](zx_status_t status) {
FX_PLOGS(ERROR, status) << "Dependent component disconnected.";
bindings_.CloseAll(ZX_ERR_INTERNAL);
});
}
void FakeCameraImpl::GetIdentifier(GetIdentifierCallback callback) { callback(identifier_); }
void FakeCameraImpl::GetConfigurations(GetConfigurationsCallback callback) {
callback(real_configurations_);
}
void FakeCameraImpl::WatchCurrentConfiguration(WatchCurrentConfigurationCallback callback) {
bindings_.CloseAll(ZX_ERR_NOT_SUPPORTED);
}
void FakeCameraImpl::SetCurrentConfiguration(uint32_t index) {
bindings_.CloseAll(ZX_ERR_NOT_SUPPORTED);
}
void FakeCameraImpl::WatchMuteState(WatchMuteStateCallback callback) {
bindings_.CloseAll(ZX_ERR_NOT_SUPPORTED);
}
void FakeCameraImpl::SetSoftwareMuteState(bool muted, SetSoftwareMuteStateCallback callback) {
bindings_.CloseAll(ZX_ERR_NOT_SUPPORTED);
}
void FakeCameraImpl::ConnectToStream(uint32_t index,
fidl::InterfaceRequest<fuchsia::camera3::Stream> request) {
configurations_[current_configuration_index_][index]->GetHandler()(std::move(request));
}
void FakeCameraImpl::Rebind(fidl::InterfaceRequest<Device> request) {
bindings_.CloseAll(ZX_ERR_NOT_SUPPORTED);
}
} // namespace camera
| 32.957746 | 99 | 0.743803 | [
"vector"
] |
866d24d10669e6a13da7edca5e1f9191a5a4c52f | 5,670 | cpp | C++ | 3rdparty/opencv-git/modules/features2d/src/detectors.cpp | luoyongheng/dtslam | d3c2230d45db14c811eff6fd43e119ac39af1352 | [
"BSD-3-Clause"
] | 144 | 2015-01-15T03:38:44.000Z | 2022-02-17T09:07:52.000Z | 3rdparty/opencv-git/modules/features2d/src/detectors.cpp | luoyongheng/dtslam | d3c2230d45db14c811eff6fd43e119ac39af1352 | [
"BSD-3-Clause"
] | 9 | 2015-09-09T06:51:46.000Z | 2020-06-17T14:10:10.000Z | 3rdparty/opencv-git/modules/features2d/src/detectors.cpp | luoyongheng/dtslam | d3c2230d45db14c811eff6fd43e119ac39af1352 | [
"BSD-3-Clause"
] | 58 | 2015-01-14T23:43:49.000Z | 2021-11-15T05:19:08.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
namespace cv
{
/*
* FeatureDetector
*/
FeatureDetector::~FeatureDetector()
{}
void FeatureDetector::detect( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask ) const
{
keypoints.clear();
if( image.empty() )
return;
CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) );
detectImpl( image, keypoints, mask );
}
void FeatureDetector::detect(InputArrayOfArrays _imageCollection, std::vector<std::vector<KeyPoint> >& pointCollection,
InputArrayOfArrays _masks ) const
{
if (_imageCollection.isUMatVector())
{
std::vector<UMat> uimageCollection, umasks;
_imageCollection.getUMatVector(uimageCollection);
_masks.getUMatVector(umasks);
pointCollection.resize( uimageCollection.size() );
for( size_t i = 0; i < uimageCollection.size(); i++ )
detect( uimageCollection[i], pointCollection[i], umasks.empty() ? noArray() : umasks[i] );
return;
}
std::vector<Mat> imageCollection, masks;
_imageCollection.getMatVector(imageCollection);
_masks.getMatVector(masks);
pointCollection.resize( imageCollection.size() );
for( size_t i = 0; i < imageCollection.size(); i++ )
detect( imageCollection[i], pointCollection[i], masks.empty() ? noArray() : masks[i] );
}
/*void FeatureDetector::read( const FileNode& )
{}
void FeatureDetector::write( FileStorage& ) const
{}*/
bool FeatureDetector::empty() const
{
return false;
}
void FeatureDetector::removeInvalidPoints( const Mat& mask, std::vector<KeyPoint>& keypoints )
{
KeyPointsFilter::runByPixelsMask( keypoints, mask );
}
Ptr<FeatureDetector> FeatureDetector::create( const String& detectorType )
{
if( detectorType.compare( "HARRIS" ) == 0 )
{
Ptr<FeatureDetector> fd = FeatureDetector::create("GFTT");
fd->set("useHarrisDetector", true);
return fd;
}
return Algorithm::create<FeatureDetector>("Feature2D." + detectorType);
}
GFTTDetector::GFTTDetector( int _nfeatures, double _qualityLevel,
double _minDistance, int _blockSize,
bool _useHarrisDetector, double _k )
: nfeatures(_nfeatures), qualityLevel(_qualityLevel), minDistance(_minDistance),
blockSize(_blockSize), useHarrisDetector(_useHarrisDetector), k(_k)
{
}
void GFTTDetector::detectImpl( InputArray _image, std::vector<KeyPoint>& keypoints, InputArray _mask) const
{
std::vector<Point2f> corners;
if (_image.isUMat())
{
UMat ugrayImage;
if( _image.type() != CV_8U )
cvtColor( _image, ugrayImage, COLOR_BGR2GRAY );
else
ugrayImage = _image.getUMat();
goodFeaturesToTrack( ugrayImage, corners, nfeatures, qualityLevel, minDistance, _mask,
blockSize, useHarrisDetector, k );
}
else
{
Mat image = _image.getMat(), grayImage = image;
if( image.type() != CV_8U )
cvtColor( image, grayImage, COLOR_BGR2GRAY );
goodFeaturesToTrack( grayImage, corners, nfeatures, qualityLevel, minDistance, _mask,
blockSize, useHarrisDetector, k );
}
keypoints.resize(corners.size());
std::vector<Point2f>::const_iterator corner_it = corners.begin();
std::vector<KeyPoint>::iterator keypoint_it = keypoints.begin();
for( ; corner_it != corners.end(); ++corner_it, ++keypoint_it )
*keypoint_it = KeyPoint( *corner_it, (float)blockSize );
}
}
| 35 | 119 | 0.672487 | [
"vector"
] |
86712f9a66bf8a71ac58b22b15cad8f855fa13b7 | 471 | cpp | C++ | 0137-single-number-ii.cpp | Jamesweng/leetcode | 1711a2a0e31d831e40137203c9abcba0bf56fcad | [
"Apache-2.0"
] | 106 | 2019-06-08T15:23:45.000Z | 2020-04-04T17:56:54.000Z | 0137-single-number-ii.cpp | Jamesweng/leetcode | 1711a2a0e31d831e40137203c9abcba0bf56fcad | [
"Apache-2.0"
] | null | null | null | 0137-single-number-ii.cpp | Jamesweng/leetcode | 1711a2a0e31d831e40137203c9abcba0bf56fcad | [
"Apache-2.0"
] | 3 | 2019-07-13T05:51:29.000Z | 2020-04-04T17:56:57.000Z | class Solution {
public:
int singleNumber(vector<int>& nums) {
int tracking_a = 0, tracking_b = 0;
for (int i = 0; i < nums.size(); ++i) {
int for_tracking_b = tracking_a & nums[i];
int to_reset = tracking_a & tracking_b & nums[i];
tracking_a |= nums[i];
tracking_b |= for_tracking_b;
tracking_a ^= to_reset;
tracking_b ^= to_reset;
}
return tracking_a;
}
};
| 29.4375 | 61 | 0.528662 | [
"vector"
] |
8675b59c409389fc4d44aa3158b3543c363f7814 | 9,190 | cpp | C++ | third_party/omr/fvtest/compilertriltest/SimplifierFoldAbsNegTest.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/fvtest/compilertriltest/SimplifierFoldAbsNegTest.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/fvtest/compilertriltest/SimplifierFoldAbsNegTest.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2017, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include <cmath>
#include "JitTest.hpp"
#include "default_compiler.hpp"
#include "il/Node.hpp"
#include "infra/ILWalk.hpp"
#include "ras/IlVerifier.hpp"
#include "ras/IlVerifierHelpers.hpp"
#include "SharedVerifiers.hpp" //for NoAndIlVerifier
template <typename T> char* prefixForType();
template <> char* prefixForType<int32_t>() { return "i"; }
template <> char* prefixForType<int64_t>() { return "l"; }
template <> char* prefixForType< float>() { return "f"; }
template <> char* prefixForType< double>() { return "d"; }
template <typename T> char* nameForType();
template <> char* nameForType<int32_t>() { return "Int32" ; }
template <> char* nameForType<int64_t>() { return "Int64" ; }
template <> char* nameForType< float>() { return "Float" ; }
template <> char* nameForType< double>() { return "Double"; }
template <typename T> std::vector<T> dataForType();
template <> std::vector<int32_t> dataForType<int32_t>()
{
static int32_t values[] = { 0, 1, 2, -1, -2, 99999, -99999, std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::min() };
return std::vector<int32_t>(values, values + sizeof(values) / sizeof(int32_t));
}
template <> std::vector<int64_t> dataForType<int64_t>()
{
static int64_t values[] = { 0, 1, 2, -1, -2, 99999, -99999, std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::min() };
return std::vector<int64_t>(values, values + sizeof(values) / sizeof(int64_t));
}
template <> std::vector<float> dataForType<float>()
{
static float values[] = { 0, 1, 2, -1, -2, 3.14F, -3.14F, std::numeric_limits<float>::min(), std::numeric_limits<float>::min() };
return std::vector<float>(values, values + sizeof(values) / sizeof(float));
}
template <> std::vector<double> dataForType<double>()
{
static double values[] = { 0, 1, 2, -1, -2, 3.14F, -3.14F, std::numeric_limits<double>::min(), std::numeric_limits<double>::min() };
return std::vector<double>(values, values + sizeof(values) / sizeof(double));
}
class SimplifierFoldAbsNegTestIlVerifierBase : public TR::IlVerifier
{
public:
int32_t verify(TR::ResolvedMethodSymbol *sym)
{
for(TR::PreorderNodeIterator iter(sym->getFirstTreeTop(), sym->comp()); iter.currentTree(); ++iter)
{
int32_t rtn = verifyNode(iter.currentNode());
if(rtn)
return rtn;
}
return 0;
}
protected:
virtual int32_t verifyNode(TR::Node *node) = 0;
};
/**
* Test Fixture for SimplifierFoldAbsNegTest that
* selects only the relevant opts for the test case
*/
template <typename T>
class SimplifierFoldAbsNegTest : public TRTest::JitOptTest
{
public:
SimplifierFoldAbsNegTest()
{
/* Add an optimization.
* You can add as many optimizations as you need, in order,
* using `addOptimization`, or add a group using
* `addOptimizations(omrCompilationStrategies[warm])`.
* This could also be done in test cases themselves.
*/
addOptimization(OMR::treeSimplification);
}
};
typedef ::testing::Types<int32_t, int64_t, float, double> Types;
TYPED_TEST_CASE(SimplifierFoldAbsNegTest, Types);
class NoAbsAbsIlVerifier : public SimplifierFoldAbsNegTestIlVerifierBase
{
protected:
virtual int32_t verifyNode(TR::Node *node)
{
return node->getOpCode().isAbs() && node->getChild(0)->getOpCode().isAbs();
}
};
/*
* method(T parameter)
* return abs(abs(parameter));
*/
TYPED_TEST(SimplifierFoldAbsNegTest, FoldAbsAbs) {
char inputTrees[256];
std::snprintf(inputTrees, sizeof(inputTrees), "(method return=%s args=[%s] "
" (block "
" (%sreturn "
" (%sabs "
" (%sabs (%sload parm=0))))))",
nameForType<TypeParam>(), nameForType<TypeParam>(),
prefixForType<TypeParam>(), prefixForType<TypeParam>(), prefixForType<TypeParam>(), prefixForType<TypeParam>());
auto trees = parseString(inputTrees);
ASSERT_NOTNULL(trees);
Tril::DefaultCompiler compiler(trees);
NoAbsAbsIlVerifier verifier;
ASSERT_EQ(0, compiler.compileWithVerifier(&verifier)) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;
auto entry_point = compiler.getEntryPoint<TypeParam(*)(TypeParam)>();
// Invoke the compiled method, and assert the output is correct.
auto values = dataForType<TypeParam>();
for (auto it = values.begin(); it != values.end(); ++it)
{
EXPECT_EQ(std::abs(*it), entry_point(*it));
}
}
class NoAbsNegIlVerifier : public SimplifierFoldAbsNegTestIlVerifierBase
{
protected:
virtual int32_t verifyNode(TR::Node *node)
{
return node->getOpCode().isAbs() && node->getChild(0)->getOpCode().isNeg();
}
};
/*
* method(T parameter)
* return abs(neg(parameter));
*/
TYPED_TEST(SimplifierFoldAbsNegTest, FoldAbsNeg) {
char inputTrees[256];
std::snprintf(inputTrees, sizeof(inputTrees), "(method return=%s args=[%s] "
" (block "
" (%sreturn "
" (%sabs "
" (%sneg (%sload parm=0))))))",
nameForType<TypeParam>(), nameForType<TypeParam>(),
prefixForType<TypeParam>(), prefixForType<TypeParam>(), prefixForType<TypeParam>(), prefixForType<TypeParam>());
auto trees = parseString(inputTrees);
ASSERT_NOTNULL(trees);
Tril::DefaultCompiler compiler(trees);
NoAbsNegIlVerifier verifier;
ASSERT_EQ(0, compiler.compileWithVerifier(&verifier)) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;
auto entry_point = compiler.getEntryPoint<TypeParam(*)(TypeParam)>();
// Invoke the compiled method, and assert the output is correct.
auto values = dataForType<TypeParam>();
for (auto it = values.begin(); it != values.end(); ++it)
{
EXPECT_EQ(std::abs(*it), entry_point(*it));
}
}
class NoNegNegIlVerifier : public SimplifierFoldAbsNegTestIlVerifierBase
{
protected:
virtual int32_t verifyNode(TR::Node *node)
{
return node->getOpCode().isNeg() && node->getChild(0)->getOpCode().isNeg();
}
};
/*
* method(T parameter)
* return neg(neg(parameter));
*/
TYPED_TEST(SimplifierFoldAbsNegTest, FoldNegNeg) {
char inputTrees[256];
std::snprintf(inputTrees, sizeof(inputTrees), "(method return=%s args=[%s] "
" (block "
" (%sreturn "
" (%sneg "
" (%sneg (%sload parm=0))))))",
nameForType<TypeParam>(), nameForType<TypeParam>(),
prefixForType<TypeParam>(), prefixForType<TypeParam>(), prefixForType<TypeParam>(), prefixForType<TypeParam>());
auto trees = parseString(inputTrees);
ASSERT_NOTNULL(trees);
Tril::DefaultCompiler compiler(trees);
NoNegNegIlVerifier verifier;
ASSERT_EQ(0, compiler.compileWithVerifier(&verifier)) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;
auto entry_point = compiler.getEntryPoint<TypeParam(*)(TypeParam)>();
// Invoke the compiled method, and assert the output is correct.
auto values = dataForType<TypeParam>();
for (auto it = values.begin(); it != values.end(); ++it)
{
EXPECT_EQ(*it, entry_point(*it));
}
}
| 37.81893 | 138 | 0.597933 | [
"vector"
] |
869979794696bf11f2a2dedb3e79b72aa3d2093d | 28,725 | cpp | C++ | extract_misc/brainvisa_ext/RII_Struct3D-4.1.0/RicCorticalThicknessByNormal/src/GM_Normal.cpp | binarybottle/mindboggle_sidelined | 1431d4877f4ceae384486fb66798bc22e6471af7 | [
"Apache-2.0"
] | 3 | 2019-07-20T05:36:03.000Z | 2020-12-23T07:47:43.000Z | extract_misc/brainvisa_ext/RII_Struct3D-4.1.0/RicCorticalThicknessByNormal/src/GM_Normal.cpp | binarybottle/mindboggle_sidelined | 1431d4877f4ceae384486fb66798bc22e6471af7 | [
"Apache-2.0"
] | 2 | 2020-11-30T10:18:42.000Z | 2020-12-24T06:29:47.000Z | extract_misc/brainvisa_ext/RII_Struct3D-4.1.0/RicCorticalThicknessByNormal/src/GM_Normal.cpp | binarybottle/mindboggle_sidelined | 1431d4877f4ceae384486fb66798bc22e6471af7 | [
"Apache-2.0"
] | null | null | null | // --------------------------- GM_Normal.cpp ---------------------------------
/**
\file
Routines to find the distance between two meshes by intersecting
normals from one mesh with triangles of the other.
Copyright (C) 2007 by Bill Rogers, Research Imaging Center, UTHSCSA
rogers@uthscsa.edu
*/
#include "RicMesh.h"
#include "RicTexture.h"
#include "GM_Normal.h"
#include <math.h>
#include <pthread.h>
#include "RicUtil.h"
/// Structure to pass info to the threads for threaded version
typedef struct { int *inner_vlist; ///< array of indices for inner mesh vertices
int n_in_verts; ///< number of inner mesh vertices
int *inner_plist; ///< array of indicies for inner mesh polygons
int n_in_polys; ///< number of inner mesh polygon indices
int *outer_plist; ///< array of indicies for outer mesh polygons
int n_out_polys; ///< number of outer mesh polygon indices
RicMesh *inner_mesh; ///< inner mesh
RicMesh *outer_mesh; ///< outer mesh
float *inner_thick; ///< thickness array - one node for each inner mesh vertex
RicMesh *closest_vects; ///< mesh of vectors connecting inner and outer meshes
float mind; ///< minimum allowed distance from vertex
float maxd; ///< maximum allowed distance from vertex
float sfac; ///< scale factor for normal line
} NormThreadStuff;
/// thread function declaration
void *FindNormalDistThread( void *tstruct );
///////////////////////// FindNormalDistBrute ////////////////////////
/**
This routine determines the thickness at each inner mesh vertex by
finding the intersection of a line normal of that vertex with a triangle
in the outer mesh
@param inner_mesh - white matter mesh
@param outer_mesh - gray matter mesh
@param closest_vects - output mesh with vectors connecting nearest points
@param thick - output texture to put inner-outer distances in - one value for each inner vertex
@param nflip - normal direction, if -1 flip normals
@param mind - min distance to search for normal intersection with other mesh
@param maxd - max distance to search for normal intersection with other mesh
@return - 1 on success
*/
int FindNormalDistBrute(RicMesh *inner_mesh, RicMesh *outer_mesh, RicMesh *closest_vects,
RicTexture *thick, int nflip, float mind, float maxd)
{
// check to see that the gm mesh and the texture are the same size
if ( inner_mesh->v_size != thick->size )
{
cout << "FindNormalDistSubdivide - error inner mesh and texture not same size"<<endl;
return 0;
}
int i,j;
Point minpnt;
int ninfound, noutfound;
float indist,outdist;
Point pint;
// scale factor for normal line end point - includes normal direction
float sfac = nflip*maxd;
float maxdsqu = maxd*maxd; // square of distance for comparisons
// populate the thickness map with ERRVAL as default value
for ( i=0 ; i<thick->size ; ++i ) thick->nodes[i] = ERRVAL;
// work from inner to outer
for ( i=0 ; i<inner_mesh->v_size ; ++i )
{
// skip if vertex labeled as not to use
if ( inner_mesh->vertices[i].label == 1 )
continue;
Point p0,p1; // line normal to vertex
Vector n0,n1; // normals from vertex and opposing polygon
p0 = inner_mesh->vertices[i].pnt;
n0 = inner_mesh->normals[i].pnt;
// make a long line in the direction of the normal
p1.x = p0.x + sfac*n0.x; // add normal to vertex to get line
p1.y = p0.y + sfac*n0.y;
p1.z = p0.z + sfac*n0.z;
// test against all polygons in the inner mesh
// to find the closest inner polygon
ninfound=0;
indist=ERRVAL;
Point t0,t1,t2;
float d0,d1,d2;
for ( j=0 ; j<inner_mesh->p_size ; ++j )
{
// see if the line intersects the plane of the current polygon
// skip if it does not
t0 = inner_mesh->vertices[inner_mesh->polygons[j].vidx[0]].pnt;
t1 = inner_mesh->vertices[inner_mesh->polygons[j].vidx[1]].pnt;
t2 = inner_mesh->vertices[inner_mesh->polygons[j].vidx[2]].pnt;
// skip if any of the triangle points are our current vertex
if ( (d0=distsqu(p0,t0)) < 0.1 ) continue;
if ( (d1=distsqu(p0,t1)) < 0.1 ) continue;
if ( (d2=distsqu(p0,t2)) < 0.1 ) continue;
// skip if all vertices are out of search distance
if ( d0>maxdsqu && d1>maxdsqu && d2>maxdsqu ) continue;
if ( !line_intersect_triangle(t0, t1, t2,p0,p1,&pint) )
continue;
// compare the distance to the current min wm distance
++ninfound;
float d = dist(pint,p0);
if ( d==0 )
continue;
if ( d < indist )
indist = d;
}
// test against all polygons in the outer mesh
noutfound=0;
outdist = ERRVAL;
for ( j=0 ; j<outer_mesh->p_size ; ++j )
{
// see if the line intersects the plane of the current polygon
// skip if it does not
Point t0,t1,t2;
t0 = outer_mesh->vertices[outer_mesh->polygons[j].vidx[0]].pnt;
t1 = outer_mesh->vertices[outer_mesh->polygons[j].vidx[1]].pnt;
t2 = outer_mesh->vertices[outer_mesh->polygons[j].vidx[2]].pnt;
// skip if any of the triangle points are our current vertex
if ( (d0=distsqu(p0,t0)) < 0.1 ) continue;
if ( (d1=distsqu(p0,t1)) < 0.1 ) continue;
if ( (d2=distsqu(p0,t2)) < 0.1 ) continue;
// skip if all vertices are out of search distance
if ( d0>maxd && d1>maxd && d2>maxd ) continue;
if ( !line_intersect_triangle(t0, t1, t2,p0,p1,&pint) )
continue;
// compare the distance to the current min wm distance
++noutfound;
float d = dist(pint,p0);
if ( (d < indist) && (d < maxd) ) // must be closer than nearest wm polygon
{
if ( d < outdist ) // see if closer than last suitable distance
{
outdist = d;
minpnt = pint;
}
}
}
// check against minimum distance
if ( outdist < mind )
outdist = mind;
// see if a vertex found but too far away
if ( outdist == ERRVAL && noutfound > 0 )
outdist = maxd;
// assign distance for vertex
thick->nodes[i] = outdist;
// assign vector for points connecting surfaces
if ( outdist != ERRVAL && outdist > mind && outdist < maxd )
{
vertex cvert(minpnt.x,minpnt.y,minpnt.z);
closest_vects->assign_node(2*i, inner_mesh->vertices[i]);
closest_vects->assign_normal(2*i,inner_mesh->normals[i]);
closest_vects->assign_node(2*i+1, cvert);
closest_vects->assign_normal(2*i+1, inner_mesh->normals[i]);
closest_vects->assign_polygon(i, 2*i, 2*i+1, 0);
}
}
return 1;
}
//////////////////////// FindNormalDistSubdivide //////////////////////////////////
/**
Find the distance between two meshes by taking a normal from the vertex
of one mesh and intersecting the second mesh. The normal is extended
to the maximum distance to search for an intersection.
Care is taken so that the normal distance chosen does not intersect any
surfaces between end points.
This version subdivides the meshes into smaller portions so that the search will
be faster.
@param inner_mesh - grey matter mesh
@param outer_mesh - white matter mesh
@param closest_vects - output mesh with vectors connecting nearest points
@param thick - output texture to put inner-outer distances in - one value for each inner vertex
@param nsub - number of subdivisions for each axis
@param over - amount of overlap to add to subdivisions
@param nflip - normal direction, if -1 flip normals
@param mind - min distance to search for normal intersection with other mesh
@param maxd - max distance to search for normal intersection with other mesh
@return - 1 on success
*/
int FindNormalDistSubdivide(RicMesh *inner_mesh, RicMesh *outer_mesh, RicMesh *closest_vects,
RicTexture *thick, int nsub, float over, int nflip, float mind, float maxd)
{
int i,j,k,l,m,n;
// check to see that the inner mesh and the texture are the same size
if ( inner_mesh->v_size != thick->size )
{
cout << "FindNormalDistSubdivide - error inner mesh and texture not same size"<<endl;
return 0;
}
// array pointers for vertex and polygon lists for subdividing the meshes
int *inner_vlist;
int *inner_plist;
int *outer_plist;
// allocate memory for the arrays
inner_vlist = new int[inner_mesh->v_size];
inner_plist = new int[inner_mesh->p_size];
outer_plist = new int[outer_mesh->p_size];
// scale factor for normal line end point - includes normal direction
float sfac = nflip*maxd;
float maxdsqu = maxd*maxd; // square of distance for comparisons
// make sure that limits have been calculated for the gm mesh
inner_mesh->calc_limits();
// find the step size for each axis for an iteration
float xinc,yinc,zinc;
xinc = (inner_mesh->xmax-inner_mesh->xmin)/(float)nsub;
yinc = (inner_mesh->ymax-inner_mesh->ymin)/(float)nsub;
zinc = (inner_mesh->zmax-inner_mesh->zmin)/(float)nsub;
// initialize the thickness values to ERRVAL
for ( i=0 ; i<thick->size ; ++i ) thick->nodes[i]=ERRVAL;
// the number of actual searches will be the cube of the subdivision number
float xstart,ystart,zstart; // starting values for vertex search
float xend,yend,zend; // ending value for vertex search
float xstart2,ystart2,zstart2; // starting values for vertex search
float xend2,yend2,zend2; // ending value for vertex search
int n_in_verts = 0; // number of inner mesh vertices found in a subdivision
int n_in_polys = 0; // number of inner mesh polygons found in a subdivision
int n_out_polys = 0;// number of outer mesh polygons found in a subdivision
for ( i=0 ; i<nsub ; ++i )
{
xstart = inner_mesh->xmin + i*xinc;
xend = xstart+xinc;
for ( j=0 ; j<nsub ; ++j )
{
ystart = inner_mesh->ymin + j*yinc;
yend = ystart+yinc;
for ( k=0 ; k<nsub ; ++k )
{
///////////////// preprocess for current subdivision ///////////
// find all the vertices and polygons in these bounds
n_in_verts = n_in_polys = n_out_polys = 0;
zstart = inner_mesh->zmin + k*zinc;
zend = zstart + zinc;
// find the appropriate gm vertices in this box
for ( l=0 ; l<inner_mesh->v_size ; ++l )
{
if ( inner_mesh->vertices[l].pnt.x >= xstart && inner_mesh->vertices[l].pnt.x <= xend
&& inner_mesh->vertices[l].pnt.y >= ystart && inner_mesh->vertices[l].pnt.y <= yend
&& inner_mesh->vertices[l].pnt.z >= zstart && inner_mesh->vertices[l].pnt.z <= zend )
{
inner_vlist[n_in_verts++] = l;
}
}
// allow for overlap
xstart2 = xstart-over;
ystart2 = ystart-over;
zstart2 = zstart-over;
xend2 = xend+over;
yend2 = yend+over;
zend2 = zend+over;
// look for inner triangles that fit in this box
for ( l=0 ; l<inner_mesh->p_size ; ++l )
{
// check each triangle vertex
for ( m=0 ; m<3 ; ++m )
{
int vidx = inner_mesh->polygons[l].vidx[m];
if ( inner_mesh->vertices[vidx].pnt.x >= xstart2
&& inner_mesh->vertices[vidx].pnt.x <= xend2
&& inner_mesh->vertices[vidx].pnt.y >= ystart2
&& inner_mesh->vertices[vidx].pnt.y <= yend2
&& inner_mesh->vertices[vidx].pnt.z >= zstart2
&& inner_mesh->vertices[vidx].pnt.z <= zend )
{
inner_plist[n_in_polys++] = l;
break; // no need to check the others
}
}
}
// look for outer triangles that fit in this box
for ( l=0 ; l<outer_mesh->p_size ; ++l )
{
// check each triangle vertex
for ( m=0 ; m<3 ; ++m )
{
int vidx = outer_mesh->polygons[l].vidx[m];
if ( outer_mesh->vertices[vidx].pnt.x >= xstart2
&& outer_mesh->vertices[vidx].pnt.x <= xend2
&& outer_mesh->vertices[vidx].pnt.y >= ystart2
&& outer_mesh->vertices[vidx].pnt.y <= yend2
&& outer_mesh->vertices[vidx].pnt.z >= zstart2
&& outer_mesh->vertices[vidx].pnt.z <= zend2 )
{
outer_plist[n_out_polys++] = l;
break; // no need to check the others
}
}
}
//////////////////// Crunch the Subdivision ///////////////////
// repeat for each inner vertex
for ( l=0 ; l<n_in_verts ; ++l )
{
// skip if vertex labeled as not to use
if ( inner_mesh->vertices[inner_vlist[l]].label == 1 )
continue;
Point p0,p1; // line normal to vertex
Vector n0,n1; // normals from vertex and opposing polygon
p0 = inner_mesh->vertices[inner_vlist[l]].pnt;
n0 = inner_mesh->normals[inner_vlist[l]].pnt;
// make a long line in the direction of the normal
p1.x = p0.x + sfac*n0.x; // add normal to vertex to get line
p1.y = p0.y + sfac*n0.y;
p1.z = p0.z + sfac*n0.z;
Point minpnt;
int ninfound, noutfound;
float indist,outdist;
Point pint;
ninfound=0;
indist=ERRVAL;
// First find the closest inner mesh triangle to our inner vertex
// This is used to check to see if the normal intersects the
// inner surface before the outer one
int v0,v1,v2; // vertex indices for current poly
Point t0,t1,t2; // triangle vertex points
float d0,d1,d2; // distance between triangle vertices and current point
for ( m=0 ; m<n_in_polys ; ++m )
{
// see if the line intersects the plane of the current polygon
// skip if it does not
v0 = inner_mesh->polygons[inner_plist[m]].vidx[0];
v1 = inner_mesh->polygons[inner_plist[m]].vidx[1];
v2 = inner_mesh->polygons[inner_plist[m]].vidx[2];
t0 = inner_mesh->vertices[v0].pnt;
t1 = inner_mesh->vertices[v1].pnt;
t2 = inner_mesh->vertices[v2].pnt;
// skip if any of the triangle points are our current vertex
if ( (d0=distsqu(p0,t0)) < 0.1 ) continue;
if ( (d1=distsqu(p0,t1)) < 0.1 ) continue;
if ( (d2=distsqu(p0,t2)) < 0.1 ) continue;
// skip if all vertices are out of search distance
if ( d0>maxdsqu && d1>maxdsqu && d2>maxdsqu ) continue;
// see if intersection point lines not within triangle then skip
if ( !line_intersect_triangle(t0, t1, t2,p0,p1,&pint) )
continue;
// compare the distance to the current min inner distance
++ninfound;
float d = dist(pint,p0);
if ( d==0 )
continue;
if ( d < indist )
indist = d;
} // end loop to find distance to nearest inner surface
// test against all polygons in the outer mesh
noutfound=0;
outdist = ERRVAL;
for ( m=0 ; m<n_out_polys ; ++m )
{
// see if the line intersects the plane of the current polygon
// skip if it does not
v0 = outer_mesh->polygons[outer_plist[m]].vidx[0];
v1 = outer_mesh->polygons[outer_plist[m]].vidx[1];
v2 = outer_mesh->polygons[outer_plist[m]].vidx[2];
t0 = outer_mesh->vertices[v0].pnt;
t1 = outer_mesh->vertices[v1].pnt;
t2 = outer_mesh->vertices[v2].pnt;
// skip if any of the triangle points are our current vertex
if ( (d0=distsqu(p0,t0)) < 0.1 ) continue;
if ( (d1=distsqu(p0,t1)) < 0.1 ) continue;
if ( (d2=distsqu(p0,t2)) < 0.1 ) continue;
// skip if all vertices are out of search distance
if ( d0>maxd && d1>maxd && d2>maxd ) continue;
// see if intersection point lines not within triangle then skip
if ( !line_intersect_triangle(t0, t1, t2,p0,p1,&pint) )
continue;
// compare the distance to the current min inner distance
++noutfound;
float d = dist(pint,p0);
if ( (d < indist) && d < maxd ) // must be closer than nearest inner polygon
{
if ( d < outdist ) // see if closer than last suitable distance
{
outdist = d;
minpnt = pint;
}
}
}
// check against minimum distance
if ( outdist < mind )
outdist = mind;
// see if a vertex found but too far away
if ( outdist == ERRVAL && noutfound > 0 )
outdist = maxd;
// assign distance for vertex
thick->nodes[inner_vlist[l]] = outdist;
// assign vector for points connecting surfaces
if ( outdist != ERRVAL && outdist > mind && outdist < maxd)
{
vertex cvert(minpnt.x,minpnt.y,minpnt.z);
n = inner_vlist[l];
closest_vects->assign_node(2*n, inner_mesh->vertices[n]);
closest_vects->assign_normal(2*n,inner_mesh->normals[n]);
closest_vects->assign_node(2*n+1, cvert);
closest_vects->assign_normal(2*n+1, inner_mesh->normals[n]);
closest_vects->assign_polygon(n, 2*n, 2*n+1, 0);
}
} // end of subdivision
} // z search
} // y search
} // x search
// clean up memory allocation
delete [] inner_vlist;
delete [] inner_plist;
delete [] outer_plist;
return 1;
}
//////////////////////// FindNormalDistThreads //////////////////////////////////
/**
Find the distance between two meshes by taking a normal from the vertex
of one mesh and intersecting the second mesh. The normal is extended
to the maximum distance to search for an intersection.
Care is taken so that the normal distance chosen does not intersect any
surfaces between end points.
This version subdivides the meshes into smaller portions so that the search will
be faster. In addition, this version assigns a separate thread to each subdivision.
@param inner_mesh - white matter mesh
@param outer_mesh - gray matter mesh
@param closest_vects - output mesh with vectors connecting nearest points
@param thick - output texture to put inner-outer distances in - one value for each inner vertex
@param nsub - number of subdivisions for each axis
@param over - amount of overlap to add to subdivisions
@param nflip - normal direction, if -1 flip normals
@param mind - min distance to search for normal intersection with other mesh
@param maxd - max distance to search for normal intersection with other mesh
@return - 1 on success
*/
int FindNormalDistThreads(RicMesh *inner_mesh, RicMesh *outer_mesh, RicMesh *closest_vects,
RicTexture *thick, int nsub, float over, int nflip, float mind, float maxd)
{
int i,j,k,l,m;
// check to see that the inner mesh and the texture are the same size
if ( inner_mesh->v_size != thick->size )
{
cout << "FindNormalDistThreads - error inner mesh and texture not same size"<<endl;
return 0;
}
// array pointers for vertex and polygon lists for subdividing the meshes
int **inv_mat; // inner mesh vertices
int **inp_mat; // inner mesh polygons
int **outp_mat; // outer mesh polygons
// number of threads
int nthreads = nsub*nsub*nsub;
// allocate memory for the arrays for vertices and polygons
matrix(&inv_mat,nthreads,inner_mesh->v_size); // inner vertices
matrix(&inp_mat,nthreads,inner_mesh->p_size); // inner polygons
matrix(&outp_mat,nthreads,outer_mesh->p_size); // outer polygons
// allocate thread pointers
pthread_t *bfThreadPtr;
bfThreadPtr = new pthread_t[nthreads];
// allocate array of structures passing data to threads
NormThreadStuff *pstuff;
pstuff = new NormThreadStuff[nthreads];
// scale factor for normal line end point - includes normal direction
float sfac = nflip*maxd;
// make sure that limits have been calculated for the gm mesh
inner_mesh->calc_limits();
// find the step size for each axis for an iteration
float xinc,yinc,zinc;
xinc = (inner_mesh->xmax-inner_mesh->xmin)/(float)nsub;
yinc = (inner_mesh->ymax-inner_mesh->ymin)/(float)nsub;
zinc = (inner_mesh->zmax-inner_mesh->zmin)/(float)nsub;
// initialize the thickness values to ERRVAL
for ( i=0 ; i<thick->size ; ++i ) thick->nodes[i]=ERRVAL;
// the number of actual searches will be the cube of the subdivision number
float xstart,ystart,zstart; // starting values for vertex search
float xend,yend,zend; // ending value for vertex search
float xstart2,ystart2,zstart2; // starting values for vertex search
float xend2,yend2,zend2; // ending value for vertex search
int n_in_verts = 0; // number of inner mesh vertices found in a subdivision
int n_in_polys = 0; // number of inner mesh polygons found in a subdivision
int n_out_polys = 0;// number of outer mesh polygons found in a subdivision
int cur_thread;
////// repeat for each subdivision //////
for ( i=0 ; i<nsub ; ++i )
{
xstart = inner_mesh->xmin + i*xinc;
xend = xstart+xinc;
for ( j=0 ; j<nsub ; ++j )
{
ystart = inner_mesh->ymin + j*yinc;
yend = ystart+yinc;
for ( k=0 ; k<nsub ; ++k )
{
///////////////// preprocess for current subdivision ///////////
// find all the vertices and polygons in these bounds
cur_thread = (i*nsub*nsub)+j*nsub+k;
n_in_verts = n_in_polys = n_out_polys = 0;
zstart = inner_mesh->zmin + k*zinc;
zend = zstart + zinc;
// find the appropriate gm vertices in this box
for ( l=0 ; l<inner_mesh->v_size ; ++l )
{
if ( inner_mesh->vertices[l].pnt.x >= xstart && inner_mesh->vertices[l].pnt.x <= xend
&& inner_mesh->vertices[l].pnt.y >= ystart && inner_mesh->vertices[l].pnt.y <= yend
&& inner_mesh->vertices[l].pnt.z >= zstart && inner_mesh->vertices[l].pnt.z <= zend )
{
inv_mat[cur_thread][n_in_verts++] = l;
}
}
// allow for overlap
xstart2 = xstart-over;
ystart2 = ystart-over;
zstart2 = zstart-over;
xend2 = xend+over;
yend2 = yend+over;
zend2 = zend+over;
// look for inner triangles that fit in this box
for ( l=0 ; l<inner_mesh->p_size ; ++l )
{
// check each triangle vertex
for ( m=0 ; m<3 ; ++m )
{
int vidx = inner_mesh->polygons[l].vidx[m];
if ( inner_mesh->vertices[vidx].pnt.x >= xstart2
&& inner_mesh->vertices[vidx].pnt.x <= xend2
&& inner_mesh->vertices[vidx].pnt.y >= ystart2
&& inner_mesh->vertices[vidx].pnt.y <= yend2
&& inner_mesh->vertices[vidx].pnt.z >= zstart2
&& inner_mesh->vertices[vidx].pnt.z <= zend )
{
inp_mat[cur_thread][n_in_polys++] = l;
break; // no need to check the others
}
}
}
// look for outer triangles that fit in this box
for ( l=0 ; l<outer_mesh->p_size ; ++l )
{
// check each triangle vertex
for ( m=0 ; m<3 ; ++m )
{
int vidx = outer_mesh->polygons[l].vidx[m];
if ( outer_mesh->vertices[vidx].pnt.x >= xstart2
&& outer_mesh->vertices[vidx].pnt.x <= xend2
&& outer_mesh->vertices[vidx].pnt.y >= ystart2
&& outer_mesh->vertices[vidx].pnt.y <= yend2
&& outer_mesh->vertices[vidx].pnt.z >= zstart2
&& outer_mesh->vertices[vidx].pnt.z <= zend2 )
{
outp_mat[cur_thread][n_out_polys++] = l;
break; // no need to check the others
}
}
}
//////////////////// Crunch the Subdivision ///////////////////
// fill up structure with data to pass to thread
pstuff[cur_thread].inner_vlist = inv_mat[cur_thread];
pstuff[cur_thread].n_in_verts = n_in_verts;
pstuff[cur_thread].inner_plist = inp_mat[cur_thread];
pstuff[cur_thread].n_in_polys = n_in_polys;
pstuff[cur_thread].outer_plist = outp_mat[cur_thread];
pstuff[cur_thread].n_out_polys = n_out_polys;
pstuff[cur_thread].outer_mesh = outer_mesh;
pstuff[cur_thread].inner_mesh = inner_mesh;
pstuff[cur_thread].closest_vects = closest_vects;
pstuff[cur_thread].inner_thick = thick->nodes;
pstuff[cur_thread].mind = mind;
pstuff[cur_thread].maxd = maxd;
pstuff[cur_thread].sfac = sfac;
// now create a thread for this subdivision
pthread_create(&bfThreadPtr[cur_thread],NULL, FindNormalDistThread,
(void *)&pstuff[cur_thread]);
} // z search
} // y search
} // x search
// now wait for all the threads to finish
for (i=0 ; i<nthreads ; ++i)
{
pthread_join(bfThreadPtr[i],NULL);
//fprintf(stderr,"Thread %d finished\n",i);
}
// clean up memory allocation
free_matrix(inv_mat);
free_matrix(inp_mat);
free_matrix(outp_mat);
delete [] bfThreadPtr;
delete [] pstuff;
return 1;
}
////////////////////////// FindNormalDistThread ///////////////////////////
/**
This is the thread spun off for each subdivision in the threaded version.
Find the distance between two meshes by taking a normal from the vertex
of one mesh and intersecting the second mesh. The normal is extended
to the maximum distance to search for an intersection.
@param tstruct - pointer to NormThreadStuff structure
@return - null pointer
*/
void *FindNormalDistThread( void *tstruct )
{
NormThreadStuff *stuff;
stuff = (NormThreadStuff*) tstruct;
// square of distance for comparisons
float maxdsqu = stuff->maxd*stuff->maxd;
// now do the brute force search for this subdivision
int l,m,n;
// repeat for each inner vertex
for ( l=0 ; l<stuff->n_in_verts ; ++l )
{
// skip if vertex labeled as not to use
if ( stuff->inner_mesh->vertices[stuff->inner_vlist[l]].label == 1 )
continue;
Point p0,p1; // line normal to vertex
Vector n0; // normal from vertex
p0 = stuff->inner_mesh->vertices[stuff->inner_vlist[l]].pnt;
n0 = stuff->inner_mesh->normals[stuff->inner_vlist[l]].pnt;
// make a long line in the direction of the normal
p1.x = p0.x + stuff->sfac*n0.x; // add normal to vertex to get line
p1.y = p0.y + stuff->sfac*n0.y;
p1.z = p0.z + stuff->sfac*n0.z;
Point minpnt;
int ninfound, noutfound;
float indist,outdist;
Point pint;
ninfound=0;
indist=ERRVAL;
// First find the closest inner mesh triangle to our inner vertex
// This is used to check to see if the normal intersects the
// inner surface before the outer one
int v0,v1,v2; // vertex indices for current poly
Point t0,t1,t2; // triangle vertex points
float d0,d1,d2; // distance between triangle vertices and current point
for ( m=0 ; m<stuff->n_in_polys ; ++m )
{
// see if the line intersects the plane of the current polygon
// skip if it does not
v0 = stuff->inner_mesh->polygons[stuff->inner_plist[m]].vidx[0];
v1 = stuff->inner_mesh->polygons[stuff->inner_plist[m]].vidx[1];
v2 = stuff->inner_mesh->polygons[stuff->inner_plist[m]].vidx[2];
t0 = stuff->inner_mesh->vertices[v0].pnt;
t1 = stuff->inner_mesh->vertices[v1].pnt;
t2 = stuff->inner_mesh->vertices[v2].pnt;
// skip if any of the triangle points are our current vertex
if ( (d0=distsqu(p0,t0)) < 0.1 ) continue;
if ( (d1=distsqu(p0,t1)) < 0.1 ) continue;
if ( (d2=distsqu(p0,t2)) < 0.1 ) continue;
// skip if all vertices are out of search distance
if ( d0>maxdsqu && d1>maxdsqu && d2>maxdsqu ) continue;
// see if intersection point lines not within triangle then skip
if ( !line_intersect_triangle(t0, t1, t2,p0,p1,&pint) )
continue;
// compare the distance to the current min inner distance
++ninfound;
float d = dist(pint,p0);
if ( d==0 )
continue;
if ( d < indist )
indist = d;
} // end loop to find distance to nearest inner surface
// test against all polygons in the outer mesh
noutfound=0;
outdist = ERRVAL;
for ( m=0 ; m<stuff->n_out_polys ; ++m )
{
// see if the line intersects the plane of the current polygon
// skip if it does not
v0 = stuff->outer_mesh->polygons[stuff->outer_plist[m]].vidx[0];
v1 = stuff->outer_mesh->polygons[stuff->outer_plist[m]].vidx[1];
v2 = stuff->outer_mesh->polygons[stuff->outer_plist[m]].vidx[2];
t0 = stuff->outer_mesh->vertices[v0].pnt;
t1 = stuff->outer_mesh->vertices[v1].pnt;
t2 = stuff->outer_mesh->vertices[v2].pnt;
// skip if any of the triangle points are our current vertex
if ( (d0=distsqu(p0,t0)) < 0.1 ) continue;
if ( (d1=distsqu(p0,t1)) < 0.1 ) continue;
if ( (d2=distsqu(p0,t2)) < 0.1 ) continue;
// skip if all vertices are out of search distance
if ( d0>maxdsqu && d1>maxdsqu && d2>maxdsqu ) continue;
// see if intersection point lines not within triangle then skip
if ( !line_intersect_triangle(t0, t1, t2,p0,p1,&pint) )
continue;
// compare the distance to the current min inner distance
++noutfound;
float d = dist(pint,p0);
if ( (d < indist) && d < stuff->maxd ) // must be closer than nearest inner polygon
{
if ( d < outdist ) // see if closer than last suitable distance
{
outdist = d;
minpnt = pint;
}
}
}
// check against minimum distance
if ( outdist < stuff->mind )
outdist = stuff->mind;
// see if a vertex found but too far away
if ( outdist == ERRVAL && noutfound > 0 )
outdist = stuff->maxd;
// assign distance for vertex
stuff->inner_thick[stuff->inner_vlist[l]] = outdist;
// assign vector for points connecting surfaces
if ( outdist != ERRVAL && outdist > stuff->mind && outdist < stuff->maxd)
{
vertex cvert(minpnt.x,minpnt.y,minpnt.z);
n = stuff->inner_vlist[l];
stuff->closest_vects->assign_node(2*n, stuff->inner_mesh->vertices[n]);
stuff->closest_vects->assign_normal(2*n,stuff->inner_mesh->normals[n]);
stuff->closest_vects->assign_node(2*n+1, cvert);
stuff->closest_vects->assign_normal(2*n+1, stuff->inner_mesh->normals[n]);
stuff->closest_vects->assign_polygon(n, 2*n, 2*n+1, 0);
}
} // end of subdivision
return NULL;
}
| 33.994083 | 95 | 0.655701 | [
"mesh",
"vector"
] |
86a262808b08377b8448f9d7ff11deb9daeb2f2f | 1,306 | cpp | C++ | examples/example5.cpp | mambaru/wjson | 48de30f1247564ab16c93fc824a14b182145ff90 | [
"MIT"
] | 21 | 2016-09-29T10:25:12.000Z | 2020-07-07T23:19:51.000Z | examples/example5.cpp | mambaru/wjson | 48de30f1247564ab16c93fc824a14b182145ff90 | [
"MIT"
] | 10 | 2016-11-17T09:09:35.000Z | 2021-10-03T11:47:18.000Z | examples/example5.cpp | mambaru/wjson | 48de30f1247564ab16c93fc824a14b182145ff90 | [
"MIT"
] | 6 | 2016-09-29T12:05:06.000Z | 2022-02-17T13:05:18.000Z | #include <wjson/json.hpp>
#include <wjson/strerror.hpp>
#include <iostream>
int main()
{
// Одномерный массив
typedef wjson::value<int> int_json;
typedef std::vector<int> vint_t;
typedef wjson::array< std::vector<int_json> > vint_json;
std::string json="[ 1,\t2,\r3,\n4, /*пять*/ 5 ]";
vint_t vint;
vint_json::serializer()(vint, json.begin(), json.end(), fas_nullptr);
json.clear();
vint_json::serializer()(vint, std::back_inserter(json));
std::cout << json << std::endl;
// Двумерный массив (вектор векторов )
typedef std::vector< vint_t > vvint_t;
typedef wjson::array< std::vector<vint_json> > vvint_json;
json="[ [], [1], [2, 3], [4, 5, 6] ]";
vvint_t vvint;
vvint_json::serializer()(vvint, json.begin(), json.end(), fas_nullptr);
json.clear();
vvint_json::serializer()(vvint, std::back_inserter(json));
std::cout << json << std::endl;
// Трехмерный массив (вектор векторов векторов)
typedef std::vector< vvint_t > vvvint_t;
typedef wjson::array< std::vector<vvint_json> > vvvint_json;
json="[ [[]], [[1]], [[2], [3]], [[4], [5, 6] ] ]";
vvvint_t vvvint;
vvvint_json::serializer()(vvvint, json.begin(), json.end(), fas_nullptr);
json.clear();
vvvint_json::serializer()(vvvint, std::back_inserter(json));
std::cout << json << std::endl;
}
| 33.487179 | 75 | 0.649311 | [
"vector"
] |
86a69e52a03593aa2883684eb4d2678262d87267 | 32,574 | cpp | C++ | com/netfx/src/clr/utilcode/md5.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/clr/utilcode/md5.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/clr/utilcode/md5.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// md5.cpp
//
#include "stdafx.h"
#include <stdlib.h>
#include <wtypes.h>
#include "md5.h"
void MD5::Init(BOOL fConstructed)
{
// These two fields are read only, and so initialization thereof can be
// omitted on the second and subsequent hashes using this same instance.
//
if (!fConstructed)
{
memset(m_padding, 0, 64);
m_padding[0]=0x80;
}
m_cbitHashed = 0;
m_cbData = 0;
m_a = 0x67452301; // magic
m_b = 0xefcdab89; // ... constants
m_c = 0x98badcfe; // ... per
m_d = 0x10325476; // .. RFC1321
}
void MD5::HashMore(const void* pvInput, ULONG cbInput)
// Hash the additional data into the state
{
const BYTE* pbInput = (const BYTE*)pvInput;
m_cbitHashed += (cbInput<<3);
ULONG cbRemaining = 64 - m_cbData;
if (cbInput < cbRemaining)
{
// It doesn't fill up the buffer, so just store it
memcpy(&m_data[m_cbData], pbInput, cbInput);
m_cbData += cbInput;
}
else
{
// It does fill up the buffer. Fill up all that it will take
memcpy(&m_data[m_cbData], pbInput, cbRemaining);
// Hash the now-full buffer
MD5Transform(m_state, (ULONG*)&m_data[0]);
cbInput -= cbRemaining;
pbInput += cbRemaining;
// Hash the data in 64-byte runs, starting just after what we've copied
while (cbInput >= 64)
{
MD5Transform(m_state, (ULONG*)pbInput);
pbInput += 64;
cbInput -= 64;
}
// Store the tail of the input into the buffer
memcpy(&m_data[0], pbInput, cbInput);
m_cbData = cbInput;
}
}
void MD5::GetHashValue(MD5HASHDATA* phash)
// Finalize the hash by appending the necessary padding and length count. Then
// return the final hash value.
{
union {
ULONGLONG cbitHashed;
BYTE rgb[8];
}u;
// Remember how many bits there were in the input data
u.cbitHashed = m_cbitHashed;
// Calculate amount of padding needed. Enough so total byte count hashed is 56 mod 64
ULONG cbPad = (m_cbData < 56 ? 56-m_cbData : 120-m_cbData);
// Hash the padding
HashMore(&m_padding[0], cbPad);
// Hash the (before padding) bit length
HashMore(&u.rgb[0], 8);
// Return the hash value
memcpy(phash, &m_a, 16);
}
// We have two implementations of the core 'transform' at the heart
// of this hash: one in C, another in x86 assembler.
//
#if !defined(_X86_)
#define USE_C_MD5_TRANSFORM
#endif
#ifdef USE_C_MD5_TRANSFORM
////////////////////////////////////////////////////////////////
//
// ROTATE_LEFT should be a macro that updates its first operand
// with its present value rotated left by the amount of its
// second operand, which is always a constant.
//
// One way to portably do it would be
//
// #define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n))))
// #define ROTATE_LEFT(x,n) (x) = ROL(x,n)
//
// but our compiler has an intrinsic!
#define ROTATE_LEFT(x,n) (x) = _lrotl(x,n)
////////////////////////////////////////////////////////////////
//
// Constants used in each of the various rounds
#define MD5_S11 7
#define MD5_S12 12
#define MD5_S13 17
#define MD5_S14 22
#define MD5_S21 5
#define MD5_S22 9
#define MD5_S23 14
#define MD5_S24 20
#define MD5_S31 4
#define MD5_S32 11
#define MD5_S33 16
#define MD5_S34 23
#define MD5_S41 6
#define MD5_S42 10
#define MD5_S43 15
#define MD5_S44 21
////////////////////////////////////////////////////////////////
//
// The core twiddle functions
// #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) // the function per the standard
#define F(x, y, z) ((((z) ^ (y)) & (x)) ^ (z)) // an alternate encoding
// #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) // the function per the standard
#define G(x, y, z) ((((x) ^ (y)) & (z)) ^ (y)) // an alternate encoding
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
#define AC(ac) ((ULONG)(ac))
////////////////////////////////////////////////////////////////
#define FF(a, b, c, d, x, s, ac) { \
(a) += F (b,c,d) + (x) + (AC(ac)); \
ROTATE_LEFT (a, s); \
(a) += (b); \
}
////////////////////////////////////////////////////////////////
#define GG(a, b, c, d, x, s, ac) { \
(a) += G (b,c,d) + (x) + (AC(ac)); \
ROTATE_LEFT (a, s); \
(a) += (b); \
}
////////////////////////////////////////////////////////////////
#define HH(a, b, c, d, x, s, ac) { \
(a) += H (b,c,d) + (x) + (AC(ac)); \
ROTATE_LEFT (a, s); \
(a) += (b); \
}
////////////////////////////////////////////////////////////////
#define II(a, b, c, d, x, s, ac) { \
(a) += I (b,c,d) + (x) + (AC(ac)); \
ROTATE_LEFT (a, s); \
(a) += (b); \
}
void __stdcall MD5Transform(ULONG state[4], const ULONG* data)
{
ULONG a=state[0];
ULONG b=state[1];
ULONG c=state[2];
ULONG d=state[3];
// Round 1
FF (a, b, c, d, data[ 0], MD5_S11, 0xd76aa478); // 1
FF (d, a, b, c, data[ 1], MD5_S12, 0xe8c7b756); // 2
FF (c, d, a, b, data[ 2], MD5_S13, 0x242070db); // 3
FF (b, c, d, a, data[ 3], MD5_S14, 0xc1bdceee); // 4
FF (a, b, c, d, data[ 4], MD5_S11, 0xf57c0faf); // 5
FF (d, a, b, c, data[ 5], MD5_S12, 0x4787c62a); // 6
FF (c, d, a, b, data[ 6], MD5_S13, 0xa8304613); // 7
FF (b, c, d, a, data[ 7], MD5_S14, 0xfd469501); // 8
FF (a, b, c, d, data[ 8], MD5_S11, 0x698098d8); // 9
FF (d, a, b, c, data[ 9], MD5_S12, 0x8b44f7af); // 10
FF (c, d, a, b, data[10], MD5_S13, 0xffff5bb1); // 11
FF (b, c, d, a, data[11], MD5_S14, 0x895cd7be); // 12
FF (a, b, c, d, data[12], MD5_S11, 0x6b901122); // 13
FF (d, a, b, c, data[13], MD5_S12, 0xfd987193); // 14
FF (c, d, a, b, data[14], MD5_S13, 0xa679438e); // 15
FF (b, c, d, a, data[15], MD5_S14, 0x49b40821); // 16
// Round 2
GG (a, b, c, d, data[ 1], MD5_S21, 0xf61e2562); // 17
GG (d, a, b, c, data[ 6], MD5_S22, 0xc040b340); // 18
GG (c, d, a, b, data[11], MD5_S23, 0x265e5a51); // 19
GG (b, c, d, a, data[ 0], MD5_S24, 0xe9b6c7aa); // 20
GG (a, b, c, d, data[ 5], MD5_S21, 0xd62f105d); // 21
GG (d, a, b, c, data[10], MD5_S22, 0x2441453); // 22
GG (c, d, a, b, data[15], MD5_S23, 0xd8a1e681); // 23
GG (b, c, d, a, data[ 4], MD5_S24, 0xe7d3fbc8); // 24
GG (a, b, c, d, data[ 9], MD5_S21, 0x21e1cde6); // 25
GG (d, a, b, c, data[14], MD5_S22, 0xc33707d6); // 26
GG (c, d, a, b, data[ 3], MD5_S23, 0xf4d50d87); // 27
GG (b, c, d, a, data[ 8], MD5_S24, 0x455a14ed); // 28
GG (a, b, c, d, data[13], MD5_S21, 0xa9e3e905); // 29
GG (d, a, b, c, data[ 2], MD5_S22, 0xfcefa3f8); // 30
GG (c, d, a, b, data[ 7], MD5_S23, 0x676f02d9); // 31
GG (b, c, d, a, data[12], MD5_S24, 0x8d2a4c8a); // 32
// Round 3
HH (a, b, c, d, data[ 5], MD5_S31, 0xfffa3942); // 33
HH (d, a, b, c, data[ 8], MD5_S32, 0x8771f681); // 34
HH (c, d, a, b, data[11], MD5_S33, 0x6d9d6122); // 35
HH (b, c, d, a, data[14], MD5_S34, 0xfde5380c); // 36
HH (a, b, c, d, data[ 1], MD5_S31, 0xa4beea44); // 37
HH (d, a, b, c, data[ 4], MD5_S32, 0x4bdecfa9); // 38
HH (c, d, a, b, data[ 7], MD5_S33, 0xf6bb4b60); // 39
HH (b, c, d, a, data[10], MD5_S34, 0xbebfbc70); // 40
HH (a, b, c, d, data[13], MD5_S31, 0x289b7ec6); // 41
HH (d, a, b, c, data[ 0], MD5_S32, 0xeaa127fa); // 42
HH (c, d, a, b, data[ 3], MD5_S33, 0xd4ef3085); // 43
HH (b, c, d, a, data[ 6], MD5_S34, 0x4881d05); // 44
HH (a, b, c, d, data[ 9], MD5_S31, 0xd9d4d039); // 45
HH (d, a, b, c, data[12], MD5_S32, 0xe6db99e5); // 46
HH (c, d, a, b, data[15], MD5_S33, 0x1fa27cf8); // 47
HH (b, c, d, a, data[ 2], MD5_S34, 0xc4ac5665); // 48
// Round 4
II (a, b, c, d, data[ 0], MD5_S41, 0xf4292244); // 49
II (d, a, b, c, data[ 7], MD5_S42, 0x432aff97); // 50
II (c, d, a, b, data[14], MD5_S43, 0xab9423a7); // 51
II (b, c, d, a, data[ 5], MD5_S44, 0xfc93a039); // 52
II (a, b, c, d, data[12], MD5_S41, 0x655b59c3); // 53
II (d, a, b, c, data[ 3], MD5_S42, 0x8f0ccc92); // 54
II (c, d, a, b, data[10], MD5_S43, 0xffeff47d); // 55
II (b, c, d, a, data[ 1], MD5_S44, 0x85845dd1); // 56
II (a, b, c, d, data[ 8], MD5_S41, 0x6fa87e4f); // 57
II (d, a, b, c, data[15], MD5_S42, 0xfe2ce6e0); // 58
II (c, d, a, b, data[ 6], MD5_S43, 0xa3014314); // 59
II (b, c, d, a, data[13], MD5_S44, 0x4e0811a1); // 60
II (a, b, c, d, data[ 4], MD5_S41, 0xf7537e82); // 61
II (d, a, b, c, data[11], MD5_S42, 0xbd3af235); // 62
II (c, d, a, b, data[ 2], MD5_S43, 0x2ad7d2bb); // 63
II (b, c, d, a, data[ 9], MD5_S44, 0xeb86d391); // 64
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
#else
__declspec(naked) void __stdcall MD5Transform(ULONG state[4], const ULONG* data)
// This implementation uses some pretty funky arithmetic identities
// to effect its logic. Way cool! Kudos to whomever came up with this.
//
{
__asm
{
push ebx
push esi
mov ecx,dword ptr [esp+10h] // data pointer to ecx
push edi
mov edi,dword ptr [esp+10h] // state pointer to edi
push ebp
mov ebx,dword ptr [edi+4] // ebx = b
mov ebp,dword ptr [edi+8] // ebp = c
mov edx,dword ptr [edi+0Ch] // edx = d
mov eax,edx // eax = d
xor eax,ebp // eax = d xor c
and eax,ebx // eax = (d xor c) ^ b
xor eax,edx // eax = ((d xor c) ^ b) xor d
add eax,dword ptr [ecx] // eax = (((d xor c) ^ b) xor d) + data[0]
add eax,dword ptr [edi] // eax = (((d xor c) ^ b) xor d) + data[0] + a
sub eax,28955B88h // eax = (((d xor c) ^ b) xor d) + data[0] + a + ac
rol eax,7 // rotated left in the standard way
lea esi,dword ptr [eax+ebx] // store temp sum in esi
mov eax,ebp // eax = c
xor eax,ebx // eax = b xor c
and eax,esi // eax = (b xor c) ^ ...
xor eax,ebp
add eax,dword ptr [ecx+4]
lea eax,dword ptr [edx+eax-173848AAh]
rol eax,0Ch
lea edx,dword ptr [esi+eax]
mov eax,ebx
xor eax,esi
and eax,edx
xor eax,ebx
add eax,dword ptr [ecx+8]
lea eax,dword ptr [ebp+eax+242070DBh]
rol eax,11h
lea edi,dword ptr [edx+eax]
mov eax,edx
xor eax,esi
and eax,edi
xor eax,esi
add eax,dword ptr [ecx+0Ch]
lea eax,dword ptr [ebx+eax-3E423112h]
rol eax,16h
lea ebx,dword ptr [edi+eax]
mov eax,edx
xor eax,edi
and eax,ebx
xor eax,edx
add eax,dword ptr [ecx+10h]
lea eax,dword ptr [esi+eax-0A83F051h]
rol eax,7
lea esi,dword ptr [ebx+eax]
mov eax,edi
xor eax,ebx
and eax,esi
xor eax,edi
add eax,dword ptr [ecx+14h]
lea eax,dword ptr [edx+eax+4787C62Ah]
rol eax,0Ch
lea edx,dword ptr [esi+eax]
mov eax,ebx
xor eax,esi
and eax,edx
xor eax,ebx
add eax,dword ptr [ecx+18h]
lea eax,dword ptr [edi+eax-57CFB9EDh]
rol eax,11h
lea edi,dword ptr [edx+eax]
mov eax,edx
xor eax,esi
and eax,edi
xor eax,esi
add eax,dword ptr [ecx+1Ch]
lea eax,dword ptr [ebx+eax-2B96AFFh]
rol eax,16h
lea ebx,dword ptr [edi+eax]
mov eax,edx
xor eax,edi
and eax,ebx
xor eax,edx
add eax,dword ptr [ecx+20h]
lea eax,dword ptr [esi+eax+698098D8h]
rol eax,7
lea esi,dword ptr [ebx+eax]
mov eax,edi
xor eax,ebx
and eax,esi
xor eax,edi
add eax,dword ptr [ecx+24h]
lea eax,dword ptr [edx+eax-74BB0851h]
rol eax,0Ch
lea edx,dword ptr [esi+eax]
mov eax,ebx
xor eax,esi
and eax,edx
xor eax,ebx
add eax,dword ptr [ecx+28h]
lea eax,dword ptr [edi+eax-0A44Fh]
rol eax,11h
lea edi,dword ptr [edx+eax]
mov eax,edx
xor eax,esi
and eax,edi
xor eax,esi
add eax,dword ptr [ecx+2Ch]
lea eax,dword ptr [ebx+eax-76A32842h]
rol eax,16h
lea ebx,dword ptr [edi+eax]
mov eax,edx
xor eax,edi
and eax,ebx
xor eax,edx
add eax,dword ptr [ecx+30h]
lea eax,dword ptr [esi+eax+6B901122h]
rol eax,7
lea esi,dword ptr [ebx+eax]
mov eax,edi
xor eax,ebx
and eax,esi
xor eax,edi
add eax,dword ptr [ecx+34h]
lea eax,dword ptr [edx+eax-2678E6Dh]
rol eax,0Ch
lea edx,dword ptr [esi+eax]
mov eax,ebx
xor eax,esi
and eax,edx
xor eax,ebx
add eax,dword ptr [ecx+38h]
lea eax,dword ptr [edi+eax-5986BC72h]
rol eax,11h
lea edi,dword ptr [edx+eax]
mov eax,edx
xor eax,esi
and eax,edi
xor eax,esi
add eax,dword ptr [ecx+3Ch]
lea eax,dword ptr [ebx+eax+49B40821h]
rol eax,16h
lea ebx,dword ptr [edi+eax]
mov eax,edi
xor eax,ebx
and eax,edx
xor eax,edi
add eax,dword ptr [ecx+4]
lea eax,dword ptr [esi+eax-9E1DA9Eh]
rol eax,5
lea esi,dword ptr [ebx+eax]
mov eax,ebx
xor eax,esi
and eax,edi
xor eax,ebx
add eax,dword ptr [ecx+18h]
lea eax,dword ptr [edx+eax-3FBF4CC0h]
rol eax,9
add eax,esi
mov edx,eax // edx = x
xor edx,esi // edx = (x xor y)
and edx,ebx // edx = ((x xor y) and z)
xor edx,esi // edx = (((x xor y) and z) xor y)
add edx,dword ptr [ecx+2Ch] // edx = (((x xor y) and z) xor y) + data
lea edx,dword ptr [edi+edx+265E5A51h] // edx = (((x xor y) and z) xor y) + data + ...
rol edx,0Eh
lea edi,dword ptr [eax+edx]
mov edx,eax
xor edx,edi
and edx,esi
xor edx,eax
add edx,dword ptr [ecx]
lea edx,dword ptr [ebx+edx-16493856h]
mov ebx,edi
rol edx,14h
add edx,edi
xor ebx,edx
and ebx,eax
xor ebx,edi
add ebx,dword ptr [ecx+14h]
lea esi,dword ptr [esi+ebx-29D0EFA3h]
mov ebx,edx
rol esi,5
add esi,edx
xor ebx,esi
and ebx,edi
xor ebx,edx
add ebx,dword ptr [ecx+28h]
lea eax,dword ptr [eax+ebx+2441453h]
rol eax,9
lea ebx,dword ptr [esi+eax]
mov eax,ebx
xor eax,esi
and eax,edx
xor eax,esi
add eax,dword ptr [ecx+3Ch]
lea eax,dword ptr [edi+eax-275E197Fh]
rol eax,0Eh
lea edi,dword ptr [ebx+eax]
mov eax,ebx
xor eax,edi
and eax,esi
xor eax,ebx
add eax,dword ptr [ecx+10h]
lea eax,dword ptr [edx+eax-182C0438h]
mov edx,edi
rol eax,14h
add eax,edi
xor edx,eax
and edx,ebx
xor edx,edi
add edx,dword ptr [ecx+24h]
lea edx,dword ptr [esi+edx+21E1CDE6h]
rol edx,5
lea esi,dword ptr [eax+edx]
mov edx,eax
xor edx,esi
and edx,edi
xor edx,eax
add edx,dword ptr [ecx+38h]
lea edx,dword ptr [ebx+edx-3CC8F82Ah]
rol edx,9
add edx,esi
mov ebx,edx
xor ebx,esi
and ebx,eax
xor ebx,esi
add ebx,dword ptr [ecx+0Ch]
lea edi,dword ptr [edi+ebx-0B2AF279h]
mov ebx,edx
rol edi,0Eh
add edi,edx
xor ebx,edi
and ebx,esi
xor ebx,edx
add ebx,dword ptr [ecx+20h]
lea eax,dword ptr [eax+ebx+455A14EDh]
rol eax,14h
lea ebx,dword ptr [edi+eax]
mov eax,edi
xor eax,ebx
and eax,edx
xor eax,edi
add eax,dword ptr [ecx+34h]
lea eax,dword ptr [esi+eax-561C16FBh]
rol eax,5
lea esi,dword ptr [ebx+eax]
mov eax,ebx
xor eax,esi
and eax,edi
xor eax,ebx
add eax,dword ptr [ecx+8]
lea eax,dword ptr [edx+eax-3105C08h]
rol eax,9
lea edx,dword ptr [esi+eax]
mov eax,edx
xor eax,esi
and eax,ebx
xor eax,esi
add eax,dword ptr [ecx+1Ch]
lea eax,dword ptr [edi+eax+676F02D9h]
rol eax,0Eh
lea edi,dword ptr [edx+eax]
mov eax,edx
xor eax,edi
mov ebp,eax
and ebp,esi
xor ebp,edx
add ebp,dword ptr [ecx+30h]
lea ebx,dword ptr [ebx+ebp-72D5B376h]
rol ebx,14h
add ebx,edi
mov ebp,ebx
xor ebp,eax
add ebp,dword ptr [ecx+14h]
lea eax,dword ptr [esi+ebp-5C6BEh]
mov esi,edi
rol eax,4
add eax,ebx
xor esi,ebx
xor esi,eax
add esi,dword ptr [ecx+20h]
lea edx,dword ptr [edx+esi-788E097Fh]
rol edx,0Bh
add edx,eax
mov esi,edx
mov ebp,edx
xor esi,ebx
xor esi,eax
add esi,dword ptr [ecx+2Ch]
lea esi,dword ptr [edi+esi+6D9D6122h]
rol esi,10h
add esi,edx
xor ebp,esi
mov edi,ebp
xor edi,eax
add edi,dword ptr [ecx+38h]
lea edi,dword ptr [ebx+edi-21AC7F4h]
rol edi,17h
add edi,esi
mov ebx,edi
xor ebx,ebp
add ebx,dword ptr [ecx+4]
lea eax,dword ptr [eax+ebx-5B4115BCh]
mov ebx,esi
rol eax,4
add eax,edi
xor ebx,edi
xor ebx,eax
add ebx,dword ptr [ecx+10h]
lea edx,dword ptr [edx+ebx+4BDECFA9h]
rol edx,0Bh
add edx,eax
mov ebx,edx
xor ebx,edi
xor ebx,eax
add ebx,dword ptr [ecx+1Ch]
lea esi,dword ptr [esi+ebx-944B4A0h]
mov ebx,edx
rol esi,10h
add esi,edx
xor ebx,esi
mov ebp,ebx
xor ebp,eax
add ebp,dword ptr [ecx+28h]
lea edi,dword ptr [edi+ebp-41404390h]
rol edi,17h
add edi,esi
mov ebp,edi
xor ebp,ebx
mov ebx,esi
add ebp,dword ptr [ecx+34h]
xor ebx,edi
lea eax,dword ptr [eax+ebp+289B7EC6h]
rol eax,4
add eax,edi
xor ebx,eax
add ebx,dword ptr [ecx]
lea edx,dword ptr [edx+ebx-155ED806h]
rol edx,0Bh
add edx,eax
mov ebx,edx
xor ebx,edi
xor ebx,eax
add ebx,dword ptr [ecx+0Ch]
lea esi,dword ptr [esi+ebx-2B10CF7Bh]
mov ebx,edx
rol esi,10h
add esi,edx
xor ebx,esi
mov ebp,ebx
xor ebp,eax
add ebp,dword ptr [ecx+18h]
lea edi,dword ptr [edi+ebp+4881D05h]
rol edi,17h
add edi,esi
mov ebp,edi
xor ebp,ebx
mov ebx,esi
add ebp,dword ptr [ecx+24h]
xor ebx,edi
lea eax,dword ptr [eax+ebp-262B2FC7h]
rol eax,4
add eax,edi
xor ebx,eax
add ebx,dword ptr [ecx+30h]
lea edx,dword ptr [edx+ebx-1924661Bh]
rol edx,0Bh
add edx,eax
mov ebx,edx
xor ebx,edi
xor ebx,eax
add ebx,dword ptr [ecx+3Ch]
lea esi,dword ptr [esi+ebx+1FA27CF8h]
mov ebx,edx
rol esi,10h
add esi,edx
xor ebx,esi
xor ebx,eax
add ebx,dword ptr [ecx+8]
lea edi,dword ptr [edi+ebx-3B53A99Bh]
mov ebx,edx
rol edi,17h
not ebx
add edi,esi
or ebx,edi
xor ebx,esi
add ebx,dword ptr [ecx]
lea eax,dword ptr [eax+ebx-0BD6DDBCh]
mov ebx,esi
rol eax,6
not ebx
add eax,edi
or ebx,eax
xor ebx,edi
add ebx,dword ptr [ecx+1Ch]
lea edx,dword ptr [edx+ebx+432AFF97h]
mov ebx,edi
rol edx,0Ah
not ebx
add edx,eax
or ebx,edx
xor ebx,eax
add ebx,dword ptr [ecx+38h]
lea esi,dword ptr [esi+ebx-546BDC59h]
mov ebx,eax
rol esi,0Fh
not ebx
add esi,edx
or ebx,esi
xor ebx,edx
add ebx,dword ptr [ecx+14h]
lea edi,dword ptr [edi+ebx-36C5FC7h]
mov ebx,edx
rol edi,15h
not ebx
add edi,esi
or ebx,edi
xor ebx,esi
add ebx,dword ptr [ecx+30h]
lea eax,dword ptr [eax+ebx+655B59C3h]
mov ebx,esi
rol eax,6
not ebx
add eax,edi
or ebx,eax
xor ebx,edi
add ebx,dword ptr [ecx+0Ch]
lea edx,dword ptr [edx+ebx-70F3336Eh]
rol edx,0Ah
add edx,eax
mov ebx,edi
not ebx
or ebx,edx
xor ebx,eax
add ebx,dword ptr [ecx+28h]
lea esi,dword ptr [esi+ebx-100B83h]
mov ebx,eax
rol esi,0Fh
not ebx
add esi,edx
or ebx,esi
xor ebx,edx
add ebx,dword ptr [ecx+4]
lea edi,dword ptr [edi+ebx-7A7BA22Fh]
mov ebx,edx
rol edi,15h
not ebx
add edi,esi
or ebx,edi
xor ebx,esi
add ebx,dword ptr [ecx+20h]
lea eax,dword ptr [eax+ebx+6FA87E4Fh]
mov ebx,esi
rol eax,6
not ebx
add eax,edi
or ebx,eax
xor ebx,edi
add ebx,dword ptr [ecx+3Ch]
lea edx,dword ptr [edx+ebx-1D31920h]
rol edx,0Ah
lea ebx,dword ptr [eax+edx]
mov edx,edi
not edx
or edx,ebx
xor edx,eax
add edx,dword ptr [ecx+18h]
lea edx,dword ptr [esi+edx-5CFEBCECh]
rol edx,0Fh
lea esi,dword ptr [ebx+edx]
mov edx,eax
not edx
or edx,esi
xor edx,ebx
add edx,dword ptr [ecx+34h]
lea edx,dword ptr [edi+edx+4E0811A1h]
rol edx,15h
lea edi,dword ptr [esi+edx]
mov edx,ebx
not edx
or edx,edi
xor edx,esi
add edx,dword ptr [ecx+10h]
lea eax,dword ptr [eax+edx-8AC817Eh]
rol eax,6
lea edx,dword ptr [edi+eax]
mov eax,esi
not eax
or eax,edx
xor eax,edi
add eax,dword ptr [ecx+2Ch]
lea eax,dword ptr [ebx+eax-42C50DCBh]
rol eax,0Ah
lea ebx,dword ptr [edx+eax]
mov eax,edi
not eax
or eax,ebx
xor eax,edx
add eax,dword ptr [ecx+8]
lea eax,dword ptr [esi+eax+2AD7D2BBh]
rol eax,0Fh
lea esi,dword ptr [ebx+eax]
mov eax,edx
not eax
or eax,esi
xor eax,ebx
add eax,dword ptr [ecx+24h]
lea eax,dword ptr [edi+eax-14792C6Fh]
mov edi,dword ptr [esp+14h]
rol eax,15h
add eax,esi
add edx,dword ptr [edi] // add in starting state
add eax,dword ptr [edi+4]
add esi,dword ptr [edi+8]
add ebx,dword ptr [edi+0Ch]
pop ebp
mov dword ptr [edi],edx // store back new state
mov dword ptr [edi+4],eax
mov dword ptr [edi+8],esi
mov dword ptr [edi+0Ch],ebx
pop edi
pop esi
pop ebx
ret 8
}
}
#endif
| 36.848416 | 108 | 0.370357 | [
"transform"
] |
86b47410cc6753ecf36aa8348934604e6c72911d | 1,297 | cpp | C++ | src/active.cpp | robertblackwell/node-addon-example | 05a5949dbe6c8279e4d5b612134a475690971556 | [
"MIT"
] | null | null | null | src/active.cpp | robertblackwell/node-addon-example | 05a5949dbe6c8279e4d5b612134a475690971556 | [
"MIT"
] | null | null | null | src/active.cpp | robertblackwell/node-addon-example | 05a5949dbe6c8279e4d5b612134a475690971556 | [
"MIT"
] | null | null | null |
#include "active.h"
#include "CoreFoundation/CoreFoundation.h"
#include "CoreServices/CoreServices.h"
#include "check.h"
#include <algorithm>
#include <assert.h>
#include <iostream>
#include <memory>
#include <napi.h>
#include <node_api.h>
#include <stdio.h>
#include <string>
#include <vector>
typedef std::vector<CallerContext*> CallerList;
static std::vector<CallerContext*> activeCallers;
void
ActiveCallers::init()
{
activeCallers = std::vector<CallerContext*>();
}
void
ActiveCallers::addCaller(CallerContext* caller)
{
if (ActiveCallers::findCaller(caller)) {
throw std::string("ActiveCaller::addCaller the caller already exists");
}
activeCallers.push_back(caller);
}
int
ActiveCallers::findCaller(CallerContext* caller)
{
std::vector<CallerContext*>::iterator it = std::find(activeCallers.begin(), activeCallers.end(), caller);
if (it != activeCallers.end()) {
int index = std::distance(activeCallers.begin(), it);
return index;
}
return -1;
}
void
ActiveCallers::removeCaller(CallerContext* caller)
{
int index = ActiveCallers::findCaller(caller);
if (index == -1) {
throw std::string("ActiveCaller::removeCaller - caller is not in active list");
}
activeCallers.erase(activeCallers.begin() + index);
}
| 24.942308 | 109 | 0.703932 | [
"vector"
] |
86b70f2b59d5d3e2b08fb5c31039aa9a3b1fa465 | 827 | cpp | C++ | Codility_MissingInteger.cpp | CharlieGearsTech/Codility | b0c4355eb68f05f24390075e3fe2fe555d40b6b9 | [
"MIT"
] | 1 | 2021-01-31T22:59:59.000Z | 2021-01-31T22:59:59.000Z | Codility_MissingInteger.cpp | CharlieGearsTech/Codility | b0c4355eb68f05f24390075e3fe2fe555d40b6b9 | [
"MIT"
] | null | null | null | Codility_MissingInteger.cpp | CharlieGearsTech/Codility | b0c4355eb68f05f24390075e3fe2fe555d40b6b9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <assert.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int solution(vector<int> &A)
{
vector<int> incr(100000u,0u);
vector<int> mask(100000u,1u);
vector<int> result;
std::partial_sum(mask.begin(),mask.end(),incr.begin());
sort(A.begin(),A.end());
set_difference(incr.begin(),incr.end(),A.begin(),A.end(),inserter(result, result.begin()));
return *min_element(result.begin(),result.end());
}
int main()
{
vector<int> v= {1,3,6,4,1,2};
int res= 0;
res= solution(v);
cout<<res<<endl;
assert(res==5);
v.clear();
v= {1,2,3};
res= solution(v);
cout<<res<<endl;
assert(res==4);
v= {-1,-3};
res= solution(v);
cout<<res<<endl;
assert(res==1);
return 0;
}
| 17.595745 | 95 | 0.586457 | [
"vector"
] |
86b90f7b1d5b782423b904d9e5ffb81e5b19b3f7 | 2,346 | cpp | C++ | src/mock/shelly_mock_rpc_service.cpp | timoschilling/shelly-homekit | c8923b3f82608a725e14734929d6b37b9472e96f | [
"Apache-2.0"
] | 1,061 | 2020-02-05T10:21:19.000Z | 2022-03-30T14:10:08.000Z | src/mock/shelly_mock_rpc_service.cpp | timoschilling/shelly-homekit | c8923b3f82608a725e14734929d6b37b9472e96f | [
"Apache-2.0"
] | 867 | 2020-02-05T15:47:10.000Z | 2022-03-31T23:17:40.000Z | src/mock/shelly_mock_rpc_service.cpp | timoschilling/shelly-homekit | c8923b3f82608a725e14734929d6b37b9472e96f | [
"Apache-2.0"
] | 119 | 2020-02-09T10:01:27.000Z | 2022-03-31T08:35:21.000Z | /*
* Copyright (c) Shelly-HomeKit Contributors
* All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "shelly_mock.hpp"
#include <cmath>
#include "mgos_rpc.h"
#include "shelly_mock_pm.hpp"
#include "shelly_mock_temp_sensor.hpp"
namespace shelly {
std::vector<MockPowerMeter *> g_mock_pms;
MockTempSensor *g_mock_sys_temp_sensor = nullptr;
static void MockSetSysTempHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi,
struct mg_str args) {
float temp = NAN;
json_scanf(args.p, args.len, ri->args_fmt, &temp);
g_mock_sys_temp_sensor->SetValue(temp);
mg_rpc_send_responsef(ri, nullptr);
(void) fi;
(void) cb_arg;
}
static void MockSetPM(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi, struct mg_str args) {
int id = -1;
float w = NAN, wh = NAN;
json_scanf(args.p, args.len, ri->args_fmt, &id, &w, &wh);
if (id < 0) {
mg_rpc_send_errorf(ri, 400, "%s is required", "id");
return;
}
if (std::isnan(w) && std::isnan(wh)) {
mg_rpc_send_errorf(ri, 400, "%s is required", "w or wh");
return;
}
for (auto *pm : g_mock_pms) {
if (pm->id() == id) {
if (!std::isnan(w)) pm->SetPowerW(w);
if (!std::isnan(wh)) pm->SetEnergyWH(wh);
mg_rpc_send_responsef(ri, nullptr);
return;
}
}
mg_rpc_send_errorf(ri, 404, "pm %d not found", id);
(void) fi;
(void) cb_arg;
}
void MockRPCInit() {
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.Mock.SetSysTemp",
"{temp: %f}", MockSetSysTempHandler, nullptr);
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.Mock.SetPM",
"{id: %d, w: %f, wh: %f}", MockSetPM, nullptr);
}
} // namespace shelly
| 30.467532 | 79 | 0.652174 | [
"vector"
] |
86bda81b8bd4f1f2d81bb860c612b3f4606b84b7 | 1,343 | cpp | C++ | Codes/leetcode-with-errichto/may-challange/failed-29CourseSchedule.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | Codes/leetcode-with-errichto/may-challange/failed-29CourseSchedule.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | Codes/leetcode-with-errichto/may-challange/failed-29CourseSchedule.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | #include <bits/stdc++.h>
using namespace std;
class Solution {
int n, end;
int *g;
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
// best guess input = vector<pair<int,int> >dekhte jerokom, thik seirokom
this->n = numCourses;
g = new int[numCourses+10];
this->end = -1;
for(int i=0; i<=numCourses; i++) { g[i] = end; }
for(int i=0; i<prerequisites.size(); i++) {
int v = prerequisites[i][0];
int u = prerequisites[i][1];
g[u] = v; // construct the graph
}
int hare = 0, tortoise = 0;
bool b = true;
// cout<<"here3\n";
while(true) {
if(tortoise != end) { tortoise = g[tortoise]; }
else{ break; }
if(hare != end) { hare = g[hare]; }
else{ break; }
if(hare != end) { hare = g[hare]; }
else{ break; }
if(hare == tortoise) { b = false; break; }
}
if(!g) delete[] g;
return b;
}
};
int main() {
Solution s;
// vector<vector<int> > v = {{0,1}};
vector<vector<int> > v = {{1,0}, {0,1}};
// vector<int> v1 = {0,1};
cout<<s.canFinish(2, v)<<"\n";
return 0;
} | 24.87037 | 81 | 0.443038 | [
"vector"
] |
86c274376ce63dd1206371259649dad22ec93967 | 1,261 | cpp | C++ | src/readQ.cpp | despargy/KukaImplementation-kinetic | 3a9ab106b117acfc6478fbf3e60e49b7e94b2722 | [
"MIT"
] | 1 | 2021-08-21T12:49:27.000Z | 2021-08-21T12:49:27.000Z | src/readQ.cpp | despargy/KukaImplementation-kinetic | 3a9ab106b117acfc6478fbf3e60e49b7e94b2722 | [
"MIT"
] | null | null | null | src/readQ.cpp | despargy/KukaImplementation-kinetic | 3a9ab106b117acfc6478fbf3e60e49b7e94b2722 | [
"MIT"
] | null | null | null | #include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <armadillo>
using namespace arma;
using namespace std;
mat readQ()
{
/* read */
// std::ifstream ifile("Collector/posmat.txt", std::ios::in);
std::ifstream ifile("Collector/posCollected_cut.txt", std::ios::in);
std::vector<double> scores;
//check to see that the file was opened correctly:
if (!ifile.is_open()) {
std::cerr << "There was a problem opening the input file!\n";
exit(1);//exit or do additional error checking
}
int DIM = 7;
double num = 0.0;
int i = 0;
//keep storing values from the text file so long as data exists:
while (ifile >> num) {
scores.push_back(num);
}
mat m(DIM,int(scores.size()/DIM));
int t=-1;
for (int i = 0; i < int(scores.size()/DIM); ++i)
{
for (int e = 0; e<DIM; e++)
{
t++;
m(e,i) = scores[t] ;
}
}
// //verify that the scores were stored correctly:
// for (int i = 0; i < int(scores.size()/DIM); ++i) {
// for (int e = 0; e<DIM; e++)
// {
// // std::cout << scores[i+e] << "\t";
// std::cout << m(e,i) << std::endl ;
// }
// }
return m;
}
| 22.122807 | 72 | 0.527359 | [
"vector"
] |
86c7682bfaa4caed1caa84220fac691e3c0a5177 | 7,394 | cpp | C++ | menus.cpp | DaemonToolz/locuste.system.connector | b7b28f2b225d97a8c2aa723964a4183fe1893f7d | [
"MIT"
] | null | null | null | menus.cpp | DaemonToolz/locuste.system.connector | b7b28f2b225d97a8c2aa723964a4183fe1893f7d | [
"MIT"
] | null | null | null | menus.cpp | DaemonToolz/locuste.system.connector | b7b28f2b225d97a8c2aa723964a4183fe1893f7d | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <map>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <regex>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#include "./globals.h"
#include "./pipes/PipeHandler.h"
using namespace std;
using namespace pipes;
void close_pipe();
void help();
void clearAndCall();
void callCommand();
void displayBrainMenu();
void displaySchedulerMenu();
void displayMainMenu();
void cursorUp();
void cursorDown();
void addScreenContent(const string& content);
void readScreenContent();
void clearScreenContent();
vector<std::string> split(const string&, const string&) ;
typedef void (*pfunc)(void);
map<int, pfunc>* authorizedKeys;
map<string, pfunc> *menuFunction;
string selectedMenuName = "main";
map<string,map<string, pfunc>> *availableCommands;
map<string,string> *helpMenu;
PipeHandler* DiagnosticPipe;
int getch(void){
struct termios oldt,newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
vector<string> splitInput(const string input){
istringstream iss(lastCommand);
vector<std::string> parsedMenu(istream_iterator<string>{iss}, istream_iterator<string>());
return parsedMenu;
}
void selectMenu(){
auto parsedMenu = splitInput(lastCommand);
if(parsedMenu.size() > 1 && menuFunction->find(parsedMenu[1]) != menuFunction->end()){
selectedMenuName = parsedMenu[1];
}
}
void displaySelectedMenu(){
(*menuFunction)[selectedMenuName]();
}
void deleteMenus(){
close_pipe();
delete DiagnosticPipe;
cout << "Pipe supprimée" << endl;
delete authorizedKeys;
cout << "Raccourcis supprimés" << endl;
}
void displayBrainMenu(){
if(running){
cout << "Menu de l'unité de contrôle" << endl;
cout << "Début du journal d'événement" << endl;
readScreenContent();
cout << "Fin du journal" << endl << endl;
}
}
void displaySchedulerMenu(){
cout << "Menu de l'ordonanceur" << endl;
}
void displayMainMenu(){
if(running){
cout << "Liste des applications LOCUSTE" << endl;
pid_lock.lock();
if(locusteApps != nullptr){
for (auto& elem : (*locusteApps)) {
cout << "[" << elem.first << "] - " << (elem.second > 0 ? " OK": " KO") << ". Pipe " << (locusteAppPipes->find(elem.first) == locusteAppPipes->end() ? "indisponible" : "disponible" ) << endl;
}
}
pid_lock.unlock();
cout << endl << "Début du journal d'événement" << endl;
readScreenContent();
cout << "Fin du journal" << endl << endl;
}
}
void quit(){
running = false;
}
void open_pipe(){
addScreenContent("Tentative de connexion");
if(DiagnosticPipe->CreatePipe(selectedMenuName)){
addScreenContent(("Succès de la connexion à " + selectedMenuName));
} else {
addScreenContent(("Echec de la connexion à " + selectedMenuName));
}
}
void close_pipe(){
if(DiagnosticPipe->DeletePipe()){
addScreenContent(("Succès de la déconnexion de " + selectedMenuName));
} else {
addScreenContent(("Echec de la déconnexion de " + selectedMenuName));
}
}
void sendAction(){
if(DiagnosticPipe->Initialized()){
DiagnosticPipe->SetCommand(lastCommand);
}
}
void startProcess(){
auto parsedCommand = splitInput(lastCommand);
if(parsedCommand.size() > 1){
auto proc = locusteApps->find(parsedCommand[1]);
if(proc != locusteApps->end() && proc->second < 0){
try {
addScreenContent(("Tentative de démarrage de l'application " + proc->first));
std::stringstream ss;
// Le nom correspond au nom de projet + nom de l'exé (qui sont les mêmes)
ss << "/home/pi/Documents/locuste/locuste/" << proc->first << "/" << proc->first << "&";
// Find a way to spawn a new independant process
ss.str(std::string());
} catch (exception& ex){
addScreenContent( ex.what());
}
}
}
}
void stopProcess(){
auto parsedCommand = splitInput(lastCommand);
if(parsedCommand.size() > 1){
auto proc = locusteApps->find(parsedCommand[1]);
if(proc != locusteApps->end() && proc->second > 0){
try{
addScreenContent(("Arrêt en cours " + proc->first));
kill(proc->second, SIGINT);
addScreenContent(("Arrêt réussi " + proc->first));
} catch (exception& ex){
addScreenContent(ex.what());
}
}
}
}
void initMenus(){
DiagnosticPipe = new PipeHandler();
menuFunction = new map<string, pfunc>();
helpMenu = new map<string,string>();
authorizedKeys = new map<int, pfunc>();
(*menuFunction)["main"] = displayMainMenu;
(*menuFunction)["locuste.service.brain"] = displayBrainMenu;
(*menuFunction)["locuste.service.osm"] = displaySchedulerMenu;
(*menuFunction)["locuste.drone.automata"] = displayMainMenu;
availableCommands = new map<string, map<string, pfunc>>();
(*availableCommands)["main"] = {
{"goto", selectMenu},
{"help", help},
{"clear", clearScreenContent},
{"start", startProcess},
{"stop", stopProcess},
{"quit", quit}
};
(*availableCommands)["locuste.service.brain"] = {
{"goto", selectMenu},
{"help", help},
{"connect", open_pipe},
{"disconnect", close_pipe},
{"module", sendAction},
{"clear", clearScreenContent},
{"quit", quit}
};
(*availableCommands)["locuste.service.osm"] = {
{"goto", selectMenu},
{"help", help},
{"quit", quit}
};
(*availableCommands)["locuste.drone.automata"] = {
{"goto", selectMenu},
{"help", help},
{"quit", quit}
};
(*helpMenu)["quit"] = "Quitter l'application";
(*helpMenu)["clear"] = "Nettoyer les journaux d'événements";
(*helpMenu)["goto"] = "Sélectionner un menu, ex: goto main, goto locuste.service.brain";
(*helpMenu)["connect"] = "Se connecter à l'application sélectionnée";
(*helpMenu)["disconnect"] = "Se déconnecter à l'application sélectionnée";
(*helpMenu)["module"] = "Choisir une action sur un module (list, start, stop, restart)";
(*helpMenu)["start"] = "Permet de démarrer une des applications listée dans le menu principal";
(*helpMenu)["stop"] = "Permet de stopper une des applications listée dans le menu principal";
(*authorizedKeys)[static_cast<int>('\n')] = clearAndCall;
(*authorizedKeys)[static_cast<int>('+')] = cursorDown;
(*authorizedKeys)[static_cast<int>('-')] = cursorUp;
}
void clearAndCall(){
callCommand();
lastCommand = "";
}
void callCommand(){
for (auto& elem : (*availableCommands)[selectedMenuName]) {
if(lastCommand.rfind(elem.first, 0) == 0){
(elem.second)();
break;
}
}
}
void help(){
auto helpVector = split(lastCommand, " ");
if(helpVector.size() > 1){
selectedHelp = (*helpMenu)[helpVector[1]];
}
}
| 28.438462 | 209 | 0.603733 | [
"vector"
] |
f86fa4a7a99a5aa8c1d259f208aa0c17edfe523c | 3,100 | hpp | C++ | lib/include/common/Ini.hpp | bielskij/altair-emu | 49463fd0fcacd70540fd6aa880dfc7cef0ad958d | [
"MIT"
] | null | null | null | lib/include/common/Ini.hpp | bielskij/altair-emu | 49463fd0fcacd70540fd6aa880dfc7cef0ad958d | [
"MIT"
] | null | null | null | lib/include/common/Ini.hpp | bielskij/altair-emu | 49463fd0fcacd70540fd6aa880dfc7cef0ad958d | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2020 Jaroslaw Bielski (bielski.j@gmail.com)
*
* 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 COMMON_INI_HPP_
#define COMMON_INI_HPP_
#include <map>
#include <vector>
#include <algorithm>
namespace common {
class Ini {
public:
class Section {
public:
Section(const std::string §ionName) : _sectionName(sectionName) {
}
virtual ~Section() {
}
bool contains(const std::string &key) const {
return this->_entries.find(key) != this->_entries.end();
}
const std::string &getValue(const std::string &key) const {
if (this->contains(key)) {
return this->_entries.at(key);
}
throw std::invalid_argument("Key '" + key + "' was not found!");
}
const std::string &getName() const {
return this->_sectionName;
}
void add(const std::string &key, const std::string &val) {
this->_entries[key] = val;
}
std::vector<std::string> getKeys() const {
std::vector<std::string> ret;
for (auto &i : _entries) {
ret.push_back(i.first);
}
return ret;
}
private:
std::string _sectionName;
std::map<std::string, std::string> _entries;
};
public:
Ini() {
}
virtual ~Ini() {
}
bool parse(const std::string &path);
bool contains(const std::string §ionName) const {
return this->_sectionMap.find(sectionName) != this->_sectionMap.end();
}
const std::vector<Section *> &get(const std::string §ionName) const {
if (this->contains(sectionName)) {
return this->_sectionMap.at(sectionName);
}
throw std::invalid_argument("Section '" + sectionName + "' was not found!");
}
std::vector<Section *> getSections() const {
std::vector<Section *> ret;
for (auto &i : this->_sectionMap) {
std::copy(i.second.begin(), i.second.end(), std::back_inserter(ret));
}
return ret;
}
private:
std::map<std::string, std::vector<Section *>> _sectionMap;
};
}
#endif /* COMMON_INI_HPP_ */
| 26.495726 | 81 | 0.66 | [
"vector"
] |
f8717286c6a442984a0cf9105ec724810e1fb98d | 5,017 | cpp | C++ | Tools/Pipeline/DegenerateMesh.cpp | LukaszByczynski/tbl-4edges | 11f8c2a1e40271c542321d9d4d0e4ed24cce92c8 | [
"MIT"
] | 21 | 2015-07-19T13:47:17.000Z | 2022-03-13T11:13:28.000Z | Tools/Pipeline/DegenerateMesh.cpp | theblacklotus/4edges | 11f8c2a1e40271c542321d9d4d0e4ed24cce92c8 | [
"MIT"
] | 1 | 2018-03-24T17:54:49.000Z | 2018-03-24T17:57:01.000Z | Tools/Pipeline/DegenerateMesh.cpp | jsvennevid/tbl-4edges | 11f8c2a1e40271c542321d9d4d0e4ed24cce92c8 | [
"MIT"
] | 2 | 2019-02-07T20:42:13.000Z | 2021-02-10T07:09:47.000Z | /*
Copyright (c) 2004-2006 Jesper Svennevid, Daniel Collin
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 "DegenerateMesh.h"
#include <Shared/Base/Io/Log.h>
#include <Shared/Base/Debug/Assert.h>
#include <XSIShape.h>
#include <XSIMesh.h>
#include <XSITriangleList.h>
#include <map>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace zenic
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool DegenerateMesh::Vertex::operator == (const DegenerateMesh::Vertex& v) const
{
return position == v.position && normal == v.normal && uv == v.uv;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DegenerateMesh::DegenerateMesh()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DegenerateMesh::~DegenerateMesh()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void DegenerateMesh::process(CSLXSIMesh* mesh, bool useNormals)
{
CSLXSIShape* shape = mesh->XSIShape();
// We only handle one set of triangles for now.
if (mesh->GetXSITriangleListCount() == 0)
{
ZENIC_WARNING("No triangles in the object. Can not be tristipped");
return;
}
CSLXSITriangleList* triangleList = mesh->XSITriangleLists()[0];
uint triCount = (uint)mesh->XSITriangleLists()[0]->GetTriangleCount() * 3;
// Positions
int* posIndexList = triangleList->GetVertexIndices()->ArrayPtr();
Vector3* posVertexArray = (Vector3*)shape->GetVertexPositionList()->GetAttributeArray()->ArrayPtr();
// Texture Coords
int* uvIndexList = 0;
Vector2* uvVertexArray = 0;
int* normalIndexList = 0;
Vector3* normalVertexArray = 0;
CSLXSISubComponentAttributeList* componentList = shape->GetFirstTexCoordList();
if (componentList)
{
uvIndexList = triangleList->GetAttributeByName(componentList->GetName())->ArrayPtr();
uvVertexArray = (Vector2*)componentList->GetAttributeArray()->ArrayPtr();
}
componentList = shape->GetFirstNormalList();
if (componentList && useNormals)
{
normalIndexList = triangleList->GetAttributeByName(componentList->GetName())->ArrayPtr();
normalVertexArray = (Vector3*)componentList->GetAttributeArray()->ArrayPtr();
}
// setup the lists
m_uniqueVertexList.clear();
m_uniqueVertexList.resize(shape->GetVertexPositionList()->GetCount());
m_indices.clear();
m_indices.reserve(triCount); // intentionally reserved, not resized
// generate the stuff
for (uint i = 0; i < triCount; ++i)
{
Vertex vertex;
vertex.position = posVertexArray[posIndexList[i]];
if (uvVertexArray)
vertex.uv = uvVertexArray[uvIndexList[i]];
if (normalVertexArray)
vertex.normal = normalVertexArray[normalIndexList[i]];
u32 index = createOrRetrieveUniqueVertex(posIndexList[i], vertex);
m_indices.push_back(index);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
u32 DegenerateMesh::createOrRetrieveUniqueVertex(u32 originalPositionIndex, const Vertex& vertex)
{
Vertex& orig = m_uniqueVertexList[originalPositionIndex];
if (!orig.initialized)
{
orig = vertex;
orig.initialized = true;
return originalPositionIndex;
}
else if (orig == vertex)
{
return originalPositionIndex;
}
else
{
// no match, go to next or create new
if (orig.nextIndex)
{
// cascade
return createOrRetrieveUniqueVertex(orig.nextIndex, vertex);
}
else
{
// get new index
u32 newIndex = u32(m_uniqueVertexList.size());
orig.nextIndex = newIndex;
m_uniqueVertexList.push_back(vertex);
m_uniqueVertexList[newIndex].initialized = true;
return newIndex;
}
}
}
}
| 29.511765 | 119 | 0.615707 | [
"mesh",
"object",
"shape"
] |
f875245f4ae208628d61b53e612dae59bdd40e49 | 1,221 | cpp | C++ | SPOJ/SPOJ/robot.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | SPOJ/SPOJ/robot.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | SPOJ/SPOJ/robot.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
#include <cassert>
#include <iomanip>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <complex>
#include <numeric>
#include <functional>
#include <sstream>
#include <algorithm>
#define MAX 1000010
#define MOD 1000000007
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
int main()
{
LL t,a,b,x,y,l,pat_height,bb;
string str;
//scanf("%d",&t);
t = 1;
while(t--)
{
cin>>a>>b;
cin>>str;
l = str.length();
x = 0;
y = 0;
maxh = INT_MAX;
for(int i=0;i<l;i++)
{
if(str[i] == 'L')
x -= 1;
else if(str[i] == 'R')
x += 1;
else if(str[i] == 'U')
y += 1;
else if(str[i] == 'D')
y -= 1;
}
cout<<x<<" "<<y<<endl;
pat_height = y;
if(y>=0)
bb = b - pat_height - 1;
else
bb = b + pat_hegith
}
return 0;
}
| 18.784615 | 36 | 0.488124 | [
"vector"
] |
f877cb4809d006fe9cf0d2669644fdaf2cb3830a | 1,934 | cpp | C++ | socialNetwork/gen-cpp/UserTimelineService_server.skeleton.cpp | rodrigo-bruno/DeathStarBench | c9ce09aaf7c1298a7c88efacd1010a71db0fa59d | [
"Apache-2.0"
] | 364 | 2019-04-28T01:45:37.000Z | 2022-03-31T15:08:03.000Z | socialNetwork/gen-cpp/UserTimelineService_server.skeleton.cpp | rodrigo-bruno/DeathStarBench | c9ce09aaf7c1298a7c88efacd1010a71db0fa59d | [
"Apache-2.0"
] | 111 | 2019-04-15T11:08:49.000Z | 2022-03-31T17:39:16.000Z | socialNetwork/gen-cpp/UserTimelineService_server.skeleton.cpp | rodrigo-bruno/DeathStarBench | c9ce09aaf7c1298a7c88efacd1010a71db0fa59d | [
"Apache-2.0"
] | 229 | 2019-05-14T08:55:57.000Z | 2022-03-31T03:14:55.000Z | // This autogenerated skeleton file illustrates how to build a server.
// You should copy it to another filename to avoid overwriting it.
#include "UserTimelineService.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::social_network;
class UserTimelineServiceHandler : virtual public UserTimelineServiceIf {
public:
UserTimelineServiceHandler() {
// Your initialization goes here
}
void WriteUserTimeline(const int64_t req_id, const int64_t post_id, const int64_t user_id, const int64_t timestamp, const std::map<std::string, std::string> & carrier) {
// Your implementation goes here
printf("WriteUserTimeline\n");
}
void ReadUserTimeline(std::vector<Post> & _return, const int64_t req_id, const int64_t user_id, const int32_t start, const int32_t stop, const std::map<std::string, std::string> & carrier) {
// Your implementation goes here
printf("ReadUserTimeline\n");
}
};
int main(int argc, char **argv) {
int port = 9090;
::apache::thrift::stdcxx::shared_ptr<UserTimelineServiceHandler> handler(new UserTimelineServiceHandler());
::apache::thrift::stdcxx::shared_ptr<TProcessor> processor(new UserTimelineServiceProcessor(handler));
::apache::thrift::stdcxx::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
::apache::thrift::stdcxx::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
::apache::thrift::stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();
return 0;
}
| 40.291667 | 192 | 0.770941 | [
"vector"
] |
f87840d967620a9725080c20b4e4fbba8a16f8f6 | 2,555 | cpp | C++ | casbin/util/builtin_operators.cpp | romitkarmakar/casbin-cpp | eed706b1171685f321311c6d14b365f72777989c | [
"Apache-2.0"
] | null | null | null | casbin/util/builtin_operators.cpp | romitkarmakar/casbin-cpp | eed706b1171685f321311c6d14b365f72777989c | [
"Apache-2.0"
] | null | null | null | casbin/util/builtin_operators.cpp | romitkarmakar/casbin-cpp | eed706b1171685f321311c6d14b365f72777989c | [
"Apache-2.0"
] | null | null | null | #include "builtin_operators.h"
bool key_match(string arg1, string arg2)
{
arg2 = trim(arg2);
arg1 = trim(arg1);
auto arg2arr = split(arg2, '/');
auto arg1arr = split(arg1, '/');
auto itr = arg2arr.begin();
int i = 0;
while (itr != arg2arr.end())
{
if (*itr == "*")
{
i++;
++itr;
continue;
}
if (i >= arg1arr.size())
return false;
if (*itr != arg1arr.at(i))
return false;
i++;
++itr;
}
return true;
}
bool key_match2(string arg1, string arg2)
{
arg2 = trim(arg2);
arg1 = trim(arg1);
vector<string> arg2arr = split(arg2, '/');
vector<string> arg1arr = split(arg1, '/');
int i = 0;
for (string ele : arg2arr)
{
if (ele.at(0) == ':')
{
i++;
continue;
}
if (i >= arg1arr.size())
return false;
if (ele != arg1arr.at(i))
return false;
i++;
}
return true;
}
bool key_match4(string arg1, string arg2)
{
arg2 = trim(arg2);
arg1 = trim(arg1);
vector<string> arg2arr = split(arg2, '/');
vector<string> arg1arr = split(arg1, '/');
unordered_map<string, string> urlKey;
int i = 0;
for (string ele : arg2arr)
{
if (i >= arg1arr.size())
return false;
if (ele.at(0) == '{' && ele.at(ele.length() - 1) == '}')
{
ele = ele.erase(0, 1);
ele.erase(ele.length() - 1, 1);
if (urlKey.find(ele) == urlKey.end())
{
urlKey.insert(pair<string, string>(ele, arg1arr.at(i)));
}
else
{
if (urlKey.find(ele)->second != arg1arr.at(i))
return false;
}
i++;
continue;
}
if (ele != arg1arr.at(i))
return false;
i++;
}
return true;
}
inline bool regex_match(string arg1, string arg2)
{
regex e(arg2);
if (regex_search(arg1, e)) return true;
return false;
}
vector<int> ipToInt(string IP)
{
vector<string> arr = split(IP, '.');
vector<int> result;
for (string temp : arr)
{
result.push_back(stoi(temp));
}
return result;
}
string intArrToBin(vector<int> arr)
{
string binary = "";
for (int temp : arr)
binary += bitset<8>(temp).to_string();
return binary;
}
bool ip_match(string ip1, string ip2)
{
string cidr = split(ip2, '/')[1];
vector<int> arr1 = ipToInt(ip1);
vector<int> arr2 = ipToInt(split(ip2, '/')[0]);
return intArrToBin(arr1).substr(0, stoi(cidr)) == intArrToBin(arr2).substr(0, stoi(cidr));
}
function<bool(string, string)> generate_g_function(role_manager* rm) {
auto func = [](role_manager* rm, string name1, string name2) {
if (rm == NULL) return name1 == name2;
bool result = rm->has_link(name1, name2);
return result;
};
return bind(func, rm, placeholders::_1, placeholders::_2);
} | 17.992958 | 91 | 0.603523 | [
"vector"
] |
f87ce0d7aacff93d0213f47a87a6e9a7bf543cef | 7,423 | cpp | C++ | src/ethereum/ethereum.cpp | vpubchain/syscoin | 72af49f24d2f4dd3628fd3ca8f7e3415534f55c8 | [
"MIT"
] | 1 | 2020-02-09T21:15:36.000Z | 2020-02-09T21:15:36.000Z | src/ethereum/ethereum.cpp | vpubchain/syscoin | 72af49f24d2f4dd3628fd3ca8f7e3415534f55c8 | [
"MIT"
] | null | null | null | src/ethereum/ethereum.cpp | vpubchain/syscoin | 72af49f24d2f4dd3628fd3ca8f7e3415534f55c8 | [
"MIT"
] | 1 | 2021-12-01T07:18:04.000Z | 2021-12-01T07:18:04.000Z | // Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <services/witnessaddress.h>
#include <logging.h>
#include <util/strencodings.h>
int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
std::string partialPath;
char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
int partialPathInt = strtol(pathPtrInt, NULL, 10);
if(partialPathInt == 0 || partialPathInt == 2){
partialPath = encodedPartialPath.substr(2);
}else{
partialPath = encodedPartialPath.substr(1);
}
if(partialPath == path.substr(pathPtr, partialPath.size())){
return partialPath.size();
}else{
return -1;
}
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
try{
dev::RLP currentNode;
const int len = parentNodes.itemCount();
dev::RLP nodeKey = root;
int pathPtr = 0;
const std::string pathString = dev::toHex(path);
int nibbles;
char pathPtrInt[2];
for (int i = 0 ; i < len ; i++) {
currentNode = parentNodes[i];
if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
return false;
}
if(pathPtr > (int)pathString.size()){
return false;
}
switch(currentNode.itemCount()){
case 17://branch node
if(pathPtr == (int)pathString.size()){
if(currentNode[16].payload().contentsEqual(value.data().toVector())){
return true;
}else{
return false;
}
}
pathPtrInt[0] = pathString[pathPtr];
pathPtrInt[1] = '\0';
nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
pathPtr += 1;
break;
case 2:
nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);
if(nibbles <= -1)
return false;
pathPtr += nibbles;
if(pathPtr == (int)pathString.size()) { //leaf node
if(currentNode[1].payload().contentsEqual(value.data().toVector())){
return true;
} else {
return false;
}
} else {//extension node
nodeKey = currentNode[1];
}
break;
default:
return false;
}
}
}
catch(...){
return false;
}
return false;
}
/**
* Parse eth input string expected to contain smart contract method call data. If the method call is not what we
* expected, or the length of the expected string is not what we expect then return false.
*
* @param vchInputExpectedMethodHash The expected method hash
* @param vchInputData The input to parse
* @param vchAssetContract The ERC20 contract address of the token involved in moving over
* @param outputAmount The amount burned
* @param nAsset The asset burned
* @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a CAmount (int64) with truncation of insignifficant bits
* @param witnessAddress The destination witness address for the minting
* @return true if everything is valid
*/
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const std::vector<unsigned char>& vchInputData, const std::vector<unsigned char>& vchAssetContract, CAmount& outputAmount, uint32_t& nAsset, const uint8_t& nLocalPrecision, CWitnessAddress& witnessAddress) {
if(vchAssetContract.empty()){
return false;
}
// total 7 or 8 fields are expected @ 32 bytes each field, 8 fields if witness > 32 bytes
if(vchInputData.size() < 228 || vchInputData.size() > 260) {
return false;
}
// method hash is 4 bytes
std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
// if the method hash doesn't match the expected method hash then return false
if(vchMethodHash != vchInputExpectedMethodHash) {
return false;
}
std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
// reverse endian
std::reverse(vchAmount.begin(), vchAmount.end());
arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
// convert the vch into a uint32_t (nAsset)
// should be in position 68 walking backwards
nAsset = static_cast<uint32_t>(vchInputData[67]);
nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;
// start from 100 offset (96 for 3rd field + 4 bytes for function signature) and subtract 20
std::vector<unsigned char>::const_iterator firstContractAddress = vchInputData.begin() + 80;
std::vector<unsigned char>::const_iterator lastContractAddress = firstContractAddress + 20;
const std::vector<unsigned char> vchERC20ContractAddress(firstContractAddress,lastContractAddress);
if(vchERC20ContractAddress != vchAssetContract)
{
return false;
}
// get precision
int dataPos = 131;
const int8_t &nPrecision = static_cast<uint8_t>(vchInputData[dataPos++]);
// local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
// we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
if(nLocalPrecision > nPrecision){
outputAmountArith *= pow(10, nLocalPrecision-nPrecision);
// ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
} else if(nLocalPrecision < nPrecision){
outputAmountArith /= pow(10, nPrecision-nLocalPrecision);
}
// once we have truncated it is safe to get low 64 bits of the uint256 which should encapsulate the entire value
outputAmount = outputAmountArith.GetLow64();
// skip data field market (32 bytes) + 31 bytes offset to the varint _byte
dataPos += 63;
const unsigned char &dataLength = vchInputData[dataPos++] - 1; // // - 1 to account for the version byte
// witness programs can extend to 40 bytes, min length is 2 for min witness program
if(dataLength > 40 || dataLength < 2){
return false;
}
// witness address information starting at position dataPos till the end
// get version proceeded by witness program bytes
const unsigned char& nVersion = vchInputData[dataPos++];
std::vector<unsigned char>::const_iterator firstWitness = vchInputData.begin()+dataPos;
std::vector<unsigned char>::const_iterator lastWitness = firstWitness + dataLength;
witnessAddress = CWitnessAddress(nVersion, std::vector<unsigned char>(firstWitness,lastWitness));
return witnessAddress.IsValid();
} | 42.66092 | 298 | 0.659033 | [
"vector"
] |
f883d0bb27360f18bd6dbb2a3204cef40dacb5ee | 1,008 | cpp | C++ | 05-Code-Organization-Cpp-Templates/05. Demos/05. HeaderAndSourceFiles/Company.cpp | KostadinovK/Cpp-Advanced | ae2ef3185baecc887dcd231dec900cf8c7da44c9 | [
"Apache-2.0"
] | null | null | null | 05-Code-Organization-Cpp-Templates/05. Demos/05. HeaderAndSourceFiles/Company.cpp | KostadinovK/Cpp-Advanced | ae2ef3185baecc887dcd231dec900cf8c7da44c9 | [
"Apache-2.0"
] | null | null | null | 05-Code-Organization-Cpp-Templates/05. Demos/05. HeaderAndSourceFiles/Company.cpp | KostadinovK/Cpp-Advanced | ae2ef3185baecc887dcd231dec900cf8c7da44c9 | [
"Apache-2.0"
] | null | null | null | #include "Company.h"
#include <sstream>
Company::Company(int id, std::string name, std::vector<std::pair<char, char> > employees)
: id(id)
, name(name)
, employees(employees) {}
int Company::getId() const {
return this->id;
}
std::string Company::getName() const {
return this->name;
}
std::vector<std::pair<char, char> > Company::getEmployees() const {
return this->employees;
}
std::string Company::toString() const {
std::ostringstream stream;
stream << id << " " << name << " ";
for (int i = 0; i < employees.size(); i++) {
auto initials = employees[i];
stream << initials.first << initials.second;
if (i < employees.size() - 1) {
stream << " ";
}
}
return stream.str();
}
bool Company::operator==(const Company& other) const {
return this->id == other.id;
}
std::string Company::operator+(const std::string& s) {
return this->toString() + s;
}
Company& Company::operator+=(const std::pair<char, char>& employee) {
this->employees.push_back(employee);
return *this;
} | 21 | 89 | 0.646825 | [
"vector"
] |
f88628d0ea5a7da8b2a56abb369ec032c485b474 | 60,938 | hpp | C++ | include/universal/number/integer/integer_impl.hpp | FloEdelmann/universal | c5b83f251ad91229399b7f97e4eeefcf718819d4 | [
"MIT"
] | null | null | null | include/universal/number/integer/integer_impl.hpp | FloEdelmann/universal | c5b83f251ad91229399b7f97e4eeefcf718819d4 | [
"MIT"
] | null | null | null | include/universal/number/integer/integer_impl.hpp | FloEdelmann/universal | c5b83f251ad91229399b7f97e4eeefcf718819d4 | [
"MIT"
] | null | null | null | #pragma once
// integer_impl.hpp: implementation of a fixed-size arbitrary integer precision number
//
// Copyright (C) 2017-2022 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <regex>
#include <vector>
#include <map>
// supporting types and functions
#include <universal/number/shared/specific_value_encoding.hpp>
#include <universal/number/shared/blocktype.hpp>
/*
the integer arithmetic can be configured to:
- throw exceptions on overflow
- throw execptions on arithmetic
you need the exception types defined, but you have the option to throw them
*/
#include <universal/number/integer/exceptions.hpp>
// composition types used by integer
#include <universal/number/support/decimal.hpp>
namespace sw { namespace universal {
enum class IntegerNumberType {
IntegerNumber = 0, // { ...,-3,-2,-1,0,1,2,3,... }
WholeNumber = 1, // { 0,1,2,3,... }
NaturalNumber = 2 // { 1,2,3,... }
};
// forward references
template<size_t nbits, typename BlockType, IntegerNumberType NumberType> class integer;
template<size_t nbits, typename BlockType, IntegerNumberType NumberType> integer<nbits, BlockType, NumberType> max_int();
template<size_t nbits, typename BlockType, IntegerNumberType NumberType> integer<nbits, BlockType, NumberType> min_int();
template<size_t nbits, typename BlockType, IntegerNumberType NumberType> struct idiv_t;
template<size_t nbits, typename BlockType, IntegerNumberType NumberType> idiv_t<nbits, BlockType, NumberType> idiv(const integer<nbits, BlockType, NumberType>&, const integer<nbits, BlockType, NumberType>&b);
// scale calculate the power of 2 exponent that would capture an approximation of a normalized real value
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline long scale(const integer<nbits, BlockType, NumberType>& i) {
integer<nbits, BlockType, NumberType> v(i);
if (i.sign()) { // special case handling
v.twosComplement();
if (v == i) { // special case of 10000..... largest negative number in 2's complement encoding
return long(nbits - 1);
}
}
// calculate scale
long scale = 0;
while (v > 1) {
++scale;
v >>= 1;
}
return scale;
}
// signed integer conversion
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline constexpr integer<nbits, BlockType, NumberType>& convert(int64_t v, integer<nbits, BlockType, NumberType>& result) { return result.convert(v); }
// unsigned integer conversion
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline constexpr integer<nbits, BlockType, NumberType>& convert(uint64_t v, integer<nbits, BlockType, NumberType>& result) { return result.convert(v); }
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
bool parse(const std::string& number, integer<nbits, BlockType, NumberType>& v);
// idiv_t for integer<nbits, BlockType, NumberType> to capture quotient and remainder during long division
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
struct idiv_t {
integer<nbits, BlockType, NumberType> quot; // quotient
integer<nbits, BlockType, NumberType> rem; // remainder
};
/*
The rules for detecting overflow in a two's complement sum are simple:
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
- If the sum of two negative numbers yields a positive result, the sum has overflowed.
- Otherwise, the sum has not overflowed.
It is important to note the overflow and carry out can each occur without the other.
In unsigned numbers, carry out is equivalent to overflow. In two's complement, carry out tells
you nothing about overflow.
The reason for the rules is that overflow in two's complement occurs, not when a bit is carried out
out of the left column, but when one is carried into it. That is, when there is a carry into the sign.
The rules detect this error by examining the sign of the result. A negative and positive added together
cannot overflow, because the sum is between the addends. Since both of the addends fit within the
allowable range of numbers, and their sum is between them, it must fit as well.
When implementing addition/subtraction on chuncks the overflow condition must be deduced from the
chunk values. The chunks need to be interpreted as unsigned binary segments.
*/
// integer is an arbitrary fixed-sized 2's complement integer
template<size_t _nbits, typename BlockType = uint8_t, IntegerNumberType NumberType = IntegerNumberType::IntegerNumber>
class integer {
public:
using bt = BlockType;
static constexpr size_t nbits = _nbits;
static constexpr size_t bitsInByte = 8ull;
static constexpr size_t bitsInBlock = sizeof(bt) * bitsInByte;
static constexpr size_t nrBlocks = 1ull + ((nbits - 1ull) / bitsInBlock);
static constexpr size_t MSU = nrBlocks - 1ull;
static constexpr bt ALL_ONES = bt(~0); // block type specific all 1's value
static constexpr bt MSU_MASK = (ALL_ONES >> (nrBlocks * bitsInBlock - nbits));
static constexpr size_t bitsInMSU = bitsInBlock - (nrBlocks * bitsInBlock - nbits);
static constexpr size_t storageMask = (0xFFFFFFFFFFFFFFFFull >> (64ull - bitsInBlock));
constexpr integer() noexcept : _block{ 0 } {};
constexpr integer(const integer&) noexcept = default;
constexpr integer(integer&&) noexcept = default;
constexpr integer& operator=(const integer&) noexcept = default;
constexpr integer& operator=(integer&&) noexcept = default;
/// Construct a new integer from another, sign extend when necessary, BlockTypes must be the same
template<size_t srcbits>
integer(const integer<srcbits, BlockType, NumberType>& a) {
// static_assert(srcbits > nbits, "Source integer is bigger than target: potential loss of precision"); // TODO: do we want this?
bitcopy(a);
if constexpr (srcbits < nbits) {
if (a.sign()) { // sign extend
for (unsigned i = srcbits; i < nbits; ++i) {
setbit(i);
}
}
}
}
// initializers for native types
constexpr integer(signed char initial_value) { *this = initial_value; }
constexpr integer(short initial_value) { *this = initial_value; }
constexpr integer(int initial_value) { *this = initial_value; }
constexpr integer(long initial_value) { *this = initial_value; }
constexpr integer(long long initial_value) { *this = initial_value; }
constexpr integer(char initial_value) { *this = initial_value; }
constexpr integer(unsigned short initial_value) { *this = initial_value; }
constexpr integer(unsigned int initial_value) { *this = initial_value; }
constexpr integer(unsigned long initial_value) { *this = initial_value; }
constexpr integer(unsigned long long initial_value) { *this = initial_value; }
constexpr integer(float initial_value) { *this = initial_value; }
constexpr integer(double initial_value) { *this = initial_value; }
constexpr integer(long double initial_value) { *this = initial_value; }
// specific value constructor
constexpr integer(const SpecificValue code) noexcept
: _block{ 0 } {
switch (code) {
case SpecificValue::maxpos:
maxpos();
break;
case SpecificValue::minpos:
minpos();
break;
case SpecificValue::zero:
default:
zero();
break;
case SpecificValue::minneg:
minneg();
break;
case SpecificValue::maxneg:
maxneg();
break;
case SpecificValue::infneg:
case SpecificValue::infpos:
case SpecificValue::qnan:
case SpecificValue::snan:
case SpecificValue::nar:
zero();
break;
}
}
// access operator for bits
// this needs a proxy to be able to create l-values
// bool operator[](const unsigned int i) const //
// simpler interface for now, using at(i) and set(i)/reset(i)
// assignment operators for native types
constexpr integer& operator=(signed char rhs) noexcept { return convert_signed(rhs); }
constexpr integer& operator=(short rhs) noexcept { return convert_signed(rhs); }
constexpr integer& operator=(int rhs) noexcept { return convert_signed(rhs); }
constexpr integer& operator=(long rhs) noexcept { return convert_signed(rhs); }
constexpr integer& operator=(long long rhs) noexcept { return convert_signed(rhs); }
constexpr integer& operator=(char rhs) noexcept { return convert_unsigned(rhs); }
constexpr integer& operator=(unsigned short rhs) noexcept { return convert_unsigned(rhs); }
constexpr integer& operator=(unsigned int rhs) noexcept { return convert_unsigned(rhs); }
constexpr integer& operator=(unsigned long rhs) noexcept { return convert_unsigned(rhs); }
constexpr integer& operator=(unsigned long long rhs) noexcept { return convert_unsigned(rhs); }
constexpr integer& operator=(float rhs) noexcept { return convert_ieee(rhs); }
constexpr integer& operator=(double rhs) noexcept { return convert_ieee(rhs); }
#if LONG_DOUBLE_SUPPORT
constexpr integer& operator=(long double rhs) noexcept { return convert_ieee(rhs); }
#endif
#ifdef ADAPTER_POSIT_AND_INTEGER
// convenience assignment operator
template<size_t nbits, size_t es>
integer& operator=(const posit<nbits, es>& rhs) {
convert_p2i(rhs, *this);
return *this;
}
#endif // ADAPTER_POSIT_AND_INTEGER
// prefix operators
constexpr integer operator-() const {
integer negated(*this);
negated.flip();
negated += 1;
return negated;
}
// one's complement
constexpr integer operator~() const {
integer complement(*this);
complement.flip();
return complement;
}
// increment
constexpr integer operator++(int) {
integer tmp(*this);
operator++();
return tmp;
}
constexpr integer& operator++() {
*this += integer(1);
_block[MSU] = static_cast<bt>(_block[MSU] & MSU_MASK); // assert precondition of properly nulled leading non-bits
return *this;
}
// decrement
constexpr integer operator--(int) {
integer tmp(*this);
operator--();
return tmp;
}
constexpr integer& operator--() {
*this -= integer(1);
_block[MSU] = static_cast<bt>(_block[MSU] & MSU_MASK); // assert precondition of properly nulled leading non-bits
return *this;
}
// conversion operators
explicit operator unsigned short() const noexcept { return to_integer<unsigned short>(); }
explicit operator unsigned int() const noexcept { return to_integer<unsigned int>(); }
explicit operator unsigned long() const noexcept { return to_integer<unsigned long>(); }
explicit operator unsigned long long() const noexcept { return to_integer<unsigned long long>(); }
explicit operator short() const noexcept { return to_integer<short>(); }
explicit operator int() const noexcept { return to_integer<int>(); }
explicit operator long() const noexcept { return to_integer<long>(); }
explicit operator long long() const noexcept { return to_integer<long long>(); }
explicit operator float() const noexcept { return to_real<float>(); }
explicit operator double() const noexcept { return to_real<double>(); }
#if LONG_DOUBLE_SUPPORT
explicit operator long double() const { return to_real<long double>(); }
#endif
// arithmetic operators
integer& operator+=(const integer& rhs) {
if constexpr (nrBlocks == 1) {
_block[0] = static_cast<bt>(_block[0] + rhs.block(0));
// null any leading bits that fall outside of nbits
_block[MSU] = static_cast<bt>(MSU_MASK & _block[MSU]);
}
else {
integer<nbits, BlockType, NumberType> sum;
std::uint64_t carry = 0;
BlockType* pA = _block;
BlockType const* pB = rhs._block;
BlockType* pC = sum._block;
BlockType* pEnd = pC + nrBlocks;
while (pC != pEnd) {
carry += static_cast<std::uint64_t>(*pA) + static_cast<std::uint64_t>(*pB);
*pC = static_cast<bt>(carry);
if constexpr (bitsInBlock == 64) carry = 0; else carry >>= bitsInBlock;
++pA; ++pB; ++pC;
}
// enforce precondition for fast comparison by properly nulling bits that are outside of nbits
BlockType* pLast = pEnd - 1;
*pLast = static_cast<bt>(MSU_MASK & *pLast);
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
// TODO: what is the real overflow condition?
// it is not carry == 1 as say 1 + -1 sets the carry but is 0
// if (carry) throw integer_overflow();
#endif
* this = sum;
}
return *this;
}
integer& operator-=(const integer& rhs) {
integer twos(rhs);
operator+=(twos.twosComplement());
return *this;
}
integer& operator*=(const integer& rhs) {
if constexpr (NumberType == IntegerNumberType::IntegerNumber) {
if constexpr (nrBlocks == 1) {
_block[0] = static_cast<bt>(_block[0] * rhs.block(0));
}
else {
// is there a better way than upconverting to deal with maxneg in a 2's complement encoding?
integer<nbits + 1, BlockType, NumberType> base(*this);
integer<nbits + 1, BlockType, NumberType> multiplicant(rhs);
bool resultIsNeg = (base.isneg() ^ multiplicant.isneg());
if (base.isneg()) {
base.twosComplement();
}
if (multiplicant.isneg()) {
multiplicant.twosComplement();
}
clear();
for (unsigned i = 0; i < static_cast<unsigned>(nrBlocks); ++i) {
std::uint64_t segment(0);
for (unsigned j = 0; j < static_cast<unsigned>(nrBlocks); ++j) {
segment += static_cast<std::uint64_t>(base.block(i)) * static_cast<std::uint64_t>(multiplicant.block(j));
if (i + j < static_cast<unsigned>(nrBlocks)) {
segment += _block[i + j];
_block[i + j] = static_cast<bt>(segment);
segment >>= bitsInBlock;
}
}
}
if (resultIsNeg) twosComplement();
}
}
else { // whole and natural numbers are closed under multiplication (modulo)
if constexpr (nrBlocks == 1) {
_block[0] = static_cast<bt>(_block[0] * rhs.block(0));
}
else {
integer<nbits, BlockType, NumberType> base(*this);
integer<nbits, BlockType, NumberType> multiplicant(rhs);
clear();
for (unsigned i = 0; i < static_cast<unsigned>(nrBlocks); ++i) {
std::uint64_t segment(0);
for (unsigned j = 0; j < static_cast<unsigned>(nrBlocks); ++j) {
segment += static_cast<std::uint64_t>(base.block(i)) * static_cast<std::uint64_t>(multiplicant.block(j));
if (i + j < static_cast<unsigned>(nrBlocks)) {
segment += _block[i + j];
_block[i + j] = static_cast<bt>(segment);
segment >>= bitsInBlock;
}
}
}
}
}
// null any leading bits that fall outside of nbits
_block[MSU] = static_cast<bt>(MSU_MASK & _block[MSU]);
return *this;
}
integer& operator/=(const integer& rhs) {
if constexpr (nbits == (sizeof(BlockType)*8) ) {
if (rhs._block[0] == 0) {
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
throw integer_divide_by_zero{};
#else
std::cerr << "integer_divide_by_zero\n";
#endif // INTEGER_THROW_ARITHMETIC_EXCEPTION
}
if constexpr (sizeof(BlockType) == 1) {
_block[0] = static_cast<bt>(std::int8_t(_block[0]) / std::int8_t(rhs._block[0]));
}
else if constexpr (sizeof(BlockType) == 2) {
_block[0] = static_cast<bt>(std::int16_t(_block[0]) / std::int16_t(rhs._block[0]));
}
else if constexpr (sizeof(BlockType) == 4) {
_block[0] = static_cast<bt>(std::int32_t(_block[0]) / std::int32_t(rhs._block[0]));
}
else if constexpr (sizeof(BlockType) == 8) {
_block[0] = static_cast<bt>(std::int64_t(_block[0]) / std::int64_t(rhs._block[0]));
}
_block[0] = static_cast<bt>(MSU_MASK & _block[0]);
}
else {
idiv_t<nbits, BlockType, NumberType> divresult = idiv<nbits, BlockType, NumberType>(*this, rhs);
*this = divresult.quot;
}
return *this;
}
integer& operator%=(const integer& rhs) {
if constexpr (nbits == (sizeof(BlockType) * 8)) {
if (rhs._block[0] == 0) {
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
throw integer_divide_by_zero{};
#else
std::cerr << "integer_divide_by_zero\n";
#endif // INTEGER_THROW_ARITHMETIC_EXCEPTION
}
if constexpr (sizeof(BlockType) == 1) {
_block[0] = static_cast<bt>(std::int8_t(_block[0]) % std::int8_t(rhs._block[0]));
}
else if constexpr (sizeof(BlockType) == 2) {
_block[0] = static_cast<bt>(std::int16_t(_block[0]) % std::int16_t(rhs._block[0]));
}
else if constexpr (sizeof(BlockType) == 4) {
_block[0] = static_cast<bt>(std::int32_t(_block[0]) % std::int32_t(rhs._block[0]));
}
else if constexpr (sizeof(BlockType) == 8) {
_block[0] = static_cast<bt>(std::int64_t(_block[0]) % std::int64_t(rhs._block[0]));
}
_block[0] = static_cast<bt>(MSU_MASK & _block[0]);
}
else {
idiv_t<nbits, BlockType, NumberType> divresult = idiv<nbits, BlockType, NumberType>(*this, rhs);
*this = divresult.rem;
}
return *this;
}
// arithmetic shift right operator
integer& operator<<=(int bitsToShift) {
if (bitsToShift == 0) return *this;
if (bitsToShift < 0) return operator>>=(-bitsToShift);
if (bitsToShift > static_cast<int>(nbits)) {
setzero();
return *this;
}
if (bitsToShift >= static_cast<int>(bitsInBlock)) {
int blockShift = bitsToShift / static_cast<int>(bitsInBlock);
for (int i = static_cast<int>(MSU); i >= blockShift; --i) {
_block[i] = _block[i - blockShift];
}
for (int i = blockShift - 1; i >= 0; --i) {
_block[i] = bt(0);
}
// adjust the shift
bitsToShift -= static_cast<int>(blockShift * bitsInBlock);
if (bitsToShift == 0) return *this;
}
if constexpr (MSU > 0) {
// construct the mask for the upper bits in the block that needs to move to the higher word
bt mask = 0xFFFFFFFFFFFFFFFF << (bitsInBlock - bitsToShift);
for (size_t i = MSU; i > 0; --i) {
_block[i] <<= bitsToShift;
// mix in the bits from the right
bt bits = bt(mask & _block[i - 1]);
_block[i] |= (bits >> (bitsInBlock - bitsToShift));
}
}
_block[0] <<= bitsToShift;
return *this;
}
integer& operator>>=(int bitsToShift) {
if (bitsToShift == 0) return *this;
if (bitsToShift < 0) return operator<<=(-bitsToShift);
if (bitsToShift >= static_cast<int>(nbits)) {
setzero();
return *this;
}
bool signext = sign();
size_t blockShift = 0;
if (bitsToShift >= static_cast<int>(bitsInBlock)) {
blockShift = bitsToShift / bitsInBlock;
if (MSU >= blockShift) {
// shift by blocks
for (size_t i = 0; i <= MSU - blockShift; ++i) {
_block[i] = _block[i + blockShift];
}
}
// adjust the shift
bitsToShift -= static_cast<int>(blockShift * bitsInBlock);
if (bitsToShift == 0) {
// fix up the leading zeros if we have a negative number
if (signext) {
// bitsToShift is guaranteed to be less than nbits
bitsToShift += static_cast<int>(blockShift * bitsInBlock);
for (unsigned i = nbits - bitsToShift; i < nbits; ++i) {
this->setbit(i);
}
}
else {
// clean up the blocks we have shifted clean
bitsToShift += static_cast<int>(blockShift * bitsInBlock);
for (unsigned i = nbits - bitsToShift; i < nbits; ++i) {
this->setbit(i, false);
}
}
return *this;
}
}
if constexpr (MSU > 0) {
bt mask = ALL_ONES;
mask >>= (bitsInBlock - bitsToShift); // this is a mask for the lower bits in the block that need to move to the lower word
for (size_t i = 0; i < MSU; ++i) { // TODO: can this be improved? we should not have to work on the upper blocks in case we block shifted
_block[i] >>= bitsToShift;
// mix in the bits from the left
bt bits = bt(mask & _block[i + 1]);
_block[i] |= (bits << (bitsInBlock - bitsToShift));
}
}
_block[MSU] >>= bitsToShift;
// fix up the leading zeros if we have a negative number
if (signext) {
// bitsToShift is guaranteed to be less than nbits
bitsToShift += static_cast<int>(blockShift * bitsInBlock);
for (unsigned i = nbits - bitsToShift; i < nbits; ++i) {
this->setbit(i);
}
}
else {
// clean up the blocks we have shifted clean
bitsToShift += static_cast<int>(blockShift * bitsInBlock);
for (unsigned i = nbits - bitsToShift; i < nbits; ++i) {
this->setbit(i, false);
}
}
// enforce precondition for fast comparison by properly nulling bits that are outside of nbits
_block[MSU] &= MSU_MASK;
return *this;
}
integer& logicShiftRight(int shift) {
if (shift == 0) return *this;
if (shift < 0) {
return operator<<=(-shift);
}
if (nbits <= unsigned(shift)) {
clear();
return *this;
}
integer<nbits, BlockType, NumberType> target;
for (int i = nbits - 1; i >= shift; --i) { // TODO: inefficient as it works at the bit level
target.setbit(static_cast<size_t>(i) - static_cast<size_t>(shift), at(static_cast<size_t>(i)));
}
*this = target;
return *this;
}
integer& operator&=(const integer& rhs) {
for (unsigned i = 0; i < nrBlocks; ++i) {
_block[i] &= rhs._block[i];
}
_block[MSU] &= MSU_MASK;
return *this;
}
integer& operator|=(const integer& rhs) {
for (unsigned i = 0; i < nrBlocks; ++i) {
_block[i] |= rhs._block[i];
}
_block[MSU] &= MSU_MASK;
return *this;
}
integer& operator^=(const integer& rhs) {
for (unsigned i = 0; i < nrBlocks; ++i) {
_block[i] ^= rhs._block[i];
}
_block[MSU] &= MSU_MASK;
return *this;
}
// modifiers
inline constexpr void clear() noexcept {
bt* p = _block;
if constexpr (0 == nrBlocks) {
return;
}
else if constexpr (1 == nrBlocks) {
*p = bt(0);
}
else if constexpr (2 == nrBlocks) {
*p++ = bt(0);
*p = bt(0);
}
else if constexpr (3 == nrBlocks) {
*p++ = bt(0);
*p++ = bt(0);
*p = bt(0);
}
else if constexpr (4 == nrBlocks) {
*p++ = bt(0);
*p++ = bt(0);
*p++ = bt(0);
*p = bt(0);
}
else {
for (size_t i = 0; i < nrBlocks; ++i) {
*p++ = bt(0);
}
}
}
inline constexpr void setzero() noexcept { clear(); }
inline constexpr integer& maxpos() noexcept {
clear();
setbit(nbits - 1ull, true);
flip();
return *this;
}
inline constexpr integer& minpos() noexcept {
clear();
setbit(0, true);
return *this;
}
inline constexpr integer& zero() noexcept {
clear();
return *this;
}
inline constexpr integer& minneg() noexcept {
clear();
flip();
return *this;
}
inline constexpr integer& maxneg() noexcept {
clear();
setbit(nbits - 1ull, true);
return *this;
}
inline constexpr void setbit(unsigned i, bool v = true) noexcept {
if (i < nbits) {
bt block = _block[i / bitsInBlock];
bt null = ~(1ull << (i % bitsInBlock));
bt bit = bt(v ? 1 : 0);
bt mask = bt(bit << (i % bitsInBlock));
_block[i / bitsInBlock] = bt((block & null) | mask);
return;
}
}
inline constexpr void setbyte(unsigned byteIndex, uint8_t data) {
uint8_t mask = 0x1u;
unsigned start = byteIndex * 8;
unsigned end = start + 8;
for (unsigned i = start; i < end; ++i) {
setbit(i, (mask & data));
mask <<= 1;
}
}
inline constexpr void setblock(unsigned i, bt value) noexcept {
if (i < nrBlocks) _block[i] = value;
}
// use un-interpreted raw bits to set the bits of the integer
inline constexpr integer& setbits(uint64_t raw_bits) noexcept {
if constexpr (0 == nrBlocks) {
return *this;
}
else if constexpr (1 == nrBlocks) {
_block[0] = raw_bits & storageMask;
}
else if constexpr (2 == nrBlocks) {
if constexpr (bitsInBlock < 64) {
_block[0] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
_block[1] = raw_bits & storageMask;
}
else {
_block[0] = raw_bits & storageMask;
_block[1] = 0;
}
}
else if constexpr (3 == nrBlocks) {
if constexpr (bitsInBlock < 64) {
_block[0] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
_block[1] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
_block[2] = raw_bits & storageMask;
}
else {
_block[0] = raw_bits & storageMask;
_block[1] = 0;
_block[2] = 0;
}
}
else if constexpr (4 == nrBlocks) {
if constexpr (bitsInBlock < 64) {
_block[0] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
_block[1] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
_block[2] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
_block[3] = raw_bits & storageMask;
}
else {
_block[0] = raw_bits & storageMask;
_block[1] = 0;
_block[2] = 0;
_block[3] = 0;
}
}
else {
if constexpr (bitsInBlock < 64) {
for (size_t i = 0; i < nrBlocks; ++i) {
_block[i] = raw_bits & storageMask;
raw_bits >>= bitsInBlock;
}
}
else {
_block[0] = raw_bits & storageMask;
for (size_t i = 1; i < nrBlocks; ++i) {
_block[i] = 0;
}
}
}
_block[MSU] &= MSU_MASK; // enforce precondition for fast comparison by properly nulling bits that are outside of nbits
return *this;
}
inline integer& assign(const std::string& txt) noexcept {
if (!parse(txt, *this)) {
std::cerr << "Unable to parse: " << txt << std::endl;
}
// enforce precondition for fast comparison by properly nulling bits that are outside of nbits
_block[MSU] = static_cast<BlockType>(MSU_MASK & _block[MSU]);
return *this;
}
// pure bit copy of source integer, no sign extension
template<size_t src_nbits>
inline constexpr void bitcopy(const integer<src_nbits, BlockType, NumberType>& src) noexcept {
clear();
for (unsigned i = 0; i < nrBlocks; ++i) {
_block[i] = src.block(i);
}
_block[MSU] = static_cast<bt>(_block[MSU] & MSU_MASK); // assert precondition of properly nulled leading non-bits
}
// in-place one's complement
inline constexpr integer& flip() {
for (unsigned i = 0; i < nrBlocks; ++i) {
_block[i] = static_cast<bt>(~_block[i]);
}
_block[MSU] = static_cast<bt>(_block[MSU] & MSU_MASK); // assert precondition of properly nulled leading non-bits
return *this;
}
// in-place 2's complement
inline constexpr integer& twosComplement() {
flip();
return ++(*this);
}
// selectors
inline constexpr bool iszero() const noexcept {
for (unsigned i = 0; i < nrBlocks; ++i) {
if (_block[i] != 0) return false;
}
return true;
}
inline constexpr bool ispos() const noexcept { return *this > 0; }
inline constexpr bool isneg() const noexcept { return *this < 0; }
inline constexpr bool isone() const noexcept {
for (unsigned i = 0; i < nrBlocks; ++i) {
if (i == 0) {
if (_block[0] != BlockType(1u)) return false;
}
else {
if (_block[i] != BlockType(0u)) return false;
}
}
return true;
}
inline constexpr bool isodd() const noexcept { return bool(_block[0] & 0x01); }
inline constexpr bool iseven() const noexcept { return !isodd(); }
inline constexpr bool sign() const noexcept { return at(nbits - 1); }
inline constexpr bool at(unsigned bitIndex) const noexcept {
if (bitIndex < nbits) {
bt word = _block[bitIndex / bitsInBlock];
bt mask = bt(1ull << (bitIndex % bitsInBlock));
return (word & mask);
}
return false;
}
inline constexpr bool test(unsigned i) const noexcept { return at(i); }
inline constexpr bt block(unsigned i) const noexcept { if (i < nrBlocks) return _block[i]; else return bt(0u); }
// signed integer conversion
template<typename SignedInt>
inline constexpr integer& convert_signed(SignedInt rhs) noexcept {
clear();
if (0 == rhs) return *this;
constexpr size_t argbits = sizeof(rhs);
int64_t v = rhs;
unsigned upper = (nbits <= _nbits ? nbits : argbits);
for (unsigned i = 0; i < upper && v != 0; ++i) {
if (v & 0x1ull) setbit(i);
v >>= 1;
}
if constexpr (nbits > 64) {
if (rhs < 0) { // sign extend if negative
for (unsigned i = upper; i < nbits; ++i) {
setbit(i);
}
}
}
return *this;
}
// unsigned integer conversion
template<typename UnsignedInt>
inline constexpr integer& convert_unsigned(UnsignedInt rhs) noexcept {
clear();
if (0 == rhs) return *this;
uint64_t v = rhs;
constexpr size_t argbits = sizeof(rhs);
unsigned upper = (nbits <= _nbits ? nbits : argbits);
for (unsigned i = 0; i < upper; ++i) {
if (v & 0x1ull) setbit(i);
v >>= 1;
}
return *this;
}
// native IEEE-754 conversion
// TODO: currently only supports integer values of 64bits or less
template<typename Real>
constexpr integer& convert_ieee(Real rhs) noexcept {
clear();
return *this = static_cast<long long>(rhs); // TODO: this clamps the IEEE range to +-2^63
}
protected:
// HELPER methods
// TODO: need to properly implement signed <-> unsigned conversions
template<typename IntType>
IntType to_integer() const noexcept {
IntType v{ 0 };
if (*this == 0) return v;
constexpr unsigned sizeofint = 8 * sizeof(IntType);
uint64_t mask = 1ull;
unsigned upper = (nbits < sizeofint ? nbits : sizeofint);
for (unsigned i = 0; i < upper; ++i) {
v |= at(i) ? mask : 0;
mask <<= 1;
}
if (sign() && upper < sizeofint) { // sign extend
for (unsigned i = upper; i < sizeofint; ++i) {
v |= mask;
mask <<= 1;
}
}
return v;
}
// TODO: enable_if this for native floating-point types only
template<typename Real>
constexpr Real to_real() const noexcept {
Real r = 0.0;
Real bitValue = static_cast<Real>(1.0);
for (size_t i = 0; i < nbits; ++i) {
if (at(i)) r += bitValue;
bitValue *= static_cast<Real>(2.0);
}
return r;
}
private:
bt _block[nrBlocks];
// convert
template<size_t nnbits, typename BBlockType, IntegerNumberType NNumberType>
friend std::string convert_to_decimal_string(const integer<nnbits, BBlockType, NNumberType>& value);
// integer - integer logic comparisons
template<size_t nnbits, typename BBlockType, IntegerNumberType NNumberType>
friend bool operator==(const integer<nnbits, BBlockType, NNumberType>& lhs, const integer<nnbits, BBlockType, NNumberType>& rhs);
// find the most significant bit set
template<size_t nnbits, typename BBlockType, IntegerNumberType NNumberType>
friend signed findMsb(const integer<nnbits, BBlockType, NNumberType>& v);
};
//////////////////////// INTEGER functions /////////////////////////////////
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> abs(const integer<nbits, BlockType, NumberType>& a) {
integer<nbits, BlockType, NumberType> b(a);
return (a >= 0 ? b : b.twosComplement());
}
// free function to create a 1's complement copy of an integer
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> onesComplement(const integer<nbits, BlockType, NumberType>& value) {
integer<nbits, BlockType, NumberType> ones(value);
return ones.flip();
}
// free function to create the 2's complement of an integer
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> twosComplement(const integer<nbits, BlockType, NumberType>& value) {
integer<nbits, BlockType, NumberType> twos(value);
return twos.twosComplement();;
}
// convert integer to decimal string
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
std::string convert_to_decimal_string(const integer<nbits, BlockType, NumberType>& value) {
if (value.iszero()) {
return std::string("0");
}
integer<nbits, BlockType, NumberType> number = value.sign() ? twosComplement(value) : value;
support::decimal partial, multiplier;
partial.setzero();
multiplier.setdigit(1);
// convert integer to decimal by adding and doubling multipliers
for (unsigned i = 0; i < nbits; ++i) {
if (number.at(i)) {
support::add(partial, multiplier);
// std::cout << partial << std::endl;
}
support::add(multiplier, multiplier);
}
std::stringstream str;
if (value.sign()) str << '-';
for (support::decimal::const_reverse_iterator rit = partial.rbegin(); rit != partial.rend(); ++rit) {
str << (int)*rit;
}
return str.str();
}
// findMsb takes an integer<nbits, BlockType, NumberType> reference and returns the 0-based position of the most significant bit, -1 if v == 0
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline signed findMsb(const integer<nbits, BlockType, NumberType>& v) {
BlockType const* pV = v._block + v.nrBlocks - 1;
BlockType const* pLast = v._block;
BlockType BlockMsb = BlockType(BlockType(1u) << (v.bitsInBlock - 1));
signed msb = static_cast<signed>(v.nbits - 1ull); // the case for an aligned MSB
unsigned rem = nbits % v.bitsInBlock;
// we are organized little-endian
// check if the blocks are aligned with the representation
if (rem > 0) {
// the top bits are unaligned: construct the right mask
BlockType mask = BlockType(BlockType(1u) << (rem - 1u));
while (mask != 0) {
if (*pV & mask) return msb;
--msb;
mask >>= 1;
}
if (msb < 0) return msb;
--pV;
}
// invariant: msb is now aligned with the blocks
// std::cout << "invariant msb : " << msb << '\n';
while (pV >= pLast) {
if (*pV != 0) {
BlockType mask = BlockMsb;
while (mask != 0) {
if (*pV & mask) return msb;
--msb;
mask >>= 1;
}
}
else {
msb -= v.bitsInBlock;
}
--pV;
}
return msb; // == -1 if no significant bit found
}
//////////////////////// INTEGER operators /////////////////////////////////
// divide returns the ratio of u and v in c
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
void divide(integer<nbits, BlockType, NumberType>& c, const integer<nbits, BlockType, NumberType>& u, const integer<nbits, BlockType, NumberType>& v) {
if (v.iszero()) {
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
throw integer_divide_by_zero{};
#else
std::cerr << "integer_divide_by_zero\n";
#endif // INTEGER_THROW_ARITHMETIC_EXCEPTION
}
using Integer = integer<nbits, BlockType, NumberType>;
// given two nonnegative numbers a = (a_1a_2..a_m+n)_b and v = (v_1v_2...v_n)_b, where v_1 != 0, and n > 1
// step 1: calculate a normalization factor d = floor(b / (v_1 + 1)
// to scale both u and v so that v_1 becomes >= floor(b/2)
idiv_t<nbits, BlockType, NumberType> divresult;
if (u > v) {
std::cout << "normalize\n";
std::uint64_t b = Integer::ALL_ONES + 1;
std::cout << b << '\n';
int i = static_cast<int>(Integer::MSU);
while (v.block(static_cast<size_t>(i)) == 0) {
--i;
}
std::uint64_t vStart = v.block(static_cast<size_t>(i)) + 1;
std::uint64_t d = b / vStart;
std::cout << "normalization d = " << d << " = " << b << " / " << vStart << '\n';
Integer _u = u * Integer(d);
Integer _v = v * Integer(d);
std::uint64_t v_1 = _v.block(static_cast<size_t>(i));
std::uint64_t v_2 = 0;
std::cout << "scaled u : " << to_binary(_u, true) << '\n';
std::cout << "scaled v : " << to_binary(_v, true) << '\n';
std::cout << "v_1 : " << to_binary(Integer(v_1), true) << '\n';
// start long division of limbs
for (size_t j = 0; j < Integer::nrBlocks-1; ++j) {
std::uint64_t u_j = _u.block(Integer::MSU - j);
if (u_j == 0) continue;
std::uint64_t u_jplus1 = _u.block(Integer::MSU - j - 1);
std::uint64_t u_jplus2 = _u.block(Integer::MSU - j - 2);
std::uint64_t qHat = (u_j == v_1 ? b - 1 : (u_j * b + u_jplus1) / v_1);
std::cout << "qHat : " << qHat << " = " << u_j << " * " << b << " + " << u_jplus1 << " / " << v_1 << '\n';
// test if v2*qHat > (u_j*b + u_jplus1 - qhat*v_1) * b + u_j+2
if (v_2 * qHat > ((u_j * b + u_jplus1 - qHat * v_1) * b + u_jplus2)) {
--qHat;
}
}
}
c = divresult.quot;
}
// remainder returns a mod b in c
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
void remainder(integer<nbits, BlockType, NumberType>& c, const integer<nbits, BlockType, NumberType>& a, const integer<nbits, BlockType, NumberType>& b) {
if (b == integer<nbits, BlockType, NumberType>(0)) {
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
throw integer_divide_by_zero{};
#else
std::cerr << "integer_divide_by_zero\n";
#endif // INTEGER_THROW_ARITHMETIC_EXCEPTION
}
idiv_t<nbits, BlockType, NumberType> divresult = idiv<nbits, BlockType, NumberType>(a, b);
c = divresult.rem;
}
// divide integer<nbits, BlockType, NumberType> a and b and return result argument
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
idiv_t<nbits, BlockType, NumberType> idiv(const integer<nbits, BlockType, NumberType>& _a, const integer<nbits, BlockType, NumberType>& _b) {
if (_b.iszero()) {
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
throw integer_divide_by_zero{};
#else
std::cerr << "integer_divide_by_zero\n";
#endif // INTEGER_THROW_ARITHMETIC_EXCEPTION
}
// generate the absolute values to do long division
// 2's complement special case -max requires an signed int that is 1 bit bigger to represent abs()
bool a_negative = _a.sign();
bool b_negative = _b.sign();
bool result_negative = (a_negative ^ b_negative);
integer<nbits + 1, BlockType, NumberType> a; a.bitcopy(a_negative ? -_a : _a);
integer<nbits + 1, BlockType, NumberType> b; b.bitcopy(b_negative ? -_b : _b);
idiv_t<nbits, BlockType, NumberType> divresult;
if (a < b) {
divresult.rem = _a; // a % b = a when a / b = 0
return divresult; // a / b = 0 when b > a
}
// initialize the long division
integer<nbits + 1, BlockType, NumberType> accumulator = a;
// prepare the subtractand
integer<nbits + 1, BlockType, NumberType> subtractand = b;
int msb_b = findMsb(b);
int msb_a = findMsb(a);
int shift = msb_a - msb_b;
subtractand <<= shift;
// long division
for (int i = shift; i >= 0; --i) {
if (subtractand <= accumulator) {
accumulator -= subtractand;
divresult.quot.setbit(static_cast<size_t>(i));
}
else {
divresult.quot.setbit(static_cast<size_t>(i), false);
}
subtractand >>= 1;
// std::cout << "i = " << i << " subtractand : " << subtractand << '\n';
}
if (result_negative) { // take 2's complement
divresult.quot.flip();
divresult.quot += 1;
}
if (_a.isneg()) {
divresult.rem = -accumulator;
}
else {
divresult.rem = accumulator;
}
return divresult;
}
/// stream operators
// read a integer ASCII format and make a binary integer out of it
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
bool parse(const std::string& number, integer<nbits, BlockType, NumberType>& value) {
bool bSuccess = false;
value.clear();
// check if the txt is an integer form: [0123456789]+
std::regex decimal_regex("^[-+]*[0-9]+");
std::regex octal_regex("^[-+]*0[1-7][0-7]*$");
std::regex hex_regex("^[-+]*0[xX][0-9a-fA-F']+");
// setup associative array to map chars to nibbles
std::map<char, int> charLookup{
{ '0', 0 },
{ '1', 1 },
{ '2', 2 },
{ '3', 3 },
{ '4', 4 },
{ '5', 5 },
{ '6', 6 },
{ '7', 7 },
{ '8', 8 },
{ '9', 9 },
{ 'a', 10 },
{ 'b', 11 },
{ 'c', 12 },
{ 'd', 13 },
{ 'e', 14 },
{ 'f', 15 },
{ 'A', 10 },
{ 'B', 11 },
{ 'C', 12 },
{ 'D', 13 },
{ 'E', 14 },
{ 'F', 15 },
};
if (std::regex_match(number, octal_regex)) {
std::cout << "found an octal representation\n";
for (std::string::const_reverse_iterator r = number.rbegin();
r != number.rend();
++r) {
std::cout << "char = " << *r << std::endl;
}
bSuccess = false; // TODO
}
else if (std::regex_match(number, hex_regex)) {
//std::cout << "found a hexadecimal representation\n";
// each char is a nibble
int maxByteIndex = nbits / 8;
int byte = 0;
int byteIndex = 0;
bool odd = false;
for (std::string::const_reverse_iterator r = number.rbegin();
r != number.rend() && byteIndex < maxByteIndex;
++r) {
if (*r == '\'') {
// ignore
}
else if (*r == 'x' || *r == 'X') {
if (odd) {
// complete the most significant byte
value.setbyte(static_cast<size_t>(byteIndex), static_cast<uint8_t>(byte));
}
// check that we have [-+]0[xX] format
++r;
if (r != number.rend()) {
if (*r == '0') {
// check if we have a sign
++r;
if (r == number.rend()) {
// no sign, thus by definition positive
bSuccess = true;
}
else if (*r == '+') {
// optional positive sign, no further action necessary
bSuccess = true;
}
else if (*r == '-') {
// negative sign, invert
value = -value;
bSuccess = true;
}
else {
// the regex will have filtered this out
bSuccess = false;
}
}
else {
// we didn't find the obligatory '0', the regex should have filtered this out
bSuccess = false;
}
}
else {
// we are missing the obligatory '0', the regex should have filtered this out
bSuccess = false;
}
// we have reached the end of our parse
break;
}
else {
if (odd) {
byte += charLookup.at(*r) << 4;
value.setbyte(static_cast<size_t>(byteIndex), static_cast<uint8_t>(byte));
++byteIndex;
}
else {
byte = charLookup.at(*r);
}
odd = !odd;
}
}
}
else if (std::regex_match(number, decimal_regex)) {
//std::cout << "found a decimal integer representation\n";
integer<nbits, BlockType, NumberType> scale = 1;
for (std::string::const_reverse_iterator r = number.rbegin();
r != number.rend();
++r) {
if (*r == '-') {
value = -value;
}
else if (*r == '+') {
break;
}
else {
integer<nbits, BlockType, NumberType> digit = charLookup.at(*r);
value += scale * digit;
scale *= 10;
}
}
bSuccess = true;
}
return bSuccess;
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
std::string to_string(const integer<nbits, BlockType, NumberType>& n) {
return convert_to_decimal_string(n);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
std::string convert_to_string(std::ios_base::fmtflags flags, const integer<nbits, BlockType, NumberType>& n) {
using IntegerBase = integer<nbits, BlockType, NumberType>;
using Integer = integer<nbits+1, BlockType, NumberType>; // got to be 1 bigger to be able to represent maxneg in 2's complement form
// set the base of the target number system to convert to
int base = 10;
if ((flags & std::ios_base::oct) == std::ios_base::oct) base = 8;
if ((flags & std::ios_base::hex) == std::ios_base::hex) base = 16;
std::string result;
if (base == 8 || base == 16) {
if (n.sign()) return std::string("negative value: ignored");
BlockType shift = base == 8 ? 3 : 4;
BlockType mask = static_cast<BlockType>((1u << shift) - 1);
Integer t(n);
result.assign(nbits / shift + ((nbits % shift) ? 1 : 0), '0');
std::string::difference_type pos = result.size() - 1;
for (size_t i = 0; i < nbits / static_cast<size_t>(shift); ++i) {
char c = '0' + static_cast<char>(t.block(0) & mask);
if (c > '9')
c += 'A' - '9' - 1;
result[pos--] = c;
t >>= shift;
}
if (nbits % shift) {
mask = static_cast<BlockType>((1u << (nbits % shift)) - 1);
char c = '0' + static_cast<char>(t.block(0) & mask);
if (c > '9')
c += 'A' - '9';
result[pos] = c;
}
//
// Get rid of leading zeros:
//
std::string::size_type n = result.find_first_not_of('0');
if (!result.empty() && (n == std::string::npos))
n = result.size() - 1;
result.erase(0, n);
if (flags & std::ios_base::showbase) {
const char* pp = base == 8 ? "0" : "0x";
result.insert(static_cast<std::string::size_type>(0), pp);
}
}
else {
result.assign(nbits / 3 + 1u, '0');
std::string::difference_type pos = result.size() - 1;
Integer t(n);
if (t.sign()) t.twosComplement(); // TODO: how to deal with maxneg which has no positive representation in 2's complement?
Integer block10;
unsigned digits_in_block10 = 2;
if constexpr (IntegerBase::bitsInBlock == 8) {
block10 = 100;
digits_in_block10 = 2;
}
else if constexpr (IntegerBase::bitsInBlock == 16) {
block10 = 10'000;
digits_in_block10 = 4;
}
else if constexpr (IntegerBase::bitsInBlock == 32) {
block10 = 1'000'000'000;
digits_in_block10 = 9;
}
else if constexpr (IntegerBase::bitsInBlock == 64) {
block10 = 1'000'000'000'000'000'000;
digits_in_block10 = 18;
}
while (!t.iszero()) {
Integer t2 = t / block10;
Integer r = t % block10;
// std::cout << "t " << long(t) << '\n';
// std::cout << "t2 " << long(t2) << '\n';
// std::cout << "r " << long(r) << '\n';
t = t2;
BlockType v = r.block(0);
// std::cout << "v " << uint32_t(v) << '\n';
for (unsigned i = 0; i < digits_in_block10; ++i) {
// std::cout << i << " " << (v / 10) << " " << (v % 10) << '\n';
char c = '0' + v % 10;
v /= 10;
result[pos] = c;
// std::cout << result << '\n';
if (pos-- == 0)
break;
}
}
std::string::size_type firstDigit = result.find_first_not_of('0');
result.erase(0, firstDigit);
if (result.empty())
result = "0";
if (n.isneg())
result.insert(static_cast<std::string::size_type>(0), 1, '-');
else if (flags & std::ios_base::showpos)
result.insert(static_cast<std::string::size_type>(0), 1, '+');
}
return result;
}
#ifdef OLD
// generate an integer format ASCII format
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline std::ostream& operator<<(std::ostream& ostr, const integer<nbits, BlockType, NumberType>& i) {
// to make certain that setw and left/right operators work properly
// we need to transform the integer into a string
std::stringstream ss;
std::streamsize prec = ostr.precision();
std::streamsize width = ostr.width();
std::ios_base::fmtflags ff;
ff = ostr.flags();
ss.flags(ff);
ss << std::setw(width) << std::setprecision(prec) << convert_to_decimal_string(i);
return ostr << ss.str();
}
#else
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline std::ostream& operator<<(std::ostream& ostr, const integer<nbits, BlockType, NumberType>& i) {
std::string s = convert_to_string(ostr.flags(), i);
std::streamsize width = ostr.width();
if (width > static_cast<std::streamsize>(s.size())) {
char fill = ostr.fill();
if ((ostr.flags() & std::ios_base::left) == std::ios_base::left)
s.append(static_cast<std::string::size_type>(width - s.size()), fill);
else
s.insert(static_cast<std::string::size_type>(0), static_cast<std::string::size_type>(width - s.size()), fill);
}
return ostr << s;
}
#endif
// read an ASCII integer format
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline std::istream& operator>>(std::istream& istr, integer<nbits, BlockType, NumberType>& p) {
std::string txt;
istr >> txt;
if (!parse(txt, p)) {
std::cerr << "unable to parse -" << txt << "- into a posit value\n";
}
return istr;
}
////////////////// string operators
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline std::string to_binary(const integer<nbits, BlockType, NumberType>& number, bool nibbleMarker = false) {
std::stringstream s;
s << "0b";
for (int i = nbits - 1; i >= 0; --i) {
s << (number.at(static_cast<size_t>(i)) ? "1" : "0");
if (i > 0 && (i % 4) == 0 && nibbleMarker) s << '\'';
}
return s.str();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// integer - integer binary logic operators
// equal: precondition is that the storage is properly nulled in all arithmetic paths
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator==(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
for (unsigned i = 0; i < lhs.nrBlocks; ++i) {
if (lhs._block[i] != rhs._block[i]) return false;
}
return true;
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator!=(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return !operator==(lhs, rhs);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator< (const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
bool lhs_is_negative = lhs.sign();
bool rhs_is_negative = rhs.sign();
if (lhs_is_negative && !rhs_is_negative) return true;
if (rhs_is_negative && !lhs_is_negative) return false;
// arguments have the same sign
integer<nbits, BlockType, NumberType> diff(0);
#if INTEGER_THROW_ARITHMETIC_EXCEPTION
// we need to catch and ignore the exception
try {
diff = (lhs - rhs);
}
catch (const integer_overflow& e) {
// all good as the arithmetic is modulo
const char* p = e.what();
if (p) --p;
}
#else
diff = (lhs - rhs);
#endif
return diff.sign();
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator> (const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator< (rhs, lhs);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator<=(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return !operator> (lhs, rhs);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator>=(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return !operator< (lhs, rhs);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// integer - literal binary logic operators
// equal: precondition is that the byte-storage is properly nulled in all arithmetic paths
template<size_t nbits, typename BlockType, IntegerNumberType NumberType, typename IntType>
inline bool operator==(const integer<nbits, BlockType, NumberType>& lhs, IntType rhs) {
return operator==(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType, typename IntType>
inline bool operator!=(const integer<nbits, BlockType, NumberType>& lhs, IntType rhs) {
return !operator==(lhs, rhs);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType, typename IntType>
inline bool operator< (const integer<nbits, BlockType, NumberType>& lhs, IntType rhs) {
return operator<(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType, typename IntType>
inline bool operator> (const integer<nbits, BlockType, NumberType>& lhs, IntType rhs) {
return operator< (integer<nbits, BlockType, NumberType>(rhs), lhs);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType, typename IntType>
inline bool operator<=(const integer<nbits, BlockType, NumberType>& lhs, IntType rhs) {
return operator< (lhs, rhs) || operator==(lhs, rhs);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType, typename IntType>
inline bool operator>=(const integer<nbits, BlockType, NumberType>& lhs, IntType rhs) {
return !operator< (lhs, rhs);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// literal - integer binary logic operators
// precondition is that the byte-storage is properly nulled in all arithmetic paths
template<typename IntType, size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator==(IntType lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator==(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
template<typename IntType, size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator!=(IntType lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return !operator==(lhs, rhs);
}
template<typename IntType, size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator< (IntType lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator<(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
template<typename IntType, size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator> (IntType lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator< (rhs, lhs);
}
template<typename IntType, size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator<=(IntType lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator< (lhs, rhs) || operator==(lhs, rhs);
}
template<typename IntType, size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline bool operator>=(IntType lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return !operator< (lhs, rhs);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator<<(const integer<nbits, BlockType, NumberType>& lhs, int shift) {
integer<nbits, BlockType, NumberType> shifted(lhs);
return (shifted <<= shift);
}
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator>>(const integer<nbits, BlockType, NumberType>& lhs, int shift) {
integer<nbits, BlockType, NumberType> shifted(lhs);
return (shifted >>= shift);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// integer - integer binary arithmetic operators
// BINARY ADDITION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator+(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> sum(lhs);
sum += rhs;
return sum;
}
// BINARY SUBTRACTION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator-(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> diff(lhs);
diff -= rhs;
return diff;
}
// BINARY MULTIPLICATION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator*(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> mul(lhs);
mul *= rhs;
return mul;
}
// BINARY DIVISION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator/(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> ratio(lhs);
ratio /= rhs;
return ratio;
}
// BINARY REMAINDER
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator%(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> ratio(lhs);
ratio %= rhs;
return ratio;
}
// BINARY BIT-WISE AND
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator&(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> bitwise(lhs);
bitwise &= rhs;
return bitwise;
}
// BINARY BIT-WISE OR
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator|(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> bitwise(lhs);
bitwise |= rhs;
return bitwise;
}
// BINARY BIT-WISE XOR
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator^(const integer<nbits, BlockType, NumberType>& lhs, const integer<nbits, BlockType, NumberType>& rhs) {
integer<nbits, BlockType, NumberType> bitwise(lhs);
bitwise ^= rhs;
return bitwise;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// integer - literal binary arithmetic operators
// BINARY ADDITION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator+(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator+(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY SUBTRACTION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator-(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator-(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY MULTIPLICATION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator*(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator*(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY DIVISION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator/(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator/(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY REMAINDER
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator%(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator%(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY BIT-WISE AND
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator&(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator&(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY BIT-WISE OR
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator|(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator|(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
// BINARY BIT-WISE XOR
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator^(const integer<nbits, BlockType, NumberType>& lhs, long long rhs) {
return operator^(lhs, integer<nbits, BlockType, NumberType>(rhs));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// literal - integer binary arithmetic operators
// BINARY ADDITION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator+(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator+(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY SUBTRACTION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator-(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator-(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY MULTIPLICATION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator*(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator*(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY DIVISION
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator/(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator/(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY REMAINDER
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator%(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator%(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY BIT-WISE AND
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator&(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator&(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY BIT-WISE OR
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator|(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator|(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
// BINARY BIT-WISE XOR
template<size_t nbits, typename BlockType, IntegerNumberType NumberType>
inline integer<nbits, BlockType, NumberType> operator^(long long lhs, const integer<nbits, BlockType, NumberType>& rhs) {
return operator^(integer<nbits, BlockType, NumberType>(lhs), rhs);
}
}} // namespace sw::universal
| 37.044377 | 208 | 0.670928 | [
"vector",
"transform"
] |
f8867abd2f4fcf409bf408a0e40d5d1f60128fea | 18,380 | cc | C++ | chrome/browser/chromeos/power/cpu_data_collector.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/chromeos/power/cpu_data_collector.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/chromeos/power/cpu_data_collector.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/power/cpu_data_collector.h"
#include <stddef.h>
#include <vector>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "chrome/browser/chromeos/power/power_data_collector.h"
#include "content/public/browser/browser_thread.h"
namespace chromeos {
namespace {
// The sampling of CPU idle or CPU freq data should not take more than this
// limit.
const int kSamplingDurationLimitMs = 500;
// The CPU data is sampled every |kCpuDataSamplePeriodSec| seconds.
const int kCpuDataSamplePeriodSec = 30;
// The value in the file /sys/devices/system/cpu/cpu<n>/online which indicates
// that CPU-n is online.
const int kCpuOnlineStatus = 1;
// The base of the path to the files and directories which contain CPU data in
// the sysfs.
const char kCpuDataPathBase[] = "/sys/devices/system/cpu";
// Suffix of the path to the file listing the range of possible CPUs on the
// system.
const char kPossibleCpuPathSuffix[] = "/possible";
// Format of the suffix of the path to the file which contains information
// about a particular CPU being online or offline.
const char kCpuOnlinePathSuffixFormat[] = "/cpu%d/online";
// Format of the suffix of the path to the file which contains freq state
// information of a CPU.
const char kCpuFreqTimeInStatePathSuffixOldFormat[] =
"/cpu%d/cpufreq/stats/time_in_state";
// The path to the file which contains cpu freq state informatino of a CPU
// in newer kernel.
const char kCpuFreqTimeInStateNewPath[] =
"/sys/devices/system/cpu/cpufreq/all_time_in_state";
// Format of the suffix of the path to the directory which contains information
// about an idle state of a CPU on the system.
const char kCpuIdleStateDirPathSuffixFormat[] = "/cpu%d/cpuidle/state%d";
// Format of the suffix of the path to the file which contains the name of an
// idle state of a CPU.
const char kCpuIdleStateNamePathSuffixFormat[] = "/cpu%d/cpuidle/state%d/name";
// Format of the suffix of the path which contains information about time spent
// in an idle state on a CPU.
const char kCpuIdleStateTimePathSuffixFormat[] = "/cpu%d/cpuidle/state%d/time";
// Returns the index at which |str| is in |vector|. If |str| is not present in
// |vector|, then it is added to it before its index is returned.
size_t IndexInVector(const std::string& str, std::vector<std::string>* vector) {
for (size_t i = 0; i < vector->size(); ++i) {
if (str == (*vector)[i])
return i;
}
// If this is reached, then it means |str| is not present in vector. Add it.
vector->push_back(str);
return vector->size() - 1;
}
// Returns true if the |i|-th CPU is online; false otherwise.
bool CpuIsOnline(const int i) {
const std::string online_file_format = base::StringPrintf(
"%s%s", kCpuDataPathBase, kCpuOnlinePathSuffixFormat);
const std::string cpu_online_file = base::StringPrintf(
online_file_format.c_str(), i);
if (!base::PathExists(base::FilePath(cpu_online_file))) {
// If the 'online' status file is missing, then it means that the CPU is
// not hot-pluggable and hence is always online.
return true;
}
int online;
std::string cpu_online_string;
if (base::ReadFileToString(base::FilePath(cpu_online_file),
&cpu_online_string)) {
base::TrimWhitespaceASCII(cpu_online_string, base::TRIM_ALL,
&cpu_online_string);
if (base::StringToInt(cpu_online_string, &online))
return online == kCpuOnlineStatus;
}
LOG(ERROR) << "Bad format or error reading " << cpu_online_file << ". "
<< "Assuming offline.";
return false;
}
// Samples the CPU idle state information from sysfs. |cpu_count| is the number
// of possible CPUs on the system. Sample at index i in |idle_samples|
// corresponds to the idle state information of the i-th CPU.
void SampleCpuIdleData(
int cpu_count,
std::vector<std::string>* cpu_idle_state_names,
std::vector<CpuDataCollector::StateOccupancySample>* idle_samples) {
base::Time start_time = base::Time::Now();
for (int cpu = 0; cpu < cpu_count; ++cpu) {
CpuDataCollector::StateOccupancySample idle_sample;
idle_sample.time = base::Time::Now();
idle_sample.time_in_state.reserve(cpu_idle_state_names->size());
if (!CpuIsOnline(cpu)) {
idle_sample.cpu_online = false;
} else {
idle_sample.cpu_online = true;
const std::string idle_state_dir_format = base::StringPrintf(
"%s%s", kCpuDataPathBase, kCpuIdleStateDirPathSuffixFormat);
for (int state_count = 0; ; ++state_count) {
std::string idle_state_dir = base::StringPrintf(
idle_state_dir_format.c_str(), cpu, state_count);
// This insures us from the unlikely case wherein the 'cpuidle_stats'
// kernel module is not loaded. This could happen on a VM.
if (!base::DirectoryExists(base::FilePath(idle_state_dir)))
break;
const std::string name_file_format = base::StringPrintf(
"%s%s", kCpuDataPathBase, kCpuIdleStateNamePathSuffixFormat);
const std::string name_file_path = base::StringPrintf(
name_file_format.c_str(), cpu, state_count);
DCHECK(base::PathExists(base::FilePath(name_file_path)));
const std::string time_file_format = base::StringPrintf(
"%s%s", kCpuDataPathBase, kCpuIdleStateTimePathSuffixFormat);
const std::string time_file_path = base::StringPrintf(
time_file_format.c_str(), cpu, state_count);
DCHECK(base::PathExists(base::FilePath(time_file_path)));
std::string state_name, occupancy_time_string;
int64_t occupancy_time_usec;
if (!base::ReadFileToString(base::FilePath(name_file_path),
&state_name) ||
!base::ReadFileToString(base::FilePath(time_file_path),
&occupancy_time_string)) {
// If an error occurs reading/parsing single state data, drop all the
// samples as an incomplete sample can mislead consumers of this
// sample.
LOG(ERROR) << "Error reading idle state from "
<< idle_state_dir << ". Dropping sample.";
idle_samples->clear();
return;
}
base::TrimWhitespaceASCII(state_name, base::TRIM_ALL, &state_name);
base::TrimWhitespaceASCII(occupancy_time_string, base::TRIM_ALL,
&occupancy_time_string);
if (base::StringToInt64(occupancy_time_string, &occupancy_time_usec)) {
// idle state occupancy time in sysfs is recorded in microseconds.
int64_t time_in_state_ms = occupancy_time_usec / 1000;
size_t index = IndexInVector(state_name, cpu_idle_state_names);
if (index >= idle_sample.time_in_state.size())
idle_sample.time_in_state.resize(index + 1);
idle_sample.time_in_state[index] = time_in_state_ms;
} else {
LOG(ERROR) << "Bad format in " << time_file_path << ". "
<< "Dropping sample.";
idle_samples->clear();
return;
}
}
}
idle_samples->push_back(idle_sample);
}
// If there was an interruption in sampling (like system suspended),
// discard the samples!
int64_t delay =
base::TimeDelta(base::Time::Now() - start_time).InMilliseconds();
if (delay > kSamplingDurationLimitMs) {
idle_samples->clear();
LOG(WARNING) << "Dropped an idle state sample due to excessive time delay: "
<< delay << "milliseconds.";
}
}
bool ReadCpuFreqFromOldFile(
const std::string& path,
std::vector<std::string>* cpu_freq_state_names,
CpuDataCollector::StateOccupancySample* freq_sample) {
std::string time_in_state_string;
// Note time as close to reading the file as possible. This is
// not possible for idle state samples as the information for
// each state there is recorded in different files.
if (!base::ReadFileToString(base::FilePath(path), &time_in_state_string)) {
LOG(ERROR) << "Error reading " << path << ". "
<< "Dropping sample.";
return false;
}
std::vector<base::StringPiece> lines = base::SplitStringPiece(
time_in_state_string, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
// The last line could end with '\n'. Ignore the last empty string in
// such cases.
size_t state_count = lines.size();
if (state_count > 0 && lines.back().empty())
state_count -= 1;
for (size_t state = 0; state < state_count; ++state) {
int freq_in_khz;
int64_t occupancy_time_centisecond;
// Occupancy of each state is in the format "<state> <time>"
std::vector<base::StringPiece> pair = base::SplitStringPiece(
lines[state], " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (pair.size() == 2 && base::StringToInt(pair[0], &freq_in_khz) &&
base::StringToInt64(pair[1], &occupancy_time_centisecond)) {
const std::string state_name = base::IntToString(freq_in_khz / 1000);
size_t index = IndexInVector(state_name, cpu_freq_state_names);
if (index >= freq_sample->time_in_state.size())
freq_sample->time_in_state.resize(index + 1);
// The occupancy time is in units of centiseconds.
freq_sample->time_in_state[index] = occupancy_time_centisecond * 10;
} else {
LOG(ERROR) << "Bad format in " << path << ". "
<< "Dropping sample.";
return false;
}
}
return true;
}
// Samples the CPU freq state information from sysfs. |cpu_count| is the number
// of possible CPUs on the system. Sample at index i in |freq_samples|
// corresponds to the freq state information of the i-th CPU.
void SampleCpuFreqData(
int cpu_count,
std::vector<std::string>* cpu_freq_state_names,
std::vector<CpuDataCollector::StateOccupancySample>* freq_samples) {
base::Time start_time = base::Time::Now();
for (int cpu = 0; cpu < cpu_count; ++cpu) {
CpuDataCollector::StateOccupancySample freq_sample;
freq_sample.time_in_state.reserve(cpu_freq_state_names->size());
freq_sample.time = base::Time::Now();
if (!CpuIsOnline(cpu)) {
freq_sample.cpu_online = false;
} else {
freq_sample.cpu_online = true;
const std::string time_in_state_path_old_format = base::StringPrintf(
"%s%s", kCpuDataPathBase, kCpuFreqTimeInStatePathSuffixOldFormat);
const std::string time_in_state_path =
base::StringPrintf(time_in_state_path_old_format.c_str(), cpu);
if (base::PathExists(base::FilePath(time_in_state_path))) {
if (!ReadCpuFreqFromOldFile(time_in_state_path, cpu_freq_state_names,
&freq_sample)) {
freq_samples->clear();
return;
}
} else if (base::PathExists(base::FilePath(kCpuFreqTimeInStateNewPath))) {
// TODO(oshima): Parse the new file. crbug.com/548510.
freq_samples->clear();
return;
} else {
// If the path to the 'time_in_state' for a single CPU is missing,
// then 'time_in_state' for all CPUs is missing. This could happen
// on a VM where the 'cpufreq_stats' kernel module is not loaded.
LOG_IF(ERROR, base::SysInfo::IsRunningOnChromeOS())
<< "CPU freq stats not available in sysfs.";
freq_samples->clear();
return;
}
}
freq_samples->push_back(freq_sample);
}
// If there was an interruption in sampling (like system suspended),
// discard the samples!
int64_t delay =
base::TimeDelta(base::Time::Now() - start_time).InMilliseconds();
if (delay > kSamplingDurationLimitMs) {
freq_samples->clear();
LOG(WARNING) << "Dropped a freq state sample due to excessive time delay: "
<< delay << "milliseconds.";
}
}
// Samples CPU idle and CPU freq data from sysfs. This function should run on
// the blocking pool as reading from sysfs is a blocking task. Elements at
// index i in |idle_samples| and |freq_samples| correspond to the idle and
// freq samples of CPU i. This also function reads the number of CPUs from
// sysfs if *|cpu_count| < 0.
void SampleCpuStateOnBlockingPool(
int* cpu_count,
std::vector<std::string>* cpu_idle_state_names,
std::vector<CpuDataCollector::StateOccupancySample>* idle_samples,
std::vector<std::string>* cpu_freq_state_names,
std::vector<CpuDataCollector::StateOccupancySample>* freq_samples) {
DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (*cpu_count < 0) {
// Set |cpu_count_| to 1. If it is something else, it will get corrected
// later. A system will at least have one CPU. Hence, a value of 1 here
// will serve as a default value in case of errors.
*cpu_count = 1;
const std::string possible_cpu_path = base::StringPrintf(
"%s%s", kCpuDataPathBase, kPossibleCpuPathSuffix);
if (!base::PathExists(base::FilePath(possible_cpu_path))) {
LOG(ERROR) << "File listing possible CPUs missing. "
<< "Defaulting CPU count to 1.";
} else {
std::string possible_string;
if (base::ReadFileToString(base::FilePath(possible_cpu_path),
&possible_string)) {
int max_cpu;
// The possible CPUs are listed in the format "0-N". Hence, N is present
// in the substring starting at offset 2.
base::TrimWhitespaceASCII(possible_string, base::TRIM_ALL,
&possible_string);
if (possible_string.find("-") != std::string::npos &&
possible_string.length() > 2 &&
base::StringToInt(possible_string.substr(2), &max_cpu)) {
*cpu_count = max_cpu + 1;
} else {
LOG(ERROR) << "Unknown format in the file listing possible CPUs. "
<< "Defaulting CPU count to 1.";
}
} else {
LOG(ERROR) << "Error reading the file listing possible CPUs. "
<< "Defaulting CPU count to 1.";
}
}
}
// Initialize the deques in the data vectors.
SampleCpuIdleData(*cpu_count, cpu_idle_state_names, idle_samples);
SampleCpuFreqData(*cpu_count, cpu_freq_state_names, freq_samples);
}
} // namespace
// Set |cpu_count_| to -1 and let SampleCpuStateOnBlockingPool discover the
// correct number of CPUs.
CpuDataCollector::CpuDataCollector() : cpu_count_(-1), weak_ptr_factory_(this) {
}
CpuDataCollector::~CpuDataCollector() {
}
void CpuDataCollector::Start() {
timer_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(kCpuDataSamplePeriodSec),
this,
&CpuDataCollector::PostSampleCpuState);
}
void CpuDataCollector::PostSampleCpuState() {
int* cpu_count = new int(cpu_count_);
std::vector<std::string>* cpu_idle_state_names =
new std::vector<std::string>(cpu_idle_state_names_);
std::vector<StateOccupancySample>* idle_samples =
new std::vector<StateOccupancySample>;
std::vector<std::string>* cpu_freq_state_names =
new std::vector<std::string>(cpu_freq_state_names_);
std::vector<StateOccupancySample>* freq_samples =
new std::vector<StateOccupancySample>;
content::BrowserThread::PostBlockingPoolTaskAndReply(
FROM_HERE,
base::Bind(&SampleCpuStateOnBlockingPool,
base::Unretained(cpu_count),
base::Unretained(cpu_idle_state_names),
base::Unretained(idle_samples),
base::Unretained(cpu_freq_state_names),
base::Unretained(freq_samples)),
base::Bind(&CpuDataCollector::SaveCpuStateSamplesOnUIThread,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(cpu_count),
base::Owned(cpu_idle_state_names),
base::Owned(idle_samples),
base::Owned(cpu_freq_state_names),
base::Owned(freq_samples)));
}
void CpuDataCollector::SaveCpuStateSamplesOnUIThread(
const int* cpu_count,
const std::vector<std::string>* cpu_idle_state_names,
const std::vector<CpuDataCollector::StateOccupancySample>* idle_samples,
const std::vector<std::string>* cpu_freq_state_names,
const std::vector<CpuDataCollector::StateOccupancySample>* freq_samples) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
cpu_count_ = *cpu_count;
// |idle_samples| or |freq_samples| could be empty sometimes (for example, if
// sampling was interrupted due to system suspension). Iff they are not empty,
// they will have one sample each for each of the CPUs.
if (!idle_samples->empty()) {
// When committing the first sample, resize the data vector to the number of
// CPUs on the system. This number should be the same as the number of
// samples in |idle_samples|.
if (cpu_idle_state_data_.empty()) {
cpu_idle_state_data_.resize(idle_samples->size());
} else {
DCHECK_EQ(idle_samples->size(), cpu_idle_state_data_.size());
}
for (size_t i = 0; i < cpu_idle_state_data_.size(); ++i)
AddSample(&cpu_idle_state_data_[i], (*idle_samples)[i]);
cpu_idle_state_names_ = *cpu_idle_state_names;
}
if (!freq_samples->empty()) {
// As with idle samples, resize the data vector before committing the first
// sample.
if (cpu_freq_state_data_.empty()) {
cpu_freq_state_data_.resize(freq_samples->size());
} else {
DCHECK_EQ(freq_samples->size(), cpu_freq_state_data_.size());
}
for (size_t i = 0; i < cpu_freq_state_data_.size(); ++i)
AddSample(&cpu_freq_state_data_[i], (*freq_samples)[i]);
cpu_freq_state_names_ = *cpu_freq_state_names;
}
}
CpuDataCollector::StateOccupancySample::StateOccupancySample()
: cpu_online(false) {
}
CpuDataCollector::StateOccupancySample::StateOccupancySample(
const StateOccupancySample& other) = default;
CpuDataCollector::StateOccupancySample::~StateOccupancySample() {
}
} // namespace chromeos
| 40.663717 | 80 | 0.675027 | [
"vector"
] |
f88ee03a72b6df071db5f126a8dfb8510c302241 | 852 | hpp | C++ | src/leader/ileader_connections.hpp | mrc-g/FogMon | dc040e5566d4fa6b0fca80fb46767f40f19b7c2e | [
"MIT"
] | 7 | 2019-05-08T08:25:40.000Z | 2021-06-19T10:42:56.000Z | src/leader/ileader_connections.hpp | mrc-g/FogMon | dc040e5566d4fa6b0fca80fb46767f40f19b7c2e | [
"MIT"
] | 5 | 2020-03-07T15:24:27.000Z | 2022-03-12T00:49:53.000Z | src/leader/ileader_connections.hpp | mrc-g/FogMon | dc040e5566d4fa6b0fca80fb46767f40f19b7c2e | [
"MIT"
] | 4 | 2020-03-05T17:05:42.000Z | 2021-11-21T16:00:56.000Z | #ifndef ILEADER_CONNECTIONS_HPP_
#define ILEADER_CONNECTIONS_HPP_
#include "connections.hpp"
class ILeader;
class ILeaderConnections : virtual public IConnections {
public:
virtual void initialize(ILeader* parent) = 0;
virtual bool sendMHello(Message::node ip) = 0;
virtual bool sendRemoveNodes(std::vector<Message::node> ips) = 0;
virtual bool sendRequestReport(Message::node ip) = 0;
virtual bool sendMReport(Message::node ip, vector<Report::report_result> report) = 0;
virtual bool sendInitiateSelection(int id) = 0;
virtual bool sendStartSelection(int id) = 0;
virtual bool sendSelection(Message::leader_update update,Message::node node) = 0;
virtual bool sendEndSelection(Message::leader_update update, bool result) = 0;
virtual bool sendChangeRoles(Message::leader_update update) = 0;
};
#endif | 32.769231 | 89 | 0.747653 | [
"vector"
] |
f8914e352f3ab52dc0011fc5deddb3b526358892 | 2,790 | hpp | C++ | include/arrowhead/detail/_service_json.hpp | gebart/arrowhead | 03c0edd81e76c0700ab7900e5d0bf7c1825b3065 | [
"Apache-2.0"
] | null | null | null | include/arrowhead/detail/_service_json.hpp | gebart/arrowhead | 03c0edd81e76c0700ab7900e5d0bf7c1825b3065 | [
"Apache-2.0"
] | null | null | null | include/arrowhead/detail/_service_json.hpp | gebart/arrowhead | 03c0edd81e76c0700ab7900e5d0bf7c1825b3065 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015-2016 Fotonic
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You can redistribute this code under either of these licenses.
* For more information; see http://www.arrowhead.eu/licensing
*/
/**
* @file
* @brief JSON processing template definitions
*
* @author Joakim Nohlgård <joakim@nohlgard.se>
*/
#ifndef ARROWHEAD_DETAIL_SERVICE_JSON_HPP_
#define ARROWHEAD_DETAIL_SERVICE_JSON_HPP_
#include <cstddef> // for size_t
#include <sstream>
#include "arrowhead/config.h"
#if ARROWHEAD_USE_JSON
#include "nlohmann/json.hpp"
#endif
#include "arrowhead/exception.hpp"
#include "arrowhead/service.hpp"
namespace Arrowhead {
namespace JSON {
/**
* @ingroup json_detail
* @{
*/
#if ARROWHEAD_USE_JSON
/**
* @internal
* @brief Translate a single JSON object into a ServiceDescription
*
* @param[in] srv A JSON object
*
* @return ServiceDescription object with fields filled from the JSON content
*/
ServiceDescription service_from_obj(const nlohmann::json& srv);
/**
* @internal
* @brief Translate ServiceDescription into a JSON object
*
* @param[in] srv Service to translate
*
* @return JSON object representation of the given service description
*/
nlohmann::json obj_from_service(const ServiceDescription& sd);
#endif /* ARROWHEAD_USE_JSON */
/** @} */
} /* namespace JSON */
/* Definitions of templates declared in include/arrowhead/json.hpp */
#if ARROWHEAD_USE_JSON
template<class OutputIt, class StringType>
OutputIt parse_servicelist_json(OutputIt oit, const StringType& js_str)
{
nlohmann::json js = nlohmann::json::parse(js_str);
nlohmann::json srvl = js["service"];
for (auto it = srvl.begin(); it != srvl.end(); ++it)
{
ServiceDescription srv = JSON::service_from_obj(*it);
*oit++ = srv;
}
return oit;
}
#endif /* ARROWHEAD_USE_JSON */
#if ARROWHEAD_USE_JSON
template<class StringType>
ServiceDescription ServiceDescription::from_json(const StringType& js_str)
{
nlohmann::json js = nlohmann::json::parse(js_str);
return JSON::service_from_obj(js);
}
#endif /* ARROWHEAD_USE_JSON */
template<class OutputIt>
OutputIt parse_servicelist_json(OutputIt oit,
const char *jsbuf, size_t buflen)
{
const std::string js_str(jsbuf, buflen);
return parse_servicelist_json(oit, js_str);
}
} /* namespace Arrowhead */
#endif /* ARROWHEAD_DETAIL_SERVICE_JSON_HPP_ */
| 24.690265 | 78 | 0.717204 | [
"object"
] |
f894bf135ae3c3f0d5ede4c7cc5cdc762e5fe7eb | 994 | cpp | C++ | kittens-imgui/core/midicontrol.cpp | christiancrowle/kittens | 180c77307629e8752b61df4ff3195f3c80131e11 | [
"MIT"
] | null | null | null | kittens-imgui/core/midicontrol.cpp | christiancrowle/kittens | 180c77307629e8752b61df4ff3195f3c80131e11 | [
"MIT"
] | null | null | null | kittens-imgui/core/midicontrol.cpp | christiancrowle/kittens | 180c77307629e8752b61df4ff3195f3c80131e11 | [
"MIT"
] | null | null | null | //
// Created by devbat on 6/26/20.
//
#include "midicontrol.h"
namespace Kittens::Core {
std::vector<std::string> MidiDevice::get_port_names() {
int count = this->get_num_out_ports();
std::vector<std::string> out;
if (count > 0) {
for (int i = 0; i < count; i++) {
out.push_back(this->device_output.get_port_name(i));
}
}
return out;
}
int MidiDevice::port_name_to_num(std::string port_name) {
int count = this->get_num_out_ports();
if (count > 0) {
for (int i = 0; i < count; i++) {
if (this->device_output.get_port_name(i) == port_name)
return i;
}
}
}
int MidiDevice::get_num_out_ports() {
return this->device_output.get_port_count();
}
void MidiDevice::select_out_port(std::string name) {
this->device_output.open_port(this->port_name_to_num(name));
}
void MidiDevice::select_out_port(int num) {
this->device_output.open_port(num);
}
} // namespace Kittens::Core | 22.590909 | 66 | 0.622736 | [
"vector"
] |
f898a8b072c5a8a5a5d431f864851cb96175f891 | 3,938 | cpp | C++ | src/VideoStreaming/gstqtvideosink/delegates/qtquick2videosinkdelegate.cpp | matthiasnattke/qgroundcontrol | 9f87623a1598529a7bf24ab1122d409d02a0aed5 | [
"Apache-2.0"
] | null | null | null | src/VideoStreaming/gstqtvideosink/delegates/qtquick2videosinkdelegate.cpp | matthiasnattke/qgroundcontrol | 9f87623a1598529a7bf24ab1122d409d02a0aed5 | [
"Apache-2.0"
] | null | null | null | src/VideoStreaming/gstqtvideosink/delegates/qtquick2videosinkdelegate.cpp | matthiasnattke/qgroundcontrol | 9f87623a1598529a7bf24ab1122d409d02a0aed5 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). <qt-info@nokia.com>
Copyright (C) 2011-2013 Collabora Ltd. <info@collabora.com>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
* @brief Extracted from QtGstreamer to avoid overly complex dependency
* @author Gus Grubba <gus@auterion.com>
*/
#include "qtquick2videosinkdelegate.h"
#include "../painters/videonode.h"
QtQuick2VideoSinkDelegate::QtQuick2VideoSinkDelegate(GstElement *sink, QObject *parent)
: BaseDelegate(sink, parent)
{
}
QSGNode* QtQuick2VideoSinkDelegate::updateNode(QSGNode *node, const QRectF & targetArea)
{
GST_TRACE_OBJECT(m_sink, "updateNode called");
bool sgnodeFormatChanged = false;
VideoNode *vnode = dynamic_cast<VideoNode*>(node);
if (!vnode) {
GST_INFO_OBJECT(m_sink, "creating new VideoNode");
vnode = new VideoNode;
}
if (!m_buffer) {
if (vnode->materialType() != VideoNode::MaterialTypeSolidBlack) {
vnode->setMaterialTypeSolidBlack();
sgnodeFormatChanged = true;
}
if (sgnodeFormatChanged || targetArea != m_areas.targetArea) {
m_areas.targetArea = targetArea;
vnode->updateGeometry(m_areas);
}
} else {
//change format before geometry, so that we change QSGGeometry as well
if (m_formatDirty) {
vnode->changeFormat(m_bufferFormat);
sgnodeFormatChanged = true;
}
//recalculate the video area if needed
QReadLocker forceAspectRatioLocker(&m_forceAspectRatioLock);
if (sgnodeFormatChanged || targetArea != m_areas.targetArea || m_forceAspectRatioDirty) {
m_forceAspectRatioDirty = false;
QReadLocker pixelAspectRatioLocker(&m_pixelAspectRatioLock);
Qt::AspectRatioMode aspectRatioMode = m_forceAspectRatio ?
Qt::KeepAspectRatio : Qt::IgnoreAspectRatio;
m_areas.calculate(targetArea, m_bufferFormat.frameSize(),
m_bufferFormat.pixelAspectRatio(), m_pixelAspectRatio,
aspectRatioMode);
pixelAspectRatioLocker.unlock();
GST_LOG_OBJECT(m_sink,
"Recalculated paint areas: "
"Frame size: " QSIZE_FORMAT ", "
"target area: " QRECTF_FORMAT ", "
"video area: " QRECTF_FORMAT ", "
"black1: " QRECTF_FORMAT ", "
"black2: " QRECTF_FORMAT,
QSIZE_FORMAT_ARGS(m_bufferFormat.frameSize()),
QRECTF_FORMAT_ARGS(m_areas.targetArea),
QRECTF_FORMAT_ARGS(m_areas.videoArea),
QRECTF_FORMAT_ARGS(m_areas.blackArea1),
QRECTF_FORMAT_ARGS(m_areas.blackArea2)
);
vnode->updateGeometry(m_areas);
}
forceAspectRatioLocker.unlock();
if (m_formatDirty) {
m_formatDirty = false;
//make sure to update the colors after changing material
m_colorsDirty = true;
}
QReadLocker colorsLocker(&m_colorsLock);
if (m_colorsDirty) {
vnode->updateColors(m_brightness, m_contrast, m_hue, m_saturation);
m_colorsDirty = false;
}
colorsLocker.unlock();
vnode->setCurrentFrame(m_buffer);
}
return vnode;
}
| 36.12844 | 97 | 0.64195 | [
"geometry"
] |
f8b694aae1e53c5078e90906ff800349e791e58d | 11,658 | cpp | C++ | test/unit/classification_test.cpp | marisn/libLAS | 8c7f3109e5c3bc71cdf400b31cc36640fa42eeea | [
"BSD-3-Clause"
] | 212 | 2015-02-25T13:55:07.000Z | 2022-03-28T17:12:09.000Z | test/unit/classification_test.cpp | marisn/libLAS | 8c7f3109e5c3bc71cdf400b31cc36640fa42eeea | [
"BSD-3-Clause"
] | 134 | 2015-01-09T13:41:52.000Z | 2022-03-24T11:30:03.000Z | test/unit/classification_test.cpp | marisn/libLAS | 8c7f3109e5c3bc71cdf400b31cc36640fa42eeea | [
"BSD-3-Clause"
] | 139 | 2015-01-15T04:09:17.000Z | 2022-03-23T14:21:49.000Z | // $Id$
//
// (C) Copyright Mateusz Loskot 2008, mateusz@loskot.net
// Distributed under the BSD License
// (See accompanying file LICENSE.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)
//
#include <liblas/classification.hpp>
#include <tut/tut.hpp>
#include <bitset>
#include <sstream>
#include <stdexcept>
#include <string>
#include "common.hpp"
namespace tut
{
struct lasclassification_data
{
typedef liblas::Classification::bitset_type bitset_type;
liblas::Classification m_default;
};
typedef test_group<lasclassification_data> tg;
typedef tg::object to;
tg test_group_lasclassification("liblas::Classification");
template<>
template<>
void to::test<1>()
{
ensure_equals(m_default, bitset_type(0));
ensure_equals(m_default.GetClass(), 0);
ensure_not(m_default.IsSynthetic());
ensure_not(m_default.IsKeyPoint());
ensure_not(m_default.IsWithheld());
}
template<>
template<>
void to::test<2>()
{
liblas::Classification c0(0);
ensure_equals(c0, m_default);
ensure_equals(c0, bitset_type(0));
ensure_equals(c0.GetClass(), 0);
ensure_not(c0.IsSynthetic());
ensure_not(c0.IsKeyPoint());
ensure_not(c0.IsWithheld());
}
template<>
template<>
void to::test<3>()
{
liblas::Classification c31(0x1F);
ensure_not(c31 == m_default);
ensure_equals(c31.GetClass(), 31);
ensure_not(c31.IsSynthetic());
ensure_not(c31.IsKeyPoint());
ensure_not(c31.IsWithheld());
}
template<>
template<>
void to::test<4>()
{
liblas::Classification c255(255);
ensure_equals(c255, bitset_type(255));
ensure_equals(c255.GetClass(), 31);
ensure(c255.IsSynthetic());
ensure(c255.IsKeyPoint());
ensure(c255.IsWithheld());
}
template<>
template<>
void to::test<5>()
{
liblas::Classification c(31, false, false, false);
ensure_equals(c.GetClass(), 31);
ensure_not(c.IsSynthetic());
ensure_not(c.IsKeyPoint());
ensure_not(c.IsWithheld());
ensure_equals(c, bitset_type(std::string("00011111")));
}
template<>
template<>
void to::test<6>()
{
liblas::Classification c(7, true, false, true);
ensure_equals(c.GetClass(), 7);
ensure_not(c.IsKeyPoint());
ensure(c.IsWithheld());
ensure(c.IsSynthetic());
ensure_equals(c, bitset_type(std::string("10100111")));
}
template<>
template<>
void to::test<7>()
{
try
{
liblas::Classification c(255, true, true, true);
fail("std::out_of_range not thrown but expected");
}
catch (std::out_of_range const& e)
{
ensure(e.what(), true);
}
catch (...)
{
fail("unhandled exception expected");
}
}
template<>
template<>
void to::test<8>()
{
liblas::Classification cpy(m_default);
ensure_equals(cpy, m_default);
}
template<>
template<>
void to::test<9>()
{
liblas::Classification c(7, true, false, true);
liblas::Classification cpy(c);
ensure_equals(cpy.GetClass(), 7);
ensure_not(cpy.IsKeyPoint());
ensure(cpy.IsWithheld());
ensure(cpy.IsSynthetic());
ensure_equals(cpy, bitset_type(std::string("10100111")));
ensure_equals(cpy, c);
}
template<>
template<>
void to::test<10>()
{
liblas::Classification cpy;
cpy = m_default;
ensure_equals(cpy, m_default);
}
template<>
template<>
void to::test<11>()
{
liblas::Classification c(7, true, false, true);
liblas::Classification cpy = c;
ensure_equals(cpy.GetClass(), 7);
ensure_not(cpy.IsKeyPoint());
ensure(cpy.IsWithheld());
ensure(cpy.IsSynthetic());
ensure_equals(cpy, bitset_type(std::string("10100111")));
ensure_equals(cpy, c);
}
template<>
template<>
void to::test<12>()
{
liblas::Classification c;
c.SetClass(0);
ensure_equals(c.GetClass(), 0);
c.SetClass(31);
ensure_equals(c.GetClass(), 31);
ensure(c != m_default);
}
template<>
template<>
void to::test<13>()
{
liblas::Classification c;
c.SetSynthetic(true);
ensure(c.IsSynthetic());
ensure(c != m_default);
c.SetSynthetic(false);
ensure_not(c.IsSynthetic());
ensure_equals(c, m_default);
c.SetSynthetic(true);
ensure(c.IsSynthetic());
ensure(c != m_default);
c.SetSynthetic(false);
ensure_not(c.IsSynthetic());
ensure_equals(c, m_default);
ensure_equals(c.GetClass(), 0);
}
template<>
template<>
void to::test<14>()
{
liblas::Classification c;
c.SetKeyPoint(true);
ensure(c.IsKeyPoint());
ensure(c != m_default);
c.SetKeyPoint(false);
ensure_not(c.IsKeyPoint());
ensure_equals(c, m_default);
c.SetKeyPoint(true);
ensure(c.IsKeyPoint());
ensure(c != m_default);
c.SetKeyPoint(false);
ensure_not(c.IsKeyPoint());
ensure_equals(c, m_default);
ensure_equals(c.GetClass(), 0);
}
template<>
template<>
void to::test<15>()
{
liblas::Classification c;
c.SetWithheld(true);
ensure(c.IsWithheld());
ensure(c != m_default);
c.SetWithheld(false);
ensure_not(c.IsWithheld());
ensure_equals(c, m_default);
c.SetWithheld(true);
ensure(c.IsWithheld());
ensure(c != m_default);
c.SetWithheld(false);
ensure_not(c.IsWithheld());
ensure_equals(c, m_default);
ensure_equals(c.GetClass(), 0);
}
template<>
template<>
void to::test<16>()
{
liblas::Classification c;
c.SetKeyPoint(true);
ensure(c.IsKeyPoint());
ensure(c != m_default);
c.SetWithheld(true);
ensure(c.IsWithheld());
ensure(c.IsKeyPoint());
ensure(c != m_default);
c.SetSynthetic(true);
ensure(c.IsWithheld());
ensure(c.IsKeyPoint());
ensure(c.IsSynthetic());
ensure(c != m_default);
ensure_equals(c.GetClass(), 0);
}
template<>
template<>
void to::test<17>()
{
liblas::Classification c;
c.SetKeyPoint(true);
c.SetSynthetic(true);
c.SetWithheld(true);
ensure(c.IsWithheld());
ensure(c.IsKeyPoint());
ensure(c.IsSynthetic());
ensure_not(c == m_default);
ensure_equals(c.GetClass(), 0);
c.SetKeyPoint(false);
c.SetSynthetic(false);
c.SetWithheld(false);
ensure_not(c.IsWithheld());
ensure_not(c.IsKeyPoint());
ensure_not(c.IsSynthetic());
ensure_equals(c.GetClass(), 0);
liblas::Classification::bitset_type bits1(c);
liblas::Classification::bitset_type bits2(m_default);
ensure_equals(c, m_default);
}
template<>
template<>
void to::test<18>()
{
liblas::Classification c;
c.SetKeyPoint(true);
c.SetClass(1);
c.SetSynthetic(true);
c.SetWithheld(true);
ensure(c.IsWithheld());
ensure(c.IsKeyPoint());
ensure(c.IsSynthetic());
ensure_equals(c.GetClass(), 1);
ensure_not(c == m_default);
c.SetKeyPoint(false);
c.SetSynthetic(false);
c.SetClass(0);
c.SetWithheld(false);
ensure_not(c.IsWithheld());
ensure_not(c.IsKeyPoint());
ensure_not(c.IsSynthetic());
ensure_equals(c.GetClass(), 0);
liblas::Classification::bitset_type bits1(c);
liblas::Classification::bitset_type bits2(m_default);
ensure_equals(c, m_default);
}
template<>
template<>
void to::test<19>()
{
std::string const sbits("00000000");
liblas::Classification c;
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<20>()
{
std::string const sbits("00000011");
liblas::Classification c;
c.SetClass(3);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<21>()
{
std::string const sbits("10000001");
liblas::Classification c;
c.SetWithheld(true);
c.SetClass(1);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<22>()
{
std::string const sbits("10110000");
liblas::Classification c;
c.SetClass(16);
c.SetSynthetic(true);
c.SetKeyPoint(false);
c.SetWithheld(true);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<23>()
{
std::string const sbits("00000000");
liblas::Classification::bitset_type bits(sbits);
liblas::Classification c(bits);
ensure_equals(c, bits);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<24>()
{
std::string const sbits("00000011");
liblas::Classification::bitset_type bits(sbits);
liblas::Classification c(bits);
ensure_equals(c, bits);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<25>()
{
std::string const sbits("10000001");
liblas::Classification::bitset_type bits(sbits);
liblas::Classification c(bits);
ensure_equals(c, bits);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<26>()
{
std::string const sbits("10110000");
liblas::Classification::bitset_type bits(sbits);
liblas::Classification c(bits);
ensure_equals(c, bits);
std::ostringstream oss;
oss << c;
ensure_equals(oss.str(), sbits);
}
template<>
template<>
void to::test<27>()
{
std::string const cn("Created, never classified");
ensure_equals(m_default.GetClassName(), cn);
}
template<>
template<>
void to::test<28>()
{
std::string const cn("Low Point (noise)");
m_default.SetClass(7);
ensure_equals(m_default.GetClassName(), cn);
}
template<>
template<>
void to::test<29>()
{
std::string const cn("Reserved for ASPRS Definition");
m_default.SetClass(31);
ensure_equals(m_default.GetClassName(), cn);
}
template<>
template<>
void to::test<30>()
{
try
{
m_default.SetClass(32);
fail("std::out_of_range not thrown but expected");
}
catch (std::out_of_range const& e)
{
ensure(e.what(), true);
}
catch (...)
{
fail("unhandled exception expected");
}
}
}
| 22.725146 | 65 | 0.551381 | [
"object"
] |
f8b6ca6dd07cd2ddb1d987bb517a653c787c971f | 3,370 | cpp | C++ | src/core/TChem_InitialCondSurface.cpp | kyungjoo-kim/TChem | 69915ca8de71df9a6a463aae45c5bd6db31646bc | [
"BSD-2-Clause"
] | null | null | null | src/core/TChem_InitialCondSurface.cpp | kyungjoo-kim/TChem | 69915ca8de71df9a6a463aae45c5bd6db31646bc | [
"BSD-2-Clause"
] | null | null | null | src/core/TChem_InitialCondSurface.cpp | kyungjoo-kim/TChem | 69915ca8de71df9a6a463aae45c5bd6db31646bc | [
"BSD-2-Clause"
] | 1 | 2022-02-26T18:04:44.000Z | 2022-02-26T18:04:44.000Z | /* =====================================================================================
TChem version 2.0
Copyright (2020) NTESS
https://github.com/sandialabs/TChem
Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains
certain rights in this software.
This file is part of TChem. TChem is open source software: you can redistribute it
and/or modify it under the terms of BSD 2-Clause License
(https://opensource.org/licenses/BSD-2-Clause). A copy of the licese is also
provided under the main directory
Questions? Contact Cosmin Safta at <csafta@sandia.gov>, or
Kyungjoo Kim at <kyukim@sandia.gov>, or
Oscar Diaz-Ibarra at <odiazib@sandia.gov>
Sandia National Laboratories, Livermore, CA, USA
===================================================================================== */
#include "TChem_InitialCondSurface.hpp"
namespace TChem {
void
InitialCondSurface::runDeviceBatch( /// input
const typename TChem::UseThisTeamPolicy<TChem::exec_space>::type& policy,
const real_type_2d_view& state,
const real_type_2d_view& zSurf,
/// output
const real_type_2d_view& Z_out,
const real_type_2d_view& fac,
/// const data from kinetic model
const KineticModelConstDataDevice& kmcd,
const KineticSurfModelConstDataDevice& kmcdSurf)
{
Kokkos::Profiling::pushRegion("TChem::InitialCondSurface::runDeviceBatch");
using policy_type =
typename TChem::UseThisTeamPolicy<TChem::exec_space>::type;
const ordinal_type level = 1;
const ordinal_type per_team_extent = getWorkSpaceSize(kmcd, kmcdSurf);
// const ordinal_type per_team_scratch =
// Scratch<real_type_1d_view>::shmem_size(per_team_extent);
// policy_type policy(nBatch, Kokkos::AUTO());
// policy.set_scratch_size(level, Kokkos::PerTeam(per_team_scratch));
Kokkos::parallel_for(
"TChem::InitialCondSurface::runDeviceBatch",
policy,
KOKKOS_LAMBDA(const typename policy_type::member_type& member) {
const ordinal_type i = member.league_rank();
const real_type_1d_view fac_at_i =
Kokkos::subview(fac, i, Kokkos::ALL());
const real_type_1d_view state_at_i =
Kokkos::subview(state, i, Kokkos::ALL());
// site fraction
const real_type_1d_view Zs_at_i =
Kokkos::subview(zSurf, i, Kokkos::ALL());
const real_type_1d_view Zs_out_at_i =
Kokkos::subview(Z_out, i, Kokkos::ALL());
Scratch<real_type_1d_view> work(member.team_scratch(level),
per_team_extent);
Impl::StateVector<real_type_1d_view> sv_at_i(kmcd.nSpec, state_at_i);
TCHEM_CHECK_ERROR(!sv_at_i.isValid(),
"Error: input state vector is not valid");
{
const real_type temperature = sv_at_i.Temperature();
const real_type pressure = sv_at_i.Pressure();
const real_type_1d_view Ys = sv_at_i.MassFractions();
Impl::InitialCondSurface ::team_invoke(
member,
temperature, /// temperature
Ys, /// mass fraction (kmcd.nSpec)
pressure, /// pressure
Zs_at_i,
Zs_out_at_i,
fac_at_i,
work, // work
kmcd,
kmcdSurf);
}
});
Kokkos::Profiling::popRegion();
}
} // namespace TChem
| 35.851064 | 88 | 0.654006 | [
"vector",
"model"
] |
f8c1e56100fa209b4f4ad2587bd9c42119986650 | 9,463 | hpp | C++ | ThirdParty-mod/java2cpp/android/telephony/cdma/CdmaCellLocation.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/android/telephony/cdma/CdmaCellLocation.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/android/telephony/cdma/CdmaCellLocation.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.telephony.cdma.CdmaCellLocation
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_TELEPHONY_CDMA_CDMACELLLOCATION_HPP_DECL
#define J2CPP_ANDROID_TELEPHONY_CDMA_CDMACELLLOCATION_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace android { namespace telephony { class CellLocation; } } }
namespace j2cpp { namespace android { namespace os { class Bundle; } } }
#include <android/os/Bundle.hpp>
#include <android/telephony/CellLocation.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
namespace j2cpp {
namespace android { namespace telephony { namespace cdma {
class CdmaCellLocation;
class CdmaCellLocation
: public object<CdmaCellLocation>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
J2CPP_DECLARE_METHOD(10)
J2CPP_DECLARE_METHOD(11)
J2CPP_DECLARE_METHOD(12)
J2CPP_DECLARE_METHOD(13)
explicit CdmaCellLocation(jobject jobj)
: object<CdmaCellLocation>(jobj)
{
}
operator local_ref<android::telephony::CellLocation>() const;
CdmaCellLocation();
CdmaCellLocation(local_ref< android::os::Bundle > const&);
jint getBaseStationId();
jint getBaseStationLatitude();
jint getBaseStationLongitude();
jint getSystemId();
jint getNetworkId();
void setStateInvalid();
void setCellLocationData(jint, jint, jint);
void setCellLocationData(jint, jint, jint, jint, jint);
jint hashCode();
jboolean equals(local_ref< java::lang::Object > const&);
local_ref< java::lang::String > toString();
void fillInNotifierBundle(local_ref< android::os::Bundle > const&);
}; //class CdmaCellLocation
} //namespace cdma
} //namespace telephony
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_TELEPHONY_CDMA_CDMACELLLOCATION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_TELEPHONY_CDMA_CDMACELLLOCATION_HPP_IMPL
#define J2CPP_ANDROID_TELEPHONY_CDMA_CDMACELLLOCATION_HPP_IMPL
namespace j2cpp {
android::telephony::cdma::CdmaCellLocation::operator local_ref<android::telephony::CellLocation>() const
{
return local_ref<android::telephony::CellLocation>(get_jobject());
}
android::telephony::cdma::CdmaCellLocation::CdmaCellLocation()
: object<android::telephony::cdma::CdmaCellLocation>(
call_new_object<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(0),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(0)
>()
)
{
}
android::telephony::cdma::CdmaCellLocation::CdmaCellLocation(local_ref< android::os::Bundle > const &a0)
: object<android::telephony::cdma::CdmaCellLocation>(
call_new_object<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(1),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
{
}
jint android::telephony::cdma::CdmaCellLocation::getBaseStationId()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(2),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(2),
jint
>(get_jobject());
}
jint android::telephony::cdma::CdmaCellLocation::getBaseStationLatitude()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(3),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(3),
jint
>(get_jobject());
}
jint android::telephony::cdma::CdmaCellLocation::getBaseStationLongitude()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(4),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(4),
jint
>(get_jobject());
}
jint android::telephony::cdma::CdmaCellLocation::getSystemId()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(5),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(5),
jint
>(get_jobject());
}
jint android::telephony::cdma::CdmaCellLocation::getNetworkId()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(6),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(6),
jint
>(get_jobject());
}
void android::telephony::cdma::CdmaCellLocation::setStateInvalid()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(7),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(7),
void
>(get_jobject());
}
void android::telephony::cdma::CdmaCellLocation::setCellLocationData(jint a0, jint a1, jint a2)
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(8),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(8),
void
>(get_jobject(), a0, a1, a2);
}
void android::telephony::cdma::CdmaCellLocation::setCellLocationData(jint a0, jint a1, jint a2, jint a3, jint a4)
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(9),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(9),
void
>(get_jobject(), a0, a1, a2, a3, a4);
}
jint android::telephony::cdma::CdmaCellLocation::hashCode()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(10),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(10),
jint
>(get_jobject());
}
jboolean android::telephony::cdma::CdmaCellLocation::equals(local_ref< java::lang::Object > const &a0)
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(11),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(11),
jboolean
>(get_jobject(), a0);
}
local_ref< java::lang::String > android::telephony::cdma::CdmaCellLocation::toString()
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(12),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(12),
local_ref< java::lang::String >
>(get_jobject());
}
void android::telephony::cdma::CdmaCellLocation::fillInNotifierBundle(local_ref< android::os::Bundle > const &a0)
{
return call_method<
android::telephony::cdma::CdmaCellLocation::J2CPP_CLASS_NAME,
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_NAME(13),
android::telephony::cdma::CdmaCellLocation::J2CPP_METHOD_SIGNATURE(13),
void
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(android::telephony::cdma::CdmaCellLocation,"android/telephony/cdma/CdmaCellLocation")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,1,"<init>","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,2,"getBaseStationId","()I")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,3,"getBaseStationLatitude","()I")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,4,"getBaseStationLongitude","()I")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,5,"getSystemId","()I")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,6,"getNetworkId","()I")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,7,"setStateInvalid","()V")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,8,"setCellLocationData","(III)V")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,9,"setCellLocationData","(IIIII)V")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,10,"hashCode","()I")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,11,"equals","(Ljava/lang/Object;)Z")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,12,"toString","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(android::telephony::cdma::CdmaCellLocation,13,"fillInNotifierBundle","(Landroid/os/Bundle;)V")
} //namespace j2cpp
#endif //J2CPP_ANDROID_TELEPHONY_CDMA_CDMACELLLOCATION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 35.441948 | 115 | 0.74395 | [
"object"
] |
f8c30d8be5b0b655ab8c78227df1471bd5ddac1f | 7,602 | cpp | C++ | LeetCode/C++/637. Average of Levels in Binary Tree.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | LeetCode/C++/637. Average of Levels in Binary Tree.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | LeetCode/C++/637. Average of Levels in Binary Tree.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | /**
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node's value is in the range of 32-bit signed integer.
**/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Runtime: 24 ms, faster than 99.44% of C++ online submissions for Average of Levels in Binary Tree.
//Memory Usage: 22.3 MB, less than 25.66% of C++ online submissions for Average of Levels in Binary Tree.
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ans;
queue<TreeNode*> q;
vector<int> levelVals;
int level = 0, levelCount = 1, nextLevelCount = 0;
q.push(root);
while(q.size()!=0){
TreeNode* cur = q.front();
q.pop();
levelVals.push_back(cur->val);
levelCount--;
if(cur->left!=NULL){
q.push(cur->left);
nextLevelCount++;
}
if(cur->right!=NULL){
q.push(cur->right);
nextLevelCount++;
}
if(levelCount==0){
levelCount = nextLevelCount;
nextLevelCount = 0;
level++;
double levelSum = accumulate(levelVals.begin(), levelVals.end(), 0.0);
ans.push_back(levelSum/levelVals.size());
levelVals.clear();
}
}
return ans;
}
};
/**
Approach #1 Using Depth First Search [Accepted]
Algorithm
One of the methods to solve the given problem is to make use of Depth First Search. In DFS, we try to exhaust each branch of the given tree during the tree traversal before moving onto the next branch.
To make use of DFS to solve the given problem, we make use of two lists countcount and resres. Here, count[i]count[i] refers to the total number of nodes found at the i^{th}i
th
level(counting from root at level 0) till now, and res[i]res[i] refers to the sum of the nodes at the i^{th}i
th
level encountered till now during the Depth First Search.
We make use of a function average(t, i, res, count), which is used to fill the resres and countcount array if we start the DFS from the node tt at the i^{th}i
th
level in the given tree. We start by making the function call average(root, 0, res, count). After this, we do the following at every step:
Add the value of the current node to the resres(or sumsum) at the index corresponding to the current level. Also, increment the countcount at the index corresponding to the current level.
Call the same function, average, with the left and the right child of the current node. Also, update the current level used in making the function call.
Repeat the above steps till all the nodes in the given tree have been considered once.
Populate the averages in the resultant array to be returned.
The following animation illustrates the process.
**/
/**
Complexity Analysis
Time complexity : O(n).
The whole tree is traversed once only.
Here, nn refers to the total number of nodes in the given binary tree.
Space complexity : O(h).
resres and countcount array of size h are used.
Here, h refers to the height(maximum number of levels) of the given binary tree.
Further, the depth of the recursive tree could go upto hh only.
**/
//Runtime: 44 ms, faster than 5.57% of C++ online submissions for Average of Levels in Binary Tree.
//Memory Usage: 22.5 MB, less than 16.81% of C++ online submissions for Average of Levels in Binary Tree.
/**
class Solution {
public:
void fillVectors(TreeNode* cur, int level, vector<double>& sum, vector<int>& count){
if(cur==NULL) return;
if(level < sum.size()){
sum[level]+=cur->val;
count[level]+=1;
cout << cur->val << endl;
}else{
sum.push_back(cur->val);
count.push_back(1);
cout << cur->val << endl;
}
//DFS
fillVectors(cur->left, level+1, sum, count);
fillVectors(cur->right, level+1, sum, count);
}
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ans;
vector<double> sum;
vector<int> count;
fillVectors(root, 0, sum, count);
for(int i = 0; i < sum.size(); i++){
ans.push_back(sum[i]/count[i]);
}
return ans;
}
};
**/
/**
Approach #2 Breadth First Search [Accepted]
Another method to solve the given problem is to make use of a Breadth First Search. In BFS, we start by pushing the root node into a queuequeue. Then, we remove an element(node) from the front of the queuequeue. For every node removed from the queuequeue, we add all its children to the back of the same queuequeue. We keep on continuing this process till the queuequeue becomes empty. In this way, we can traverse the given tree on a level-by-level basis.
But, in the current implementation, we need to do a slight modification, since we need to separate the nodes on one level from that of the other.
The steps to be performed are listed below:
Put the root node into the queuequeue.
Initialize sumsum and countcount as 0 and temptemp as an empty queue.
Pop a node from the front of the queuequeue. Add this node's value to the sumsum corresponding to the current level. Also, update the countcount corresponding to the current level.
Put the children nodes of the node last popped into the a temptemp queue(instead of queuequeue).
Continue steps 3 and 4 till queuequeue becomes empty. (An empty queuequeue indicates that one level of the tree has been considered).
Reinitialize queuequeue with its value as temptemp.
Populate the resres array with the average corresponding to the current level.
Repeat steps 2 to 7 till the queuequeue and temptemp become empty.
At the end, resres is the required result.
The following animation illustrates the process.
Time complexity : O(n).
The whole tree is traversed atmost once.
Here, n refers to the number of nodes in the given binary tree.
Space complexity : O(m).
The size of queuequeue or temptemp can grow upto atmost the maximum number of nodes at any level in the given binary tree.
Here, m refers to the maximum mumber of nodes at any level in the input tree.
**/
/**
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ans;
queue<TreeNode*> q;
q.push(root);
while(q.size()!=0){
double levelSum = 0;
int levelCount = 0;
queue<TreeNode*> qNext;
while(q.size()!=0){
TreeNode* cur = q.front();
q.pop();
levelSum += cur->val;
levelCount++;
if(cur->left!=NULL){
qNext.push(cur->left);
}
if(cur->right!=NULL){
qNext.push(cur->right);
}
}
ans.push_back(levelSum*1.0/levelCount);
q = qNext;
}
return ans;
}
};
**/
| 34.712329 | 456 | 0.62773 | [
"vector"
] |
f8c78d8113118a5f9d03e3840955af9bd28d52f3 | 9,131 | cpp | C++ | Src/Utilities/FFT_Wrapper.cpp | stpope/CSL6 | 5855a91fe8fc928753d180d8d5260a3ed3a1460b | [
"BSD-2-Clause"
] | 32 | 2020-04-17T22:48:53.000Z | 2021-06-15T13:13:28.000Z | Src/Utilities/FFT_Wrapper.cpp | stpope/CSL6 | 5855a91fe8fc928753d180d8d5260a3ed3a1460b | [
"BSD-2-Clause"
] | null | null | null | Src/Utilities/FFT_Wrapper.cpp | stpope/CSL6 | 5855a91fe8fc928753d180d8d5260a3ed3a1460b | [
"BSD-2-Clause"
] | 2 | 2020-06-05T15:51:31.000Z | 2021-08-31T15:09:26.000Z | //
// FFT_Wrapper.cpp -- wrapper class for FFTs that hides implementation details
// This file includes the 3 standard concrete subclasses:
// FFTW (assumes fftw3f),
// RealFFT (RealFFT code included in CSL), and
// KISS FFT (included, untested).
//
// See the copyright notice and acknowledgment of authors in the file COPYRIGHT
//
#include "FFT_Wrapper.h"
#include "math.h"
#include <string.h> // for memcpy
using namespace csl;
//-------------------------------------------------------------------------------------------------//
#pragma mark FFTW
#ifdef USE_FFTW // the FFTW-based version
// FFTW_Wrapper = FFTW-based concrete implementation
FFTW_Wrapper::FFTW_Wrapper(unsigned size, CSL_FFTType type, CSL_FFTDir forward)
: Abst_FFT_W(size, type, forward) {
// allocate buffers
mSampBuf = (SampleBuffer) fftwf_malloc(size * sizeof(sample));
mSpectBuf = (fftwf_complex *) fftwf_malloc(mCSize * sizeof(fftwf_complex));
if (mDirection == CSL_FFT_FORWARD) { // create FFT plans
// (int n, float *in, fftw_complex *out, unsigned flags);
mPlan = fftwf_plan_dft_r2c_1d(size, mSampBuf, mSpectBuf, FFTWF_FLAGS);
} else { // inverse FFT
// int n, fftw_complex *in, float *out, unsigned flags);
mPlan = fftwf_plan_dft_c2r_1d(size, mSpectBuf, mSampBuf, FFTWF_FLAGS);
}
// logMsg("FFTW %d", size);
}
FFTW_Wrapper::~FFTW_Wrapper() {
fftwf_destroy_plan(mPlan);
fftwf_free(mSampBuf);
fftwf_free(mSpectBuf);
}
/// run the transform
void FFTW_Wrapper::nextBuffer(Buffer & in, Buffer & out) throw (CException) {
if (mDirection == CSL_FFT_FORWARD) { // mDirection == CSL_FFT_FORWARD
// copy input into sample buffer
memcpy(mSampBuf, in.buffer(0), mSize * sizeof(sample));
// printf("\t%x - %x\n", in.buffer(0), out.buffer(0));
fftwf_execute(mPlan); //// GO ////
SampleBuffer ioPtr = out.buffer(0); // out buffer
fftwf_complex * spPtr = mSpectBuf; // spectrum ptr
if (mType == CSL_FFT_REAL) { // real: write magnitude to mono output
for (unsigned j = 0; j < mCSize; j++, spPtr++)
*ioPtr++ = hypotf((*spPtr)[0], (*spPtr)[0]);
} else if (mType == CSL_FFT_COMPLEX) { // copy complex ptr to output
memcpy(out.buffer(0), mSpectBuf + 1, (mSize * sizeof(sample)));
// memcpy(out.buffer(0), mSpectBuf, (mCSize * sizeof(fftwf_complex)));
} else if (mType == CSL_FFT_MAGPHASE) { // write mag/phase to buffer[0]/[1]
SampleBuffer inOutPh = out.buffer(1);
for (unsigned j = 0; j < in.mNumFrames; j++) {
// fprintf(stderr, "re:%f cx:%f ", (*spPtr)[0], (*spPtr)[1]);
*ioPtr++ = hypotf((*spPtr)[0], (*spPtr)[1]); // write magnitude
spPtr++;
if ((*spPtr)[0] == 0.0f) {
if ((*spPtr)[1] >= 0.0f)
*inOutPh++ = CSL_PIHALF;
else
*inOutPh++ = CSL_PI + CSL_PIHALF;
} else {
*inOutPh++ = atan((*spPtr)[1] / (*spPtr)[0]); // write phase
}
}
}
} else { // mDirection == CSL_FFT_INVERSE
// copy data into spectrum
memcpy(mSpectBuf, in.buffer(0), (mCSize * sizeof(fftwf_complex)));
fftwf_execute(mPlan); // GO
// copy real output
memcpy(out.buffer(0), mSampBuf, (mSize * sizeof(sample)));
}
}
#endif // FFTW
//-------------------------------------------------------------------------------------------------//
#pragma mark FFTREAL
#ifdef USE_FFTREAL // the FFTReal-based version
// FFTR_Wrapper = FFTReal-based concrete implementation
FFTR_Wrapper::FFTR_Wrapper(unsigned size, CSL_FFTType type, CSL_FFTDir forward)
: Abst_FFT_W(size, type, forward), mFFT(size) {
SAFE_MALLOC(mTempBuf, sample, size + 1);
// logMsg("FFTReal %d", size);
}
FFTR_Wrapper::~FFTR_Wrapper() {
SAFE_FREE(mTempBuf);
}
// execute = run the transform
void FFTR_Wrapper::nextBuffer(Buffer & in, Buffer & out) throw (CException) {
if (mDirection == CSL_FFT_FORWARD) { // mDirection == CSL_FFT_FORWARD
SampleBuffer ioPtr = in.buffer(0); // set input data ptr
// printf("\t%x - %x\n", in.buffer(0), out.buffer(0));
mFFT.do_fft(mTempBuf, ioPtr); // perform FFT
// do_fft (flt_t f [], const flt_t x []) -- this is the fcn signature
// - x: pointer on the source array (time).
// - f: pointer on the destination array (frequencies).
// f [0...length(x)/2] = real values,
// f [length(x)/2+1...length(x)-1] = imaginary values of coeff 1...length(x)/2-1.
if (mType == CSL_FFT_COMPLEX) { // raw: copy complex points to output
SampleComplexPtr cxPtr = (SampleComplexPtr) out.buffer(0);
SampleBuffer rPtr = mTempBuf;
SampleBuffer iPtr = mTempBuf + (mSize / 2) ; // + 1;
float normFactor = 1.0 / sqrt((double) mSize);
for (unsigned j = 0; j < mSize / 2; j++) {
SampleBuffer cplx = cxPtr[j];
cx_r(cplx) = *rPtr++ * normFactor;
cx_i(cplx) = *iPtr++ * normFactor;
}
} else if (mType == CSL_FFT_REAL) { // real: write magnitude to mono output
ioPtr = out.buffer(0); // output pointer
SampleBuffer rPtr = mTempBuf;
SampleBuffer iPtr = mTempBuf + (mSize / 2) ; // + 1;
for (unsigned j = 0; j < mSize / 2; j++)
*ioPtr++ = hypotf(*rPtr++, *iPtr++);
} else if (mType == CSL_FFT_MAGPHASE) { // complex: write mag/phase to buffer[0]/[1]
ioPtr = out.buffer(0); // output pointer
SampleBuffer rPtr = mTempBuf;
SampleBuffer iPtr = mTempBuf + (mSize / 2);
SampleBuffer inOutPh = out.buffer(1);
for (unsigned j = 0; j < mSize / 2; j++) {
*ioPtr++ = hypotf(*rPtr, *iPtr);
if (*rPtr == 0.0f) {
if (*iPtr >= 0.0f)
*inOutPh++ = CSL_PIHALF;
else
*inOutPh++ = CSL_PI + CSL_PIHALF;
} else {
*inOutPh++ = atan(*iPtr / *rPtr);
}
rPtr++;
iPtr++;
} // end of loop
}
} else { // mDirection == CSL_FFT_INVERSE
if (mType == CSL_FFT_COMPLEX) { // CSL_FFT_COMPLEX format
// copy complex spectrum to un-packed IFFT format
SampleComplexPtr ioPtr = (SampleComplexPtr) in.buffer(0);
SampleBuffer rPtr = mTempBuf; // copy data to FFTReal format
SampleBuffer iPtr = mTempBuf + (mSize / 2);
for (unsigned j = 0; j < mSize / 2; j++) { // loop to unpack complex array
SampleBuffer cplx = ioPtr[j];
*rPtr++ = cx_r(cplx);
*iPtr++ = cx_i(cplx);
}
} else if (mType == CSL_FFT_REAL) { // real: copy real spectrum to un-packed IFFT format
SampleBuffer ioPtr = in.buffer(0);
SampleBuffer rPtr = mTempBuf; // copy data to FFTReal format
SampleBuffer iPtr = mTempBuf + (mSize / 2);
for (unsigned j = 0; j < mSize / 2; j++) { // loop to unpack real array
*rPtr++ = *ioPtr++;
*iPtr++ = 0.0f;
}
}
SampleBuffer oPtr = out.buffer(0); // output pointer
mFFT.do_ifft(mTempBuf, oPtr);
// do_ifft (const flt_t f [], flt_t x [])
// - f: pointer on the source array (frequencies).
// f [0...length(x)/2] = real values,
// f [length(x)/2+1...length(x)] = imaginary values of coeff 1...length(x)-1.
// - x: pointer on the destination array (time).
}
}
#endif
//-------------------------------------------------------------------------------------------------//
#pragma mark KISSFFT
#ifdef USE_KISSFFT
// KISSFFT_Wrapper = KISS FFT-based concrete implementation
KISSFFT_Wrapper::KISSFFT_Wrapper(unsigned size, CSL_FFTType type, CSL_FFTDir forward)
: Abst_FFT_W(size, type, forward) {
int dir = (forward == CSL_FFT_FORWARD) ? 0 : 1;
mFFT = kiss_fft_alloc(size, dir, NULL, NULL);
SAFE_MALLOC(inBuf, SampleComplex, size);
SAFE_MALLOC(outBuf, SampleComplex, size);
}
KISSFFT_Wrapper::~KISSFFT_Wrapper() {
free(mFFT);
kiss_fft_cleanup();
}
// run the transform between in and out
void KISSFFT_Wrapper::nextBuffer(Buffer & in, Buffer & out) throw (CException) {
if (mDirection == CSL_FFT_FORWARD) { // mDirection == CSL_FFT_FORWARD
SampleBuffer ioPtr = in.buffer(0); // input data ptr
SampleComplexPtr cxPtr = inBuf;
for (int j = 0; j < mSize; j++) { // loop to pack complex array
*cxPtr[0] = *ioPtr++;
cxPtr++;
}
// kiss_fft(kiss_fft_cfg cfg, const kiss_fft_cpx *fin, kiss_fft_cpx *fout)
// Perform an FFT on a complex input buffer.
// for a forward FFT,
// fin should be f[0] , f[1] , ... ,f[nfft-1]
// fout will be F[0] , F[1] , ... ,F[nfft-1]
// Note that each element is complex and can be accessed like f[k].r and f[k].i
kiss_fft(mFFT, (const kiss_fft_cpx *) inBuf, (kiss_fft_cpx *) outBuf);
ioPtr = out.buffer(0); // output pointer
if (mType == CSL_FFT_REAL) { // real: write magnitude to mono output
SampleBuffer rPtr = mTempBuf;
SampleBuffer iPtr = mTempBuf + (mSize / 2);
*ioPtr++ = *rPtr++;
*ioPtr++;
for (int j = 1; j < mSize; j++)
*ioPtr++ = hypotf(*rPtr++, *iPtr++);
} else if (mType == CSL_FFT_COMPLEX) { // raw: copy complex points to output
memcpy(ioPtr, outBuf, mSize * sizeof(SampleComplex));
}
} else { // mDirection == CSL_FFT_INVERSE
kiss_fft(mFFT, (const kiss_fft_cpx *) in.buffer(0), (kiss_fft_cpx *) outBuf);
SampleComplexPtr cxPtr = outBuf;
SampleBuffer ioPtr = out.buffer(0);
for (int j = 0; j < mSize; j++) // loop to unpack complex array
*ioPtr++ = cxPtr[j][0];
}
}
#endif
| 34.327068 | 101 | 0.610886 | [
"transform"
] |
f8d1c0da2732e91e64d09e7483e6077c8bb42f59 | 6,450 | cpp | C++ | src/DistanceToObject.cpp | username10000/Through-the-Darkness-of-Space | 34be0b65f60f0e10b0cbfb78793afa027d005a69 | [
"MIT"
] | null | null | null | src/DistanceToObject.cpp | username10000/Through-the-Darkness-of-Space | 34be0b65f60f0e10b0cbfb78793afa027d005a69 | [
"MIT"
] | null | null | null | src/DistanceToObject.cpp | username10000/Through-the-Darkness-of-Space | 34be0b65f60f0e10b0cbfb78793afa027d005a69 | [
"MIT"
] | null | null | null | #include <DistanceToObject.h>
DistanceToObject::DistanceToObject(sf::VideoMode _screen, sf::Font _font) {
screen = _screen;
font = _font;
size = (float)(screen.height / 5);
offset = 10;
// Settings for the outer circle
circle.setPosition(offset, screen.height - size - offset);
circle.setRadius(size / 2);
circle.setFillColor(sf::Color::Transparent);
circle.setOutlineThickness(2);
circle.setOutlineColor(sf::Color::White);
// Settings for the inner circle
innerCircle.setPosition(offset + size / 4, screen.height - 3 * size / 4 - offset);
innerCircle.setRadius(size / 4);
innerCircle.setFillColor(sf::Color::Transparent);
innerCircle.setOutlineThickness(1);
innerCircle.setOutlineColor(sf::Color::White);
// Settings for the text
distanceText.setFont(font);
distanceText.setCharacterSize(10);
distanceText.setColor(sf::Color::Red);
distanceText.setPosition(size / 2 + offset, screen.height - size / 2 - distanceText.getCharacterSize() - offset);
distanceText.setString("0");
// Settings for the target text
targetText.setFont(font);
targetText.setCharacterSize(10);
targetText.setColor(sf::Color::Cyan);
targetText.setPosition(size / 2 + offset, screen.height - size / 2 + distanceText.getCharacterSize() - offset);
targetText.setString("0");
// Settings for the closest name
closestName.setFont(font);
closestName.setCharacterSize(12);
closestName.setColor(sf::Color::Red);
closestName.setStyle(sf::Text::Bold);
closestName.setPosition(size / 2 + offset, screen.height - size / 2 - distanceText.getCharacterSize() * 2 - offset);
closestName.setString("0");
// Settings for the target name
targetName.setFont(font);
targetName.setCharacterSize(12);
targetName.setColor(sf::Color::Cyan);
targetName.setStyle(sf::Text::Bold);
targetName.setPosition(size / 2 + offset, screen.height - size / 2 + distanceText.getCharacterSize() * 2 - offset);
targetName.setString("0");
// Initialising the direction line
line[0] = sf::Vertex(sf::Vector2f(0, 0), sf::Color::Red);
line[1] = sf::Vertex(sf::Vector2f(0, 0), sf::Color::Red);
// Initialising the target line
targetLine[0] = sf::Vertex(sf::Vector2f(0, 0), sf::Color::Cyan);
targetLine[1] = sf::Vertex(sf::Vector2f(0, 0), sf::Color::Cyan);
// Initialising the split line
splitLine[0] = sf::Vertex(sf::Vector2f(size / 4 + offset, screen.height - size / 2 - offset));
splitLine[1] = sf::Vertex(sf::Vector2f(size / 4 + size / 2 + offset, screen.height - size / 2 - offset));
// Initialise the target object
targetDistance = -1;
targetAngle = 0;
// Initialise the Ship Direction indication
shipDirection.setPointCount(3);
shipDirection.setRadius(size / 4 / 8);
}
void DistanceToObject::setTargetDistance(float d) {
targetDistance = d;
}
void DistanceToObject::setTargetAngle(float a) {
targetAngle = a;
}
void DistanceToObject::setTargetName(std::string n) {
targetName.setString(n);
targetName.setOrigin(targetName.getLocalBounds().width / 2, targetName.getLocalBounds().height / 2);
}
float DistanceToObject::getTargetAngle() {
return targetAngle;
}
bool DistanceToObject::getHovered() {
if (Functions::dist(mouse.getPosition().x, mouse.getPosition().y, circle.getPosition().x + circle.getRadius(), circle.getPosition().y + circle.getRadius()) < circle.getRadius())
return true;
else
return false;
}
std::string DistanceToObject::getDescription() {
return "Shows the distance to the Closest Planet (RED) \nand the distance to the Target Planet (Cyan)";
}
void DistanceToObject::update(float _angle, float _distance, std::string _name, float _shipAngle) {
angle = _angle;
distance = _distance;
// Creating the string
//char d[15];
//sprintf_s(d, "%d km", (int)distance);
distanceText.setString(Functions::toStringWithComma((int)distance) + " km");
distanceText.setOrigin(distanceText.getLocalBounds().width / 2, distanceText.getLocalBounds().height / 2);
//distanceText.setOrigin(distanceText.getCharacterSize() * strlen(d) / 4, distanceText.getCharacterSize() / 2);
// Setting the name of the Object
//closestName.setOrigin(closestName.getCharacterSize() * _name.size() / 4, closestName.getCharacterSize() / 2);
closestName.setString(_name);
closestName.setOrigin(closestName.getLocalBounds().width / 2, closestName.getLocalBounds().height / 2);
// Setting the coordinates of the direction line
line[0] = sf::Vertex(sf::Vector2f(offset + size / 2 - cos(angle) * size / 4, screen.height - size / 2 - offset - sin(angle) * size / 4), sf::Color::Red);
line[1] = sf::Vertex(sf::Vector2f(offset + size / 2 - cos(angle) * size / 2, screen.height - size / 2 - offset - sin(angle) * size / 2), sf::Color::Red);
// Set the angle of the Ship
shipAngle = _shipAngle + 3.14159 / 2 + 0.15;
shipDirection.setPosition(size / 2 + offset - cos(shipAngle) * (size / 4 + shipDirection.getRadius()), screen.height - size / 2 - offset - sin(shipAngle) * (size / 4 + shipDirection.getRadius()));
shipDirection.setRotation(shipAngle * 180 / 3.14159 + 23);
//std::cout << shipAngle << std::endl;
if (targetDistance != -1) {
// Creating the string
//char dA[15];
//sprintf_s(dA, "%d km", (int)targetDistance);
targetText.setString(Functions::toStringWithComma((int)targetDistance) + " km");
targetText.setOrigin(targetText.getLocalBounds().width / 2, targetText.getLocalBounds().height / 2);
//targetText.setOrigin(targetText.getCharacterSize() * strlen(dA) / 4, targetText.getCharacterSize() / 2);
// Set the centre of the text
//targetName.setOrigin(targetName.getCharacterSize() * targetName.getString().getSize() / 4, targetName.getCharacterSize() / 2);
// Setting the coordinates of the target line
targetLine[0] = sf::Vertex(sf::Vector2f(offset + size / 2 - cos(targetAngle) * size / 4, screen.height - size / 2 - offset - sin(targetAngle) * size / 4), sf::Color::Cyan);
targetLine[1] = sf::Vertex(sf::Vector2f(offset + size / 2 - cos(targetAngle) * size / 2, screen.height - size / 2 - offset - sin(targetAngle) * size / 2), sf::Color::Cyan);
}
}
void DistanceToObject::render(sf::RenderWindow &window) {
window.draw(line, 2, sf::Lines);
if (targetDistance != -1)
window.draw(targetLine, 2, sf::Lines);
window.draw(splitLine, 2, sf::Lines);
window.draw(circle);
window.draw(innerCircle);
window.draw(distanceText);
if (targetDistance != -1)
window.draw(targetText);
window.draw(closestName);
if (targetDistance != -1)
window.draw(targetName);
window.draw(shipDirection);
} | 40.3125 | 197 | 0.715504 | [
"render",
"object"
] |
f8d41313d1066e803bf10f284b797022834c4122 | 1,681 | hpp | C++ | interface/omni/core/model/literal_expression.hpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | 33 | 2015-03-21T04:12:45.000Z | 2021-04-18T21:44:33.000Z | interface/omni/core/model/literal_expression.hpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | null | null | null | interface/omni/core/model/literal_expression.hpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | 2 | 2016-03-05T12:57:05.000Z | 2017-09-12T10:11:52.000Z | #ifndef OMNI_CORE_MODEL_LITERAL_EXPRESSION_HPP
#define OMNI_CORE_MODEL_LITERAL_EXPRESSION_HPP
#include <omni/core/core.hpp>
#include <omni/core/model/pure_expression.hpp>
#ifndef Q_MOC_RUN
#include <boost/any.hpp>
#include <boost/signals2.hpp>
#endif
namespace omni {
namespace core {
class context;
}}
namespace omni {
namespace core {
namespace model {
/**
@class literal_expression literal_expression.hpp omni/core/model/literal_expression.hpp
@brief A literal_expression is an expression that returns a value that was already defined at compile time.
literal_expression is abstract. Use the subclass builtin_literal_expression to create a literal.
(class_literal_expression will be coming later, when classes are implemented.)
**/
class OMNI_CORE_API literal_expression : public pure_expression {
public:
typedef boost::signals2::signal <void (literal_expression & sender, boost::any oldValue, boost::any newValue)> ValueChangedSignal;
boost::signals2::connection connectValueChanged (ValueChangedSignal::slot_type handler);
static meta_info & getStaticMetaInfo ();
virtual meta_info & getMetaInfo () const = 0;
virtual std::string toString (bool fullyQualified = true) const = 0;
static std::shared_ptr <literal_expression> fromString (omni::core::context & context, std::string const & text, literal_expression * originatingLiteral);
protected:
virtual void valueChanged (boost::any oldValue, boost::any newValue);
private:
ValueChangedSignal _valueChangedSignal;
};
} // namespace model
} // namespace core
} // namespace omni
#endif // include guard
| 31.12963 | 162 | 0.744795 | [
"model"
] |
f8d6a4bc120e656bc8141d6110f629ea7a4d5ef0 | 3,308 | cpp | C++ | day23_equal_and_lexicographical_compare.cpp | KuKuXia/30-Days-Plan-for-Practicing-C-Plus-Plus-11-STL | dddb1f3f6b43b628b87dcb26b72495e5c7d19e55 | [
"MIT"
] | null | null | null | day23_equal_and_lexicographical_compare.cpp | KuKuXia/30-Days-Plan-for-Practicing-C-Plus-Plus-11-STL | dddb1f3f6b43b628b87dcb26b72495e5c7d19e55 | [
"MIT"
] | null | null | null | day23_equal_and_lexicographical_compare.cpp | KuKuXia/30-Days-Plan-for-Practicing-C-Plus-Plus-11-STL | dddb1f3f6b43b628b87dcb26b72495e5c7d19e55 | [
"MIT"
] | null | null | null | //
// Created by LongXiaJun on 2018/12/29 0029.
//
#include "day23_equal_and_lexicographical_compare.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <random>
namespace demo_equal_and_lexicographical_compare {
namespace definition {
//Possible definition
template<typename InputIt1, typename InputIt2>
bool equal(InputIt1 first1, InputIt1 last1,
InputIt2 first2) {
for (; first1 != last1; ++first1, ++first2) {
if (!(*first1 == *first2)) {
return false;
}
}
return true;
}
template<typename InputIt1, typename InputIt2, typename BinaryPredicate>
bool equal(InputIt1 first1, InputIt1 last1,
InputIt2 first2, BinaryPredicate p) {
for (; first1 != last1; ++first1, ++first2) {
if (!p(*first1, *first2)) {
return false;
}
}
return true;
}
template<typename InputIt1, typename InputIt2>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2) {
for (; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2) {
if (*first1 < *first2) return true;
if (*first2 < *first1) return false;
}
return (first1 == last1) && (first2 != last2);
}
template<typename InputIt1, typename InputIt2, typename Compare>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
Compare comp) {
for (; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2) {
if (comp(*first1, *first2)) return true;
if (comp(*first2, *first1)) return false;
}
return (first1 == last1) && (first2 != last2);
}
}
// 测试字符串是否为回文
void test(const std::string &s) {
if (std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin())) {
std::cout << "\"" << s << "\" is a palindrome\n";
} else {
std::cout << "\"" << s << "\" is not a palindrome\n";
}
}
void stl_equal_and_lexicographical_compare() {
std::cout << "STL equal usage demo: \n";
test("radar");
test("hello");
std::cout << "STL lexicographical_compare usage demo: \n";
std::vector<char> v1{'a', 'b', 'c', 'd'};
std::vector<char> v2{'a', 'b', 'c', 'd'};
std::mt19937 g{std::random_device{}()};
while (!std::lexicographical_compare(v1.begin(), v1.end(),
v2.begin(), v2.end())) {
for (auto c : v1) std::cout << c << ' ';
std::cout << ">= ";
for (auto c : v2) std::cout << c << ' ';
std::cout << '\n';
std::shuffle(v1.begin(), v1.end(), g);
std::shuffle(v2.begin(), v2.end(), g);
}
for (auto c : v1) std::cout << c << ' ';
std::cout << "< ";
for (auto c : v2) std::cout << c << ' ';
std::cout << '\n';
}
} | 33.755102 | 87 | 0.480351 | [
"vector"
] |
f8d85abbfc2348b1f74e3c5b34b9706223c504e0 | 4,932 | cpp | C++ | src/Cello/mesh_ItFace.cpp | brittonsmith/enzo-e | 56d8417f2bdfc60f38326ba7208b633bfcea3175 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/Cello/mesh_ItFace.cpp | brittonsmith/enzo-e | 56d8417f2bdfc60f38326ba7208b633bfcea3175 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/Cello/mesh_ItFace.cpp | brittonsmith/enzo-e | 56d8417f2bdfc60f38326ba7208b633bfcea3175 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | // See LICENSE_CELLO file for license and copyright information
/// @file mesh_ItFace.cpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2013-06-11
/// @brief Implementation of the ItFace class
#include "mesh.hpp"
//----------------------------------------------------------------------
ItFace::ItFace(int rank,
int rank_limit,
bool periodic[3][2],
int n3[3],
Index index,
const int * ic3,
const int * ipf3) throw()
: if3_(),
ic3_(),
ipf3_(),
rank_(rank),
rank_limit_(rank_limit),
index_(index)
{
reset();
if (ic3) {
ic3_.resize(3);
for (int i=0; i<rank; i++) ic3_[i] = ic3[i];
for (int i=rank; i<3; i++) ic3_[i] = 0;
}
if (ipf3) {
ipf3_.resize(3);
for (int i=0; i<rank; i++) ipf3_[i] = ipf3[i];
for (int i=rank; i<3; i++) ipf3_[i] = ipf3[i];
}
for (int axis=0; axis<3; axis++) {
n3_[axis] = n3[axis];
for (int face=0; face<2; face++) {
periodicity_[axis][face] = periodic[axis][face];
}
}
}
//----------------------------------------------------------------------
ItFace::~ItFace() throw()
{
}
//----------------------------------------------------------------------
bool ItFace::next_ () throw()
{
do {
increment_() ;
} while (!valid_());
return (!is_reset());
}
//----------------------------------------------------------------------
void ItFace::face_ (int if3[3]) const
{
if3[0] = (rank_ >= 1) ? if3_[0] : 0;
if3[1] = (rank_ >= 2) ? if3_[1] : 0;
if3[2] = (rank_ >= 3) ? if3_[2] : 0;
}
//----------------------------------------------------------------------
Index ItFace::index() const
{
return index_.index_neighbor(if3_,n3_);
}
//----------------------------------------------------------------------
void ItFace::reset() throw()
{
if3_[0] = -2;
if3_[1] = 0;
if3_[2] = 0;
}
//----------------------------------------------------------------------
bool ItFace::is_reset() const
{
return if3_[0] == -2;
}
//----------------------------------------------------------------------
void ItFace::increment_()
{
if (is_reset()) {
set_first_();
} else {
if (rank_ >= 1 && if3_[0] < 1) {
++if3_[0];
} else {
if3_[0] = -1;
if (rank_ >= 2 && if3_[1] < 1) {
++if3_[1];
} else {
if3_[1] = -1;
if (rank_ >= 3 && if3_[2] < 1) {
++if3_[2];
} else {
reset();
}
}
}
}
}
//----------------------------------------------------------------------
void ItFace::set_first_()
{
if3_[0] = rank_ >= 1 ? -1 : 0;
if3_[1] = rank_ >= 2 ? -1 : 0;
if3_[2] = rank_ >= 3 ? -1 : 0;
}
//----------------------------------------------------------------------
bool ItFace::valid_() const
{
if (is_reset()) return true;
int rank_face = rank_ -
(abs(if3_[0]) + abs(if3_[1]) + abs(if3_[2]));
bool l_range = (rank_limit_ <= rank_face && rank_face < rank_);
bool l_face = true;
bool l_parent = true;
if (ic3_.size() > 0) {
if (ipf3_.size() == 0) {
// Face must be adjacent to child
if (ic3_.size() >= 1 && rank_ >= 1) {
if (if3_[0] == -1 && ic3_[0] != 0) l_face = false;
if (if3_[0] == 1 && ic3_[0] != 1) l_face = false;
}
if (ic3_.size() >= 2 && rank_ >= 2) {
if (if3_[1] == -1 && ic3_[1] != 0) l_face = false;
if (if3_[1] == 1 && ic3_[1] != 1) l_face = false;
}
if (ic3_.size() >= 3 && rank_ >= 3) {
if (if3_[2] == -1 && ic3_[2] != 0) l_face = false;
if (if3_[2] == 1 && ic3_[2] != 1) l_face = false;
}
} else {
// Face must be adjacent to same parent's face
if (ipf3_.size() >= 1) {
if (ipf3_[0] != 0 && (if3_[0] != ipf3_[0])) l_parent = false;
if (ipf3_[0] == 0 &&
((ic3_[0] == 0 && if3_[0] == -1) ||
(ic3_[0] == 1 && if3_[0] == 1))) l_parent = false;
}
if (ipf3_.size() >= 2) {
if (ipf3_[1] != 0 && (if3_[1] != ipf3_[1])) l_parent = false;
if (ipf3_[1] == 0 &&
((ic3_[1] == 0 && if3_[1] == -1) ||
(ic3_[1] == 1 && if3_[1] == 1))) l_parent = false;
}
if (ipf3_.size() >= 3) {
if (ipf3_[2] != 0 && (if3_[2] != ipf3_[2])) l_parent = false;
if (ipf3_[2] == 0 &&
((ic3_[2] == 0 && if3_[2] == -1) ||
(ic3_[2] == 1 && if3_[2] == 1))) l_parent = false;
}
}
}
bool l_periodic = true;
// Return false if on boundary and not periodic
if (index_.is_on_boundary(if3_,n3_)) {
if (if3_[0] == -1 && ! periodicity_[0][0]) l_periodic = false;
if (if3_[0] == +1 && ! periodicity_[0][1]) l_periodic = false;
if (if3_[1] == -1 && ! periodicity_[1][0]) l_periodic = false;
if (if3_[1] == +1 && ! periodicity_[1][1]) l_periodic = false;
if (if3_[2] == -1 && ! periodicity_[2][0]) l_periodic = false;
if (if3_[2] == +1 && ! periodicity_[2][1]) l_periodic = false;
}
return (l_face && l_range && l_parent && l_periodic);
}
//======================================================================
| 25.6875 | 72 | 0.417072 | [
"mesh"
] |
f8d9ecd114b84c89b783cfd471b4f6f10f311c76 | 37,356 | cpp | C++ | lib/IniProcessor/ini_processing.cpp | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | null | null | null | lib/IniProcessor/ini_processing.cpp | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | null | null | null | lib/IniProcessor/ini_processing.cpp | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | null | null | null | /*
* INI Processor - a small library which allows you parsing INI-files
*
* Copyright (c) 2015-2021 Vitaly Novichkov <admin@wohlnet.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.
*/
//#define USE_FILE_MAPPER
/* Stop parsing on first error (default is to keep parsing). */
//#define INI_STOP_ON_FIRST_ERROR
#ifdef _MSC_VER
#pragma warning (disable : 4127)
#pragma warning (disable : 4244)
#endif
#include "ini_processing.h"
#include <cstdio>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <clocale>
#include <sstream>
#include <algorithm>
#include <assert.h>
#ifdef _WIN32
# ifdef _MSC_VER
# ifdef _WIN64
typedef __int64 ssize_t;
# else
typedef __int32 ssize_t;
# endif
# ifndef NOMINMAX
# define NOMINMAX //Don't override std::min and std::max
# endif
# endif
# include <windows.h>
#endif
#ifdef USE_FILE_MAPPER
/*****Replace this with right path to file mapper class*****/
#include "../fileMapper/file_mapper.h"
#endif
static const unsigned char utfbom[3] = {0xEF, 0xBB, 0xBF};
enum { Space = 0x01, Special = 0x02, INIParamEq = 0x04 };
static const unsigned char charTraits[256] =
{
// Space: '\t', '\n', '\r', ' '
// Special: '\n', '\r', '"', ';', '=', '\\'
// INIParamEq: ':', '='
0, 0, 0, 0, 0, 0, 0, 0, 0, Space, Space | Special, 0, 0, Space | Special,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Space, 0, Special,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, INIParamEq,
Special, 0, Special | INIParamEq, 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, Special, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0
};
#if 0//for speed comparison who faster - macro or inline function. Seems speeds are same
#define IS_SPACE(c) (charTraits[static_cast<unsigned char>(c)] & Space)
#define IS_SPECIAL(c) (charTraits[static_cast<unsigned char>(c)] & Special)
#define IS_INIEQUAL(c) (charTraits[static_cast<unsigned char>(c)] & INIParamEq)
#else
inline unsigned char IS_SPACE(char &c)
{
return (charTraits[static_cast<unsigned char>(c)] & Space);
}
inline unsigned char IS_SPECIAL(char &c)
{
return (charTraits[static_cast<unsigned char>(c)] & Special);
}
inline unsigned char IS_INIEQUAL(char &c)
{
return (charTraits[static_cast<unsigned char>(c)] & INIParamEq);
}
#endif
/* Strip whitespace chars off end of given string, in place. Return s. */
inline char *rstrip(char *s)
{
char *p = s + strlen(s);
while(p > s && IS_SPACE(*--p))
*p = '\0';
return s;
}
/* Return pointer to first non-whitespace char in given string. */
inline char *lskip(char *s)
{
while(*s && IS_SPACE(*s))
s++;
return reinterpret_cast<char *>(s);
}
inline char *lrtrim(char *s)
{
while(*s && IS_SPACE(*s))
s++;
char *p = s + strlen(s);
while(p > s && IS_SPACE(*--p))
*p = '\0';
return s;
}
/* Return pointer to first char c or ';' comment in given string, or pointer to
null at end of string if neither found. ';' must be prefixed by a whitespace
character to register as a comment. */
inline char *find_char_or_comment(char *s, char c)
{
unsigned char was_whitespace = 0;
while(*s && *s != c && !(was_whitespace && *s == ';'))
{
was_whitespace = IS_SPACE(*s);
s++;
}
return s;
}
inline char *find_inieq_or_comment(char *s)
{
unsigned char was_whitespace = 0;
while(*s && (!IS_INIEQUAL(*s)) && !(was_whitespace && *s == ';'))
{
was_whitespace = IS_SPACE(*s);
s++;
}
return s;
}
inline char *removeQuotes(char *begin, char *end)
{
if((*begin == '\0') || (begin == end))
return begin;
if((*begin == '"') && (begin + 1 != end))
begin++;
else
return begin;
if(*(end - 1) == '"')
*(end - 1) = '\0';
return begin;
}
inline char *unescapeString(char* str)
{
char *src, *dst;
src = str;
dst = str;
while(*src)
{
if(*src == '\\')
{
src++;
switch(*src)
{
case 'n': *dst = '\n'; break;
case 'r': *dst = '\r'; break;
case 't': *dst = '\t'; break;
default: *dst = *src; break;
}
}
else
if(src != dst)
{
*dst = *src;
}
src++; dst++;
}
*dst = '\0';
return str;
}
//Remove comment line from a tail of value
inline void skipcomment(char *value)
{
unsigned char quoteDepth = 0;
while(*value)
{
if(quoteDepth > 0)
{
if(*value == '\\')
{
value++;
continue;
}
if(*value == '"')
--quoteDepth;
}
else if(*value == '"')
++quoteDepth;
if((quoteDepth == 0) && (*value == ';'))
{
*value = '\0';
break;
}
value++;
}
}
inline bool memfgets(char *&line, char *data, char *&pos, char *end)
{
line = pos;
while(pos != end)
{
if(*pos == '\n')
{
if((pos > data) && (*(pos - 1) == '\r'))
*((pos++) - 1) = '\0';//Support CRLF too
else
*(pos++) = '\0';
break;
}
++pos;
}
return (pos != line);
//EOF is a moment when position wasn't changed.
//If do check "pos != end", will be an inability to read last line.
//this logic allows detect true EOF when line is really eof
}
/* See documentation in header file. */
bool IniProcessing::parseHelper(char *data, size_t size)
{
char *section = nullptr;
#if defined(INI_ALLOW_MULTILINE)
char *prev_name = nullptr;
#endif
char *start;
char *end;
char *name;
char *value;
int lineno = 0;
int error = 0;
char *line;
char *pos_end = data + size;
char *pos_cur = data;
params::IniKeys *recentKeys = nullptr;
/* Scan through file line by line */
//while (fgets(line, INI_MAX_LINE, file) != NULL)
while(memfgets(line, data, pos_cur, pos_end))
{
lineno++;
start = line;
if((lineno == 1) && (size >= 3) && (memcmp(start, utfbom, 3) == 0))
start += 3;
start = lrtrim(start);
if(!*start)//if empty line - skip it away!
continue;
switch(*start)
{
case ';':
case '#':
//if (*start == ';' || *start == '#') {
// /* Per Python ConfigParser, allow '#' comments at start of line */
//}
continue;
case '[':
{
/* A "[section]" line */
end = find_char_or_comment(start + 1, ']');
if(*end == ']')
{
*end = '\0';
section = start + 1;
//#if defined(INI_ALLOW_MULTILINE)
// prev_name = nullptr;
//#endif
recentKeys = &m_params.iniData[section];
}
else if(!error)
{
/* No ']' found on section line */
m_params.errorCode = ERR_SECTION_SYNTAX;
error = lineno;
}
}
break;
default:
{
/* Not a comment, must be a name[=:]value pair */
end = find_inieq_or_comment(start);
if(IS_INIEQUAL(*end))
{
*end = '\0';
name = rstrip(start);
value = lskip(end + 1);
end = find_char_or_comment(value, '\0');
#ifndef CASE_SENSITIVE_KEYS
for(char *iter = name; *iter != '\0'; ++iter)
*iter = (char)tolower(*iter);
#endif
if(*end == ';')
*end = '\0';
rstrip(value);
{
char *v = value;
skipcomment(v);
v = rstrip(v);
if(!recentKeys)
recentKeys = &m_params.iniData["General"];
#ifdef INIDEBUG
printf("-> [%s]; %s = %s\n", section, name, v);
#endif
(*recentKeys)[name] = unescapeString( removeQuotes(v, v + strlen(v)) );
}
}
else if(!error)
{
/* No '=' or ':' found on name[=:]value line */
m_params.errorCode = ERR_KEY_SYNTAX;
error = lineno;
}
break;
}
}//switch(*start)
#if defined(INI_STOP_ON_FIRST_ERROR)
if(error)
break;
#endif
}
m_params.lineWithError = error;
return (error == 0);
}
/* See documentation in header file. */
bool IniProcessing::parseFile(const char *filename)
{
bool valid = true;
char *tmp = nullptr;
#ifdef USE_FILE_MAPPER
//By mystical reasons, reading whole file form fread() is faster than mapper :-P
PGE_FileMapper file(filename);
if(!file.data)
{
m_params.errorCode = ERR_NOFILE;
return -1;
}
tmp = reinterpret_cast<char *>(malloc(static_cast<size_t>(file.size + 1)));
if(!tmp)
{
m_params.errorCode = ERR_NO_MEMORY;
return false;
}
memcpy(tmp, file.data, static_cast<size_t>(file.size));
*(tmp + file.size) = '\0';//null terminate last line
valid = ini_parse_file(tmp, static_cast<size_t>(file.size));
#else
#ifdef _WIN32
//Convert UTF8 file path into UTF16 to support non-ASCII paths on Windows
std::wstring dest;
dest.resize(std::strlen(filename));
int newSize = MultiByteToWideChar(CP_UTF8,
0,
filename,
(int)dest.size(),
(wchar_t *)dest.c_str(),
(int)dest.size());
dest.resize(newSize);
FILE *cFile = _wfopen(dest.c_str(), L"rb");
#else
FILE *cFile = fopen(filename, "rb");
#endif
if(!cFile)
{
m_params.errorCode = ERR_NOFILE;
return false;
}
fseek(cFile, 0, SEEK_END);
ssize_t size = static_cast<ssize_t>(ftell(cFile));
if(size < 0)
{
m_params.errorCode = ERR_KEY_SYNTAX;
fclose(cFile);
return false;
}
fseek(cFile, 0, SEEK_SET);
tmp = reinterpret_cast<char *>(malloc(static_cast<size_t>(size + 1)));
if(!tmp)
{
fclose(cFile);
m_params.errorCode = ERR_NO_MEMORY;
return false;
}
if(fread(tmp, 1, static_cast<size_t>(size), cFile) != static_cast<size_t>(size))
valid = false;
fclose(cFile);
if(valid)
{
*(tmp + size) = '\0';//null terminate last line
try
{
valid = parseHelper(tmp, static_cast<size_t>(size));
}
catch(...)
{
valid = false;
m_params.errorCode = ERR_SECTION_SYNTAX;
}
}
#endif
free(tmp);
return valid;
}
bool IniProcessing::parseMemory(char *mem, size_t size)
{
bool valid = true;
char *tmp = nullptr;
tmp = reinterpret_cast<char *>(malloc(size + 1));
if(!tmp)
{
m_params.errorCode = ERR_NO_MEMORY;
return false;
}
memcpy(tmp, mem, static_cast<size_t>(size));
*(tmp + size) = '\0';//null terminate last line
valid = parseHelper(tmp, size);
free(tmp);
return valid;
}
IniProcessing::IniProcessing() :
m_params{"", false, -1, ERR_OK, false, params::IniSections(), nullptr, ""}
{}
IniProcessing::IniProcessing(const char *iniFileName, int) :
m_params{iniFileName, false, -1, ERR_OK, false, params::IniSections(), nullptr, ""}
{
open(iniFileName);
}
IniProcessing::IniProcessing(const std::string &iniFileName, int) :
m_params{iniFileName, false, -1, ERR_OK, false, params::IniSections(), nullptr, ""}
{
open(iniFileName);
}
#ifdef INI_PROCESSING_ALLOW_QT_TYPES
IniProcessing::IniProcessing(const QString &iniFileName, int) :
m_params{iniFileName.toStdString(), false, -1, ERR_OK, false, params::IniSections(), nullptr, ""}
{
open(m_params.filePath);
}
#endif
IniProcessing::IniProcessing(char *memory, size_t size):
m_params{"", false, -1, ERR_OK, false, params::IniSections(), nullptr, ""}
{
openMem(memory, size);
}
IniProcessing::IniProcessing(const IniProcessing &ip) :
m_params(ip.m_params)
{}
bool IniProcessing::open(const std::string &iniFileName)
{
std::setlocale(LC_NUMERIC, "C");
if(!iniFileName.empty())
{
close();
m_params.errorCode = ERR_OK;
m_params.filePath = iniFileName;
bool res = parseFile(m_params.filePath.c_str());
#ifdef INIDEBUG
if(res)
printf("\n==========WOOHOO!!!==============\n\n");
else
printf("\n==========OOOUCH!!!==============\n\n");
#endif
m_params.opened = res;
return res;
}
m_params.errorCode = ERR_NOFILE;
return false;
}
bool IniProcessing::openMem(char *memory, size_t size)
{
std::setlocale(LC_NUMERIC, "C");
if((memory != nullptr) && (size > 0))
{
close();
m_params.errorCode = ERR_OK;
m_params.filePath.clear();
bool res = parseMemory(memory, size);
m_params.opened = res;
return res;
}
m_params.errorCode = ERR_NOFILE;
return false;
}
void IniProcessing::close()
{
m_params.errorCode = ERR_OK;
m_params.iniData.clear();
m_params.opened = false;
m_params.lineWithError = -1;
}
IniProcessing::ErrCode IniProcessing::lastError()
{
return m_params.errorCode;
}
int IniProcessing::lineWithError()
{
return m_params.lineWithError;
}
bool IniProcessing::isOpened()
{
return m_params.opened;
}
bool IniProcessing::beginGroup(const std::string &groupName)
{
//Keep the group name. If not exist, will be created on value write
m_params.currentGroupName = groupName;
params::IniSections::iterator e = m_params.iniData.find(groupName);
if(e == m_params.iniData.end())
return false;
params::IniKeys &k = e->second;
m_params.currentGroup = &k;
return true;
}
bool IniProcessing::contains(const std::string &groupName)
{
if(!m_params.opened)
return false;
params::IniSections::iterator e = m_params.iniData.find(groupName);
return (e != m_params.iniData.end());
}
std::string IniProcessing::fileName()
{
return m_params.filePath;
}
std::string IniProcessing::group()
{
return m_params.currentGroupName;
}
std::vector<std::string> IniProcessing::childGroups()
{
std::vector<std::string> groups;
groups.reserve(m_params.iniData.size());
for(params::IniSections::iterator e = m_params.iniData.begin();
e != m_params.iniData.end();
e++)
{
groups.push_back(e->first);
}
return groups;
}
bool IniProcessing::hasKey(const std::string &keyName)
{
if(!m_params.opened)
return false;
if(!m_params.currentGroup)
return false;
params::IniKeys::iterator e = m_params.currentGroup->find(keyName);
return (e != m_params.currentGroup->end());
}
std::vector<std::string> IniProcessing::allKeys()
{
std::vector<std::string> keys;
if(!m_params.opened)
return keys;
if(!m_params.currentGroup)
return keys;
keys.reserve(m_params.currentGroup->size());
for(params::IniKeys::iterator it = m_params.currentGroup->begin();
it != m_params.currentGroup->end();
it++)
{
keys.push_back( it->first );
}
return keys;
}
void IniProcessing::endGroup()
{
m_params.currentGroup = nullptr;
m_params.currentGroupName.clear();
}
void IniProcessing::read(const char *key, bool &dest, bool defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
std::string &k = e->second;
size_t i = 0;
size_t ss = std::min(static_cast<size_t>(4ul), k.size());
char buff[4] = {0, 0, 0, 0};
const char *pbufi = k.c_str();
char *pbuff = buff;
for(; i < ss; i++)
(*pbuff++) = static_cast<char>(std::tolower(*pbufi++));
if(ss < 4)
{
if(ss == 0)
{
dest = false;
return;
}
if(ss == 1)
{
dest = (buff[0] == '1');
return;
}
bool isNum = true;
isNum = isNum && (std::isdigit(buff[i]) || (buff[i] == '-') || (buff[i] == '+'));
for(size_t j = 1; j < ss; j++)
isNum = (isNum && std::isdigit(buff[j]));
if(isNum)
{
long num = std::strtol(buff, 0, 0);
dest = num != 0l;
return;
}
else
{
dest = (std::memcmp(buff, "yes", 3) == 0) ||
(std::memcmp(buff, "on", 2) == 0);
return;
}
}
if(std::memcmp(buff, "true", 4) == 0)
{
dest = true;
return;
}
try
{
long num = std::strtol(buff, 0, 0);
dest = num != 0l;
return;
}
catch(...)
{
dest = false;
return;
}
}
void IniProcessing::read(const char *key, unsigned char &dest, unsigned char defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
std::string &k = e->second;
if(k.size() >= 1)
dest = static_cast<unsigned char>(k[0]);
else
dest = defVal;
}
void IniProcessing::read(const char *key, char &dest, char defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
std::string &k = e->second;
if(k.size() >= 1)
dest = k[0];
else
dest = defVal;
}
void IniProcessing::read(const char *key, unsigned short &dest, unsigned short defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = static_cast<unsigned short>(std::strtoul(e->second.c_str(), nullptr, 0));
}
void IniProcessing::read(const char *key, short &dest, short defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = static_cast<short>(std::strtol(e->second.c_str(), nullptr, 0));
}
void IniProcessing::read(const char *key, unsigned int &dest, unsigned int defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = static_cast<unsigned int>(std::strtoul(e->second.c_str(), nullptr, 0));
}
void IniProcessing::read(const char *key, int &dest, int defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = static_cast<int>(std::strtol(e->second.c_str(), nullptr, 0));
}
void IniProcessing::read(const char *key, unsigned long &dest, unsigned long defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtoul(e->second.c_str(), nullptr, 0);
}
void IniProcessing::read(const char *key, long &dest, long defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtol(e->second.c_str(), nullptr, 0);
}
void IniProcessing::read(const char *key, unsigned long long &dest, unsigned long long defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtoull(e->second.c_str(), nullptr, 0);
}
void IniProcessing::read(const char *key, long long &dest, long long defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtoll(e->second.c_str(), nullptr, 0);
}
void IniProcessing::read(const char *key, float &dest, float defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtof(e->second.c_str(), nullptr);
}
void IniProcessing::read(const char *key, double &dest, double defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtod(e->second.c_str(), nullptr);
}
void IniProcessing::read(const char *key, long double &dest, long double defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = std::strtold(e->second.c_str(), nullptr);
}
void IniProcessing::read(const char *key, std::string &dest, const std::string &defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = e->second;
}
#ifdef INI_PROCESSING_ALLOW_QT_TYPES
void IniProcessing::read(const char *key, QString &dest, const QString &defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
dest = QString::fromStdString(e->second);
}
#endif
template<class TList>
inline void StrToNumVectorHelper(const std::string &source, TList &dest, const typename TList::value_type &def)
{
typedef typename TList::value_type T;
dest.clear();
if(!source.empty())
{
std::stringstream ss(source);
std::string item;
while(std::getline(ss, item, ','))
{
std::remove(item.begin(), item.end(), ' ');
try
{
if(std::is_same<T, int>::value ||
std::is_same<T, long>::value ||
std::is_same<T, short>::value)
dest.push_back(static_cast<T>(std::strtol(item.c_str(), NULL, 0)));
else if(std::is_same<T, unsigned int>::value ||
std::is_same<T, unsigned long>::value ||
std::is_same<T, unsigned short>::value)
dest.push_back(static_cast<T>(std::strtoul(item.c_str(), NULL, 0)));
else if(std::is_same<T, float>::value)
dest.push_back(std::strtof(item.c_str(), NULL));
else
dest.push_back(std::strtod(item.c_str(), NULL));
}
catch(...)
{
dest.pop_back();
}
}
if(dest.empty())
dest.push_back(def);
}
else
dest.push_back(def);
}
template<class TList, typename T>
void readNumArrHelper(IniProcessing *self, const char *key, TList &dest, const TList &defVal)
{
bool ok = false;
IniProcessing::params::IniKeys::iterator e = self->readHelper(key, ok);
if(!ok)
{
dest = defVal;
return;
}
StrToNumVectorHelper(e->second, dest, static_cast<T>(0));
}
void IniProcessing::read(const char *key, std::vector<unsigned short> &dest, const std::vector<unsigned short> &defVal)
{
readNumArrHelper<std::vector<unsigned short>, unsigned short>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<short> &dest, const std::vector<short> &defVal)
{
readNumArrHelper<std::vector<short>, short>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<unsigned int> &dest, const std::vector<unsigned int> &defVal)
{
readNumArrHelper<std::vector<unsigned int>, unsigned int>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<int> &dest, const std::vector<int> &defVal)
{
readNumArrHelper<std::vector<int>, int>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<unsigned long> &dest, const std::vector<unsigned long> &defVal)
{
readNumArrHelper<std::vector<unsigned long>, unsigned long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<long> &dest, const std::vector<long> &defVal)
{
readNumArrHelper<std::vector<long>, long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<unsigned long long> &dest, const std::vector<unsigned long long> &defVal)
{
readNumArrHelper<std::vector<unsigned long long>, unsigned long long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<long long> &dest, const std::vector<long long> &defVal)
{
readNumArrHelper<std::vector<long long>, long long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<float> &dest, const std::vector<float> &defVal)
{
readNumArrHelper<std::vector<float>, float>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<double> &dest, const std::vector<double> &defVal)
{
readNumArrHelper<std::vector<double>, double>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, std::vector<long double> &dest, const std::vector<long double> &defVal)
{
readNumArrHelper<std::vector<long double>, long double>(this, key, dest, defVal);
}
#ifdef INI_PROCESSING_ALLOW_QT_TYPES
void IniProcessing::read(const char *key, QList<short> &dest, const QList<short> &defVal)
{
readNumArrHelper<QList<short>, short>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<unsigned short> &dest, const QList<unsigned short> &defVal)
{
readNumArrHelper<QList<unsigned short>, unsigned short>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<int> &dest, const QList<int> &defVal)
{
readNumArrHelper<QList<int>, int>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<unsigned int> &dest, const QList<unsigned int> &defVal)
{
readNumArrHelper<QList<unsigned int>, unsigned int>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<long> &dest, const QList<long> &defVal)
{
readNumArrHelper<QList<long>, long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<unsigned long> &dest, const QList<unsigned long> &defVal)
{
readNumArrHelper<QList<unsigned long>, unsigned long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<long long> &dest, const QList<long long> &defVal)
{
readNumArrHelper<QList<long long>, long long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<unsigned long long> &dest, const QList<unsigned long long> &defVal)
{
readNumArrHelper<QList<unsigned long long>, unsigned long long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<float> &dest, const QList<float> &defVal)
{
readNumArrHelper<QList<float>, float>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<double> &dest, const QList<double> &defVal)
{
readNumArrHelper<QList<double>, double>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QList<long double> &dest, const QList<long double> &defVal)
{
readNumArrHelper<QList<long double>, long double>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<short> &dest, const QVector<short> &defVal)
{
readNumArrHelper<QVector<short>, short>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<unsigned short> &dest, const QVector<unsigned short> &defVal)
{
readNumArrHelper<QVector<unsigned short>, unsigned short>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<int> &dest, const QVector<int> &defVal)
{
readNumArrHelper<QVector<int>, int>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<unsigned int> &dest, const QVector<unsigned int> &defVal)
{
readNumArrHelper<QVector<unsigned int>, unsigned int>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<long> &dest, const QVector<long> &defVal)
{
readNumArrHelper<QVector<long>, long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<unsigned long> &dest, const QVector<unsigned long> &defVal)
{
readNumArrHelper<QVector<unsigned long>, unsigned long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<long long> &dest, const QVector<long long> &defVal)
{
readNumArrHelper<QVector<long long>, long long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<unsigned long long> &dest, const QVector<unsigned long long> &defVal)
{
readNumArrHelper<QVector<unsigned long long>, unsigned long long>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<float> &dest, const QVector<float> &defVal)
{
readNumArrHelper<QVector<float>, float>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<double> &dest, const QVector<double> &defVal)
{
readNumArrHelper<QVector<double>, double>(this, key, dest, defVal);
}
void IniProcessing::read(const char *key, QVector<long double> &dest, const QVector<long double> &defVal)
{
readNumArrHelper<QVector<long double>, long double>(this, key, dest, defVal);
}
#endif
IniProcessingVariant IniProcessing::value(const char *key, const IniProcessingVariant &defVal)
{
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(!ok)
return defVal;
std::string &k = e->second;
return IniProcessingVariant(&k);
}
void IniProcessing::writeIniParam(const char *key, const std::string &value)
{
if(m_params.currentGroupName.empty())
return;
bool ok = false;
params::IniKeys::iterator e = readHelper(key, ok);
if(ok)
{
e->second = value;
}
else
{
if(!m_params.currentGroup)
{
m_params.iniData.insert({m_params.currentGroupName, params::IniKeys()});
m_params.currentGroup = &m_params.iniData[m_params.currentGroupName];
}
m_params.currentGroup->insert({std::string(key), value});
//Mark as opened
m_params.opened = true;
}
}
void IniProcessing::setValue(const char *key, unsigned short value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, short value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, unsigned int value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, int value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, unsigned long value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, long value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, unsigned long long value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, long long value)
{
writeIniParam(key, std::to_string(value));
}
void IniProcessing::setValue(const char *key, float value)
{
writeIniParam(key, IniProcessing::to_string_with_precision(value));
}
void IniProcessing::setValue(const char *key, double value)
{
writeIniParam(key, IniProcessing::to_string_with_precision(value));
}
void IniProcessing::setValue(const char *key, long double value)
{
writeIniParam(key, IniProcessing::to_string_with_precision(value));
}
void IniProcessing::setValue(const char *key, const char *value)
{
writeIniParam(key, value);
}
void IniProcessing::setValue(const char *key, const std::string &value)
{
writeIniParam(key, value);
}
#ifdef INI_PROCESSING_ALLOW_QT_TYPES
void IniProcessing::setValue(const char *key, const QString &value)
{
writeIniParam(key, value.toStdString());
}
#endif
static inline bool isFloatValue(const std::string &str)
{
enum State
{
ST_SIGN = 0,
ST_DOT,
ST_EXPONENT,
ST_EXPONENT_SIGN,
ST_TAIL
} st = ST_SIGN;
for(const char &c : str)
{
if(!isdigit(c))
{
switch(st)
{
case ST_SIGN:
if(c != '-')
return false;
st = ST_DOT;
continue;
case ST_DOT:
if(c != '.')
return false;
else
if((c == 'E') || (c == 'e'))
st = ST_EXPONENT_SIGN;
else
st = ST_EXPONENT;
continue;
case ST_EXPONENT:
if((c != 'E') && (c != 'e'))
return false;
st = ST_EXPONENT_SIGN;
continue;
case ST_EXPONENT_SIGN:
if(c != '-')
return false;
st = ST_TAIL;
continue;
case ST_TAIL:
return false;
}
return false;
}
else
{
if(st == ST_SIGN)
st = ST_DOT;
}
}
return true;
}
bool IniProcessing::writeIniFile()
{
#ifdef _WIN32
//Convert UTF8 file path into UTF16 to support non-ASCII paths on Windows
std::wstring dest;
dest.resize(m_params.filePath.size());
int newSize = MultiByteToWideChar(CP_UTF8,
0,
m_params.filePath.c_str(),
static_cast<int>(dest.size()),
&dest[0],
static_cast<int>(dest.size()));
dest.resize(newSize);
FILE *cFile = _wfopen(dest.c_str(), L"wb");
#else
FILE *cFile = fopen(m_params.filePath.c_str(), "wb");
#endif
if(!cFile)
return false;
for(params::IniSections::iterator group = m_params.iniData.begin();
group != m_params.iniData.end();
group++)
{
fprintf(cFile, "[%s]\n", group->first.c_str());
for(params::IniKeys::iterator key = group->second.begin();
key != group->second.end();
key++)
{
if(isFloatValue(key->second))
{
//Store as-is without quoting
fprintf(cFile, "%s = %s\n", key->first.c_str(), key->second.c_str());
}
else
{
//Set escape quotes and put the string with a quotes
std::string &s = key->second;
std::string escaped;
escaped.reserve(s.length() * 2);
for(char &c : s)
{
switch(c)
{
case '\n': escaped += "\\n"; break;
case '\r': escaped += "\\r"; break;
case '\t': escaped += "\\t"; break;
default:
if((c == '\\') || (c == '"'))
escaped.push_back('\\');
escaped.push_back(c);
}
}
fprintf(cFile, "%s = \"%s\"\n", key->first.c_str(), escaped.c_str());
}
}
fprintf(cFile, "\n");
fflush(cFile);
}
fclose(cFile);
return true;
}
| 26.663812 | 127 | 0.57035 | [
"vector"
] |
f8dce3d24300ea14f2f898ed933b046a3c691efd | 1,269 | hpp | C++ | include/edlib/Basis/BasisFullU1.hpp | cecri/ExactDiagonalization | a168ed2f60149b1c3e5bd9ae46a5d169aea76773 | [
"MIT"
] | null | null | null | include/edlib/Basis/BasisFullU1.hpp | cecri/ExactDiagonalization | a168ed2f60149b1c3e5bd9ae46a5d169aea76773 | [
"MIT"
] | null | null | null | include/edlib/Basis/BasisFullU1.hpp | cecri/ExactDiagonalization | a168ed2f60149b1c3e5bd9ae46a5d169aea76773 | [
"MIT"
] | null | null | null | #pragma once
#include "AbstractBasis.hpp"
#include "BasisJz.hpp"
#include <tbb/concurrent_vector.h>
#include <tbb/tbb.h>
namespace edlib
{
template<typename UINT> class BasisFullU1 final : public AbstractBasis<UINT>
{
private:
std::vector<UINT> basis_;
public:
explicit BasisFullU1(uint32_t N) : AbstractBasis<UINT>(N)
{
const uint32_t n = this->getN();
const uint32_t nup = n / 2;
BasisJz<UINT> basis(n, nup);
std::copy(basis.begin(), basis.end(), std::back_inserter(basis_));
}
[[nodiscard]] std::size_t getDim() const override { return basis_.size(); }
[[nodiscard]] UINT getNthRep(uint32_t n) const override { return basis_[n]; }
[[nodiscard]] auto hamiltonianCoeff(UINT bSigma, [[maybe_unused]] int aidx) const
-> std::pair<int, double> override
{
const auto biter = std::lower_bound(basis_.begin(), basis_.end(), bSigma);
if(biter == basis_.end() || biter->second != bSigma)
{
return {-1, 0.0};
}
int bidx = std::distance(basis_.begin(), biter);
return {bidx, 1.0};
}
std::vector<std::pair<UINT, double>> basisVec(uint32_t n) const override
{
return {{basis_[n], 1.0}};
}
};
} // namespace edlib
| 25.38 | 85 | 0.613869 | [
"vector"
] |
f8e1b0ec7ad10a3574b173f1e506f8875701342f | 18,607 | cc | C++ | content/browser/dom_storage/dom_storage_context_impl.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/browser/dom_storage/dom_storage_context_impl.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/browser/dom_storage/dom_storage_context_impl.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/dom_storage/dom_storage_context_impl.h"
#include <inttypes.h>
#include <stddef.h>
#include <stdlib.h>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/guid.h"
#include "base/location.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "base/time/time.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/process_memory_dump.h"
#include "content/browser/dom_storage/dom_storage_area.h"
#include "content/browser/dom_storage/dom_storage_database.h"
#include "content/browser/dom_storage/dom_storage_namespace.h"
#include "content/browser/dom_storage/dom_storage_task_runner.h"
#include "content/browser/dom_storage/session_storage_database.h"
#include "content/common/dom_storage/dom_storage_namespace_ids.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "content/public/browser/dom_storage_context.h"
#include "content/public/browser/local_storage_usage_info.h"
#include "content/public/browser/session_storage_usage_info.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace content {
namespace {
// Limits on the cache size and number of areas in memory, over which the areas
// are purged.
#if defined(OS_ANDROID)
const unsigned kMaxDomStorageAreaCount = 20;
const size_t kMaxDomStorageCacheSize = 2 * 1024 * 1024;
#else
const unsigned kMaxDomStorageAreaCount = 100;
const size_t kMaxDomStorageCacheSize = 20 * 1024 * 1024;
#endif
const int kSessionStoraceScavengingSeconds = 60;
// Aggregates statistics from all the namespaces.
DOMStorageNamespace::UsageStatistics GetTotalNamespaceStatistics(
const DOMStorageContextImpl::StorageNamespaceMap& namespace_map) {
DOMStorageNamespace::UsageStatistics total_stats = {0};
for (const auto& it : namespace_map) {
DOMStorageNamespace::UsageStatistics stats =
it.second->GetUsageStatistics();
total_stats.total_cache_size += stats.total_cache_size;
total_stats.total_area_count += stats.total_area_count;
total_stats.inactive_area_count += stats.inactive_area_count;
}
return total_stats;
}
} // namespace
DOMStorageContextImpl::DOMStorageContextImpl(
const base::FilePath& sessionstorage_directory,
storage::SpecialStoragePolicy* special_storage_policy,
scoped_refptr<DOMStorageTaskRunner> task_runner)
: sessionstorage_directory_(sessionstorage_directory),
task_runner_(std::move(task_runner)),
is_shutdown_(false),
force_keep_session_state_(false),
special_storage_policy_(special_storage_policy),
scavenging_started_(false),
is_low_end_device_(base::SysInfo::IsLowEndDevice()) {
// Tests may run without task runners.
if (task_runner_) {
// Registering dump provider is safe even outside the task runner.
base::trace_event::MemoryDumpManager::GetInstance()
->RegisterDumpProviderWithSequencedTaskRunner(
this, "DOMStorage", task_runner_->GetSequencedTaskRunner(
DOMStorageTaskRunner::PRIMARY_SEQUENCE),
base::trace_event::MemoryDumpProvider::Options());
}
}
DOMStorageContextImpl::~DOMStorageContextImpl() {
DCHECK(is_shutdown_);
if (session_storage_database_.get()) {
// SessionStorageDatabase shouldn't be deleted right away: deleting it will
// potentially involve waiting in leveldb::DBImpl::~DBImpl, and waiting
// shouldn't happen on this thread.
SessionStorageDatabase* to_release = session_storage_database_.get();
to_release->AddRef();
session_storage_database_ = nullptr;
task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::COMMIT_SEQUENCE,
base::BindOnce(&SessionStorageDatabase::Release,
base::Unretained(to_release)));
}
}
DOMStorageNamespace* DOMStorageContextImpl::GetStorageNamespace(
const std::string& namespace_id) {
if (is_shutdown_)
return nullptr;
StorageNamespaceMap::iterator found = namespaces_.find(namespace_id);
if (found == namespaces_.end())
return nullptr;
return found->second.get();
}
void DOMStorageContextImpl::GetSessionStorageUsage(
std::vector<SessionStorageUsageInfo>* infos) {
if (!session_storage_database_.get()) {
for (const auto& entry : namespaces_) {
std::vector<url::Origin> origins;
entry.second->GetOriginsWithAreas(&origins);
for (const url::Origin& origin : origins) {
SessionStorageUsageInfo info;
info.namespace_id = entry.second->namespace_id();
info.origin = origin.GetURL();
infos->push_back(info);
}
}
return;
}
std::map<std::string, std::vector<url::Origin>> namespaces_and_origins;
session_storage_database_->ReadNamespacesAndOrigins(
&namespaces_and_origins);
for (auto it = namespaces_and_origins.cbegin();
it != namespaces_and_origins.cend(); ++it) {
for (auto origin_it = it->second.cbegin(); origin_it != it->second.cend();
++origin_it) {
SessionStorageUsageInfo info;
info.namespace_id = it->first;
info.origin = origin_it->GetURL();
infos->push_back(info);
}
}
}
void DOMStorageContextImpl::DeleteSessionStorage(
const SessionStorageUsageInfo& usage_info) {
DCHECK(!is_shutdown_);
DOMStorageNamespace* dom_storage_namespace = nullptr;
auto it = namespaces_.find(usage_info.namespace_id);
if (it != namespaces_.end()) {
dom_storage_namespace = it->second.get();
} else {
CreateSessionNamespace(usage_info.namespace_id);
dom_storage_namespace = GetStorageNamespace(usage_info.namespace_id);
}
dom_storage_namespace->DeleteSessionStorageOrigin(
url::Origin::Create(usage_info.origin));
// Synthesize a 'cleared' event if the area is open so CachedAreas in
// renderers get emptied out too.
DOMStorageArea* area = dom_storage_namespace->GetOpenStorageArea(
url::Origin::Create(usage_info.origin));
if (area)
NotifyAreaCleared(area, usage_info.origin);
}
void DOMStorageContextImpl::Flush() {
for (auto& entry : namespaces_)
entry.second->Flush();
}
void DOMStorageContextImpl::Shutdown() {
if (task_runner_)
task_runner_->AssertIsRunningOnPrimarySequence();
is_shutdown_ = true;
StorageNamespaceMap::const_iterator it = namespaces_.begin();
for (; it != namespaces_.end(); ++it)
it->second->Shutdown();
base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
this);
if (!session_storage_database_.get())
return;
// Respect the content policy settings about what to
// keep and what to discard.
if (force_keep_session_state_)
return; // Keep everything.
bool has_session_only_origins =
special_storage_policy_.get() &&
special_storage_policy_->HasSessionOnlyOrigins();
if (has_session_only_origins) {
// We may have to delete something. We continue on the
// commit sequence after area shutdown tasks have cycled
// thru that sequence (and closed their database files).
bool success = task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::COMMIT_SEQUENCE,
base::BindOnce(&DOMStorageContextImpl::ClearSessionOnlyOrigins, this));
DCHECK(success);
}
}
void DOMStorageContextImpl::AddEventObserver(EventObserver* observer) {
event_observers_.AddObserver(observer);
}
void DOMStorageContextImpl::RemoveEventObserver(EventObserver* observer) {
event_observers_.RemoveObserver(observer);
}
void DOMStorageContextImpl::NotifyItemSet(
const DOMStorageArea* area,
const base::string16& key,
const base::string16& new_value,
const base::NullableString16& old_value,
const GURL& page_url) {
for (auto& observer : event_observers_)
observer.OnDOMStorageItemSet(area, key, new_value, old_value, page_url);
}
void DOMStorageContextImpl::NotifyItemRemoved(
const DOMStorageArea* area,
const base::string16& key,
const base::string16& old_value,
const GURL& page_url) {
for (auto& observer : event_observers_)
observer.OnDOMStorageItemRemoved(area, key, old_value, page_url);
}
void DOMStorageContextImpl::NotifyAreaCleared(
const DOMStorageArea* area,
const GURL& page_url) {
for (auto& observer : event_observers_)
observer.OnDOMStorageAreaCleared(area, page_url);
}
// Used to diagnose unknown namespace_ids given to the ipc message filter.
base::Optional<bad_message::BadMessageReason>
DOMStorageContextImpl::DiagnoseSessionNamespaceId(
const std::string& namespace_id) {
if (base::ContainsValue(recently_deleted_session_ids_, namespace_id))
return bad_message::DSH_DELETED_SESSION_ID;
return bad_message::DSH_NOT_ALLOCATED_SESSION_ID;
}
void DOMStorageContextImpl::CreateSessionNamespace(
const std::string& namespace_id) {
if (is_shutdown_)
return;
DCHECK(!namespace_id.empty());
// There are many browser tests that 'quit and restore' the browser but not
// the profile (and instead just reuse the old profile). This is unfortunate
// and doesn't actually test the 'restore' feature of session storage.
if (namespaces_.find(namespace_id) != namespaces_.end())
return;
namespaces_[namespace_id] = new DOMStorageNamespace(
namespace_id, session_storage_database_.get(), task_runner_.get());
}
void DOMStorageContextImpl::DeleteSessionNamespace(
const std::string& namespace_id,
bool should_persist_data) {
DCHECK(!namespace_id.empty());
StorageNamespaceMap::const_iterator it = namespaces_.find(namespace_id);
if (it == namespaces_.end())
return;
if (session_storage_database_.get()) {
if (!should_persist_data) {
task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::COMMIT_SEQUENCE,
base::BindOnce(
base::IgnoreResult(&SessionStorageDatabase::DeleteNamespace),
session_storage_database_, namespace_id));
} else {
// Ensure that the data gets committed before we shut down.
it->second->Shutdown();
if (!scavenging_started_) {
// Protect the persistent namespace ID from scavenging.
protected_session_ids_.insert(namespace_id);
}
}
}
namespaces_.erase(namespace_id);
recently_deleted_session_ids_.push_back(namespace_id);
if (recently_deleted_session_ids_.size() > 10)
recently_deleted_session_ids_.pop_front();
}
void DOMStorageContextImpl::CloneSessionNamespace(
const std::string& existing_id,
const std::string& new_id) {
if (is_shutdown_)
return;
DCHECK(!existing_id.empty());
DCHECK(!new_id.empty());
StorageNamespaceMap::iterator found = namespaces_.find(existing_id);
if (found != namespaces_.end()) {
namespaces_[new_id] = found->second->Clone(new_id);
return;
}
CreateSessionNamespace(new_id);
}
void DOMStorageContextImpl::ClearSessionOnlyOrigins() {
if (session_storage_database_.get()) {
std::vector<SessionStorageUsageInfo> infos;
GetSessionStorageUsage(&infos);
for (size_t i = 0; i < infos.size(); ++i) {
const url::Origin& origin = url::Origin::Create(infos[i].origin);
if (special_storage_policy_->IsStorageProtected(origin.GetURL()))
continue;
if (!special_storage_policy_->IsStorageSessionOnly(origin.GetURL()))
continue;
session_storage_database_->DeleteArea(infos[i].namespace_id, origin);
}
}
}
void DOMStorageContextImpl::SetSaveSessionStorageOnDisk() {
DCHECK(namespaces_.empty());
if (!sessionstorage_directory_.empty()) {
session_storage_database_ = new SessionStorageDatabase(
sessionstorage_directory_, task_runner_->GetSequencedTaskRunner(
DOMStorageTaskRunner::COMMIT_SEQUENCE));
}
}
void DOMStorageContextImpl::StartScavengingUnusedSessionStorage() {
if (session_storage_database_.get()) {
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&DOMStorageContextImpl::FindUnusedNamespaces, this),
base::TimeDelta::FromSeconds(kSessionStoraceScavengingSeconds));
}
}
void DOMStorageContextImpl::PurgeMemory(PurgeOption purge_option) {
if (is_shutdown_)
return;
DOMStorageNamespace::UsageStatistics initial_stats =
GetTotalNamespaceStatistics(namespaces_);
if (!initial_stats.total_area_count)
return;
// Track the total localStorage cache size.
UMA_HISTOGRAM_CUSTOM_COUNTS("LocalStorage.BrowserLocalStorageCacheSizeInKB",
initial_stats.total_cache_size / 1024, 1, 100000,
50);
const char* purge_reason = nullptr;
if (purge_option == PURGE_IF_NEEDED) {
// Purging is done based on the cache sizes without including the database
// size since it can be expensive trying to estimate the sqlite usage for
// all databases. For low end devices purge all inactive areas.
if (initial_stats.total_cache_size > kMaxDomStorageCacheSize)
purge_reason = "SizeLimitExceeded";
else if (initial_stats.total_area_count > kMaxDomStorageAreaCount)
purge_reason = "AreaCountLimitExceeded";
else if (is_low_end_device_)
purge_reason = "InactiveOnLowEndDevice";
if (!purge_reason)
return;
purge_option = PURGE_UNOPENED;
} else {
if (purge_option == PURGE_AGGRESSIVE)
purge_reason = "AggressivePurgeTriggered";
else
purge_reason = "ModeratePurgeTriggered";
}
// Return if no areas can be purged with the given option.
bool aggressively = purge_option == PURGE_AGGRESSIVE;
if (!aggressively && !initial_stats.inactive_area_count) {
return;
}
for (const auto& it : namespaces_)
it.second->PurgeMemory(aggressively);
// Track the size of cache purged.
size_t purged_size_kib =
(initial_stats.total_cache_size -
GetTotalNamespaceStatistics(namespaces_).total_cache_size) /
1024;
std::string full_histogram_name =
std::string("LocalStorage.BrowserLocalStorageCachePurgedInKB.") +
purge_reason;
base::HistogramBase* histogram = base::Histogram::FactoryGet(
full_histogram_name, 1, 100000, 50,
base::HistogramBase::kUmaTargetedHistogramFlag);
if (histogram)
histogram->Add(purged_size_kib);
UMA_HISTOGRAM_CUSTOM_COUNTS("LocalStorage.BrowserLocalStorageCachePurgedInKB",
purged_size_kib, 1, 100000, 50);
}
bool DOMStorageContextImpl::OnMemoryDump(
const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) {
if (session_storage_database_)
session_storage_database_->OnMemoryDump(pmd);
if (args.level_of_detail ==
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND) {
DOMStorageNamespace::UsageStatistics total_stats =
GetTotalNamespaceStatistics(namespaces_);
auto* mad = pmd->CreateAllocatorDump(base::StringPrintf(
"site_storage/session_storage/0x%" PRIXPTR "/cache_size",
reinterpret_cast<uintptr_t>(this)));
mad->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
base::trace_event::MemoryAllocatorDump::kUnitsBytes,
total_stats.total_cache_size);
mad->AddScalar("inactive_areas",
base::trace_event::MemoryAllocatorDump::kUnitsObjects,
total_stats.inactive_area_count);
mad->AddScalar("total_areas",
base::trace_event::MemoryAllocatorDump::kUnitsObjects,
total_stats.total_area_count);
return true;
}
for (const auto& it : namespaces_) {
it.second->OnMemoryDump(pmd);
}
return true;
}
void DOMStorageContextImpl::FindUnusedNamespaces() {
DCHECK(session_storage_database_.get());
if (scavenging_started_)
return;
scavenging_started_ = true;
std::set<std::string> namespace_ids_in_use;
for (StorageNamespaceMap::const_iterator it = namespaces_.begin();
it != namespaces_.end(); ++it)
namespace_ids_in_use.insert(it->second->namespace_id());
std::set<std::string> protected_session_ids;
protected_session_ids.swap(protected_session_ids_);
task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::COMMIT_SEQUENCE,
base::BindOnce(
&DOMStorageContextImpl::FindUnusedNamespacesInCommitSequence, this,
namespace_ids_in_use, protected_session_ids));
}
void DOMStorageContextImpl::FindUnusedNamespacesInCommitSequence(
const std::set<std::string>& namespace_ids_in_use,
const std::set<std::string>& protected_session_ids) {
DCHECK(session_storage_database_.get());
// Delete all namespaces which don't have an associated DOMStorageNamespace
// alive.
std::map<std::string, std::vector<url::Origin>> namespaces_and_origins;
session_storage_database_->ReadNamespacesAndOrigins(&namespaces_and_origins);
for (auto it = namespaces_and_origins.cbegin();
it != namespaces_and_origins.cend(); ++it) {
if (namespace_ids_in_use.find(it->first) == namespace_ids_in_use.end() &&
protected_session_ids.find(it->first) == protected_session_ids.end()) {
deletable_namespace_ids_.push_back(it->first);
}
}
if (!deletable_namespace_ids_.empty()) {
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&DOMStorageContextImpl::DeleteNextUnusedNamespace, this),
base::TimeDelta::FromSeconds(kSessionStoraceScavengingSeconds));
}
}
void DOMStorageContextImpl::DeleteNextUnusedNamespace() {
if (is_shutdown_)
return;
task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::COMMIT_SEQUENCE,
base::BindOnce(
&DOMStorageContextImpl::DeleteNextUnusedNamespaceInCommitSequence,
this));
}
void DOMStorageContextImpl::DeleteNextUnusedNamespaceInCommitSequence() {
if (deletable_namespace_ids_.empty())
return;
const std::string& persistent_id = deletable_namespace_ids_.back();
session_storage_database_->DeleteNamespace(persistent_id);
deletable_namespace_ids_.pop_back();
if (!deletable_namespace_ids_.empty()) {
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&DOMStorageContextImpl::DeleteNextUnusedNamespace, this),
base::TimeDelta::FromSeconds(kSessionStoraceScavengingSeconds));
}
}
} // namespace content
| 37.065737 | 80 | 0.734294 | [
"vector"
] |
25d4eceb326e686cceb2d8a9c46ff0a96d14cd13 | 12,844 | cc | C++ | src/operator/contrib/psroi_pooling.cc | wms2537/incubator-mxnet | b7d7e02705deb1dc4942bf39efc19f133e2181f7 | [
"Apache-2.0",
"MIT"
] | 1 | 2019-12-20T11:25:06.000Z | 2019-12-20T11:25:06.000Z | src/operator/contrib/psroi_pooling.cc | wms2537/incubator-mxnet | b7d7e02705deb1dc4942bf39efc19f133e2181f7 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/operator/contrib/psroi_pooling.cc | wms2537/incubator-mxnet | b7d7e02705deb1dc4942bf39efc19f133e2181f7 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2017 by Contributors
* Copyright (c) 2017 Microsoft
* Licensed under The Apache-2.0 License [see LICENSE for details]
* \file psroi_pooling.cc
* \brief psroi pooling operator
* \author Yi Li, Tairui Chen, Guodong Zhang, Haozhi Qi, Jifeng Dai
*/
#include "./psroi_pooling-inl.h"
#include <mshadow/base.h>
#include <mshadow/tensor.h>
#include <mshadow/packet-inl.h>
#include <mshadow/dot_engine-inl.h>
#include <cassert>
using std::ceil;
using std::floor;
using std::max;
using std::min;
namespace mshadow {
template <typename DType>
inline void PSROIPoolForwardCPU(const int count,
const DType* bottom_data,
const DType spatial_scale,
const int channels,
const int height,
const int width,
const int pooled_height,
const int pooled_width,
const DType* bottom_rois,
const int output_dim,
const int group_size,
DType* top_data) {
const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
#pragma omp parallel for num_threads(omp_threads)
for (int index = 0; index < count; index++) {
// The output is in order (n, ctop, ph, pw)
int pw = index % pooled_width;
int ph = (index / pooled_width) % pooled_height;
int ctop = (index / pooled_width / pooled_height) % output_dim;
int n = index / pooled_width / pooled_height / output_dim;
// [start, end) interval for spatial sampling
const DType* offset_bottom_rois = bottom_rois + n * 5;
int roi_batch_ind = offset_bottom_rois[0];
DType roi_start_w = static_cast<DType>(round(offset_bottom_rois[1])) * spatial_scale;
DType roi_start_h = static_cast<DType>(round(offset_bottom_rois[2])) * spatial_scale;
DType roi_end_w = static_cast<DType>(round(offset_bottom_rois[3]) + 1.) * spatial_scale;
DType roi_end_h = static_cast<DType>(round(offset_bottom_rois[4]) + 1.) * spatial_scale;
// Force too small ROIs to be 1x1
DType roi_width = max(roi_end_w - roi_start_w, static_cast<DType>(0.1)); // avoid 0
DType roi_height = max(roi_end_h - roi_start_h, static_cast<DType>(0.1));
// Compute w and h at bottom
DType bin_size_h = roi_height / static_cast<DType>(pooled_height);
DType bin_size_w = roi_width / static_cast<DType>(pooled_width);
int hstart = floor(static_cast<DType>(ph) * bin_size_h + roi_start_h);
int wstart = floor(static_cast<DType>(pw) * bin_size_w + roi_start_w);
int hend = ceil(static_cast<DType>(ph + 1) * bin_size_h + roi_start_h);
int wend = ceil(static_cast<DType>(pw + 1) * bin_size_w + roi_start_w);
// Add roi offsets and clip to input boundaries
hstart = min(max(hstart, 0), height);
hend = min(max(hend, 0), height);
wstart = min(max(wstart, 0), width);
wend = min(max(wend, 0), width);
bool is_empty = (hend <= hstart) || (wend <= wstart);
int gw = floor(static_cast<DType>(pw) * group_size / pooled_width);
int gh = floor(static_cast<DType>(ph) * group_size / pooled_height);
gw = min(max(gw, 0), group_size - 1);
gh = min(max(gh, 0), group_size - 1);
int c = (ctop * group_size + gh) * group_size + gw;
const DType* offset_bottom_data = bottom_data + (roi_batch_ind * channels + c) * height * width;
DType out_sum = 0;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
int bottom_index = h * width + w;
out_sum += offset_bottom_data[bottom_index];
}
}
DType bin_area = (hend - hstart) * (wend - wstart);
top_data[index] = is_empty ? (DType)0. : out_sum / bin_area;
}
}
template <typename DType>
inline void PSROIPoolForward(const Tensor<cpu, 4, DType>& out,
const Tensor<cpu, 4, DType>& data,
const Tensor<cpu, 2, DType>& bbox,
const float spatial_scale,
const int output_dim_,
const int group_size_) {
const DType* bottom_data = data.dptr_;
const DType* bottom_rois = bbox.dptr_;
DType* top_data = out.dptr_;
const int count = out.shape_.Size();
const int channels = data.size(1);
const int height = data.size(2);
const int width = data.size(3);
const int pooled_height = out.size(2);
const int pooled_width = out.size(3);
PSROIPoolForwardCPU<DType>(count,
bottom_data,
spatial_scale,
channels,
height,
width,
pooled_height,
pooled_width,
bottom_rois,
output_dim_,
group_size_,
top_data);
return;
}
template <typename DType>
inline void PSROIPoolBackwardAccCPU(const int count,
const DType* top_diff,
const int num_rois,
const DType spatial_scale,
const int channels,
const int height,
const int width,
const int pooled_height,
const int pooled_width,
const int group_size,
const int output_dim,
DType* bottom_diff,
const DType* bottom_rois) {
for (int index = 0; index < count; index++) {
// The output is in order (n, ctop, ph, pw)
int pw = index % pooled_width;
int ph = (index / pooled_width) % pooled_height;
int ctop = (index / pooled_width / pooled_height) % output_dim;
int n = index / pooled_width / pooled_height / output_dim;
// [start, end) interval for spatial sampling
const DType* offset_bottom_rois = bottom_rois + n * 5;
int roi_batch_ind = offset_bottom_rois[0];
DType roi_start_w = static_cast<DType>(round(offset_bottom_rois[1])) * spatial_scale;
DType roi_start_h = static_cast<DType>(round(offset_bottom_rois[2])) * spatial_scale;
DType roi_end_w = static_cast<DType>(round(offset_bottom_rois[3]) + 1.) * spatial_scale;
DType roi_end_h = static_cast<DType>(round(offset_bottom_rois[4]) + 1.) * spatial_scale;
// Force too small ROIs to be 1x1
DType roi_width = max(roi_end_w - roi_start_w, static_cast<DType>(0.1)); // avoid 0
DType roi_height = max(roi_end_h - roi_start_h, static_cast<DType>(0.1));
// Compute w and h at bottom
DType bin_size_h = roi_height / static_cast<DType>(pooled_height);
DType bin_size_w = roi_width / static_cast<DType>(pooled_width);
int hstart = floor(static_cast<DType>(ph) * bin_size_h + roi_start_h);
int wstart = floor(static_cast<DType>(pw) * bin_size_w + roi_start_w);
int hend = ceil(static_cast<DType>(ph + 1) * bin_size_h + roi_start_h);
int wend = ceil(static_cast<DType>(pw + 1) * bin_size_w + roi_start_w);
// Add roi offsets and clip to input boundaries
hstart = min(max(hstart, 0), height);
hend = min(max(hend, 0), height);
wstart = min(max(wstart, 0), width);
wend = min(max(wend, 0), width);
bool is_empty = (hend <= hstart) || (wend <= wstart);
// Compute c at bottom
int gw = floor(static_cast<DType>(pw) * group_size / pooled_width);
int gh = floor(static_cast<DType>(ph) * group_size / pooled_height);
gw = min(max(gw, 0), group_size - 1);
gh = min(max(gh, 0), group_size - 1);
int c = (ctop * group_size + gh) * group_size + gw;
DType* offset_bottom_diff = bottom_diff + (roi_batch_ind * channels + c) * height * width;
DType bin_area = (hend - hstart) * (wend - wstart);
DType diff_val = is_empty ? (DType)0. : top_diff[index] / bin_area;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
int bottom_index = h * width + w;
*(offset_bottom_diff + bottom_index) = *(offset_bottom_diff + bottom_index) + diff_val;
}
}
}
}
template <typename DType>
inline void PSROIPoolBackwardAcc(const Tensor<cpu, 4, DType>& in_grad,
const Tensor<cpu, 4, DType>& out_grad,
const Tensor<cpu, 2, DType>& bbox,
const float spatial_scale,
const int output_dim_,
const int group_size_) {
// LOG(INFO) << "PSROIPoolBackward";
const DType* top_diff = out_grad.dptr_;
const DType* bottom_rois = bbox.dptr_;
DType* bottom_diff = in_grad.dptr_;
const int count = out_grad.shape_.Size();
const int num_rois = bbox.size(0);
const int channels = in_grad.size(1);
const int height = in_grad.size(2);
const int width = in_grad.size(3);
const int pooled_height = out_grad.size(2);
const int pooled_width = out_grad.size(3);
PSROIPoolBackwardAccCPU<DType>(count,
top_diff,
num_rois,
spatial_scale,
channels,
height,
width,
pooled_height,
pooled_width,
group_size_,
output_dim_,
bottom_diff,
bottom_rois);
return;
}
} // namespace mshadow
namespace mxnet {
namespace op {
template <>
Operator* CreateOp<cpu>(PSROIPoolingParam param, int dtype) {
Operator* op = nullptr;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { op = new PSROIPoolingOp<cpu, DType>(param); });
return op;
}
Operator* PSROIPoolingProp::CreateOperatorEx(Context ctx,
mxnet::ShapeVector* in_shape,
std::vector<int>* in_type) const {
mxnet::ShapeVector out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, in_type->at(0));
}
DMLC_REGISTER_PARAMETER(PSROIPoolingParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_PSROIPooling, PSROIPoolingProp)
.describe(
"Performs region-of-interest pooling on inputs. Resize bounding box coordinates by "
"spatial_scale and crop input feature maps accordingly. The cropped feature maps are "
"pooled "
"by max pooling to a fixed size output indicated by pooled_size. batch_size will change to "
"the number of region bounding boxes after PSROIPooling")
.add_argument("data", "Symbol", "Input data to the pooling operator, a 4D Feature maps")
.add_argument(
"rois",
"Symbol",
"Bounding box coordinates, a 2D array of "
"[[batch_index, x1, y1, x2, y2]]. (x1, y1) and (x2, y2) are top left and down right "
"corners "
"of designated region of interest. batch_index indicates the index of corresponding image "
"in the input data")
.add_arguments(PSROIPoolingParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 45.066667 | 100 | 0.575055 | [
"vector"
] |
25e344e793695be399d82c8ccfeb843461163276 | 21,701 | cpp | C++ | ecmascript/compiler/stub_optimizer.cpp | openharmony-sig-ci/ark_js_runtime | 72fcff4c114fd8323c9a5d1a835efeac043e9a72 | [
"Apache-2.0"
] | null | null | null | ecmascript/compiler/stub_optimizer.cpp | openharmony-sig-ci/ark_js_runtime | 72fcff4c114fd8323c9a5d1a835efeac043e9a72 | [
"Apache-2.0"
] | null | null | null | ecmascript/compiler/stub_optimizer.cpp | openharmony-sig-ci/ark_js_runtime | 72fcff4c114fd8323c9a5d1a835efeac043e9a72 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:12:04.000Z | 2021-09-13T12:12:04.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ecmascript/compiler/stub_optimizer.h"
#include "ecmascript/compiler/llvm_ir_builder.h"
#include "ecmascript/js_object.h"
#include "ecmascript/tagged_hash_table-inl.h"
#include "libpandabase/macros.h"
namespace kungfu {
using StubOPtimizerLabelImplement = StubOptimizerLabel::StubOptimizerLabelImplement;
StubOptimizerLabel::StubOptimizerLabel(Environment *env)
{
impl_ = env->NewStubOptimizerLabel(env);
}
AddrShift StubVariable::AddPhiOperand(AddrShift val)
{
ASSERT(IsSelector(val));
StubOptimizerLabel label = env_->GetLabelFromSelector(val);
size_t idx = 0;
for (auto pred : label.GetPredecessors()) {
idx++;
val = AddOperandToSelector(val, idx, pred.ReadVariable(this));
}
return TryRemoveTrivialPhi(val);
}
AddrShift StubVariable::AddOperandToSelector(AddrShift val, size_t idx, AddrShift in)
{
env_->GetCircuit().NewIn(val, idx, in);
return val;
}
AddrShift StubVariable::TryRemoveTrivialPhi(AddrShift phiVal)
{
Gate *phi = env_->GetCircuit().LoadGatePtr(phiVal);
Gate *same = nullptr;
for (size_t i = 1; i < phi->GetNumIns(); ++i) {
In *phiIn = phi->GetIn(i);
Gate *op = (!phiIn->IsGateNull()) ? phiIn->GetGate() : nullptr;
if (op == same || op == phi) {
continue; // unique value or self-reference
}
if (same != nullptr) {
return phiVal; // the phi merges at least two values: not trivial
}
same = op;
}
if (same == nullptr) {
// the phi is unreachable or in the start block
same = env_->GetCircuit().LoadGatePtr(env_->GetCircuitBuilder().UndefineConstant());
}
// remove the trivial phi
// get all users of phi except self
std::vector<Out *> outs;
if (!phi->IsFirstOutNull()) {
Out *phiOut = phi->GetFirstOut();
while (!phiOut->IsNextOutNull()) {
if (phiOut->GetGate() != phi) {
// remove phi
outs.push_back(phiOut);
}
phiOut = phiOut->GetNextOut();
}
// save last phi out
if (phiOut->GetGate() != phi) {
outs.push_back(phiOut);
}
}
// reroute all outs of phi to same and remove phi
RerouteOuts(outs, same);
phi->DeleteGate();
// try to recursiveby remove all phi users, which might have vecome trivial
for (auto out : outs) {
if (IsSelector(out->GetGate())) {
auto out_addr_shift = env_->GetCircuit().SaveGatePtr(out->GetGate());
TryRemoveTrivialPhi(out_addr_shift);
}
}
return env_->GetCircuit().SaveGatePtr(same);
}
void StubVariable::RerouteOuts(const std::vector<Out *> &outs, Gate *newGate)
{
// reroute all outs to new node
for (auto out : outs) {
size_t idx = out->GetIndex();
out->GetGate()->ModifyIn(idx, newGate);
}
}
void StubOPtimizerLabelImplement::Seal()
{
for (auto &[variable, gate] : incompletePhis_) {
variable->AddPhiOperand(gate);
}
isSealed_ = true;
}
void StubOPtimizerLabelImplement::WriteVariable(StubVariable *var, AddrShift value)
{
valueMap_[var] = value;
}
AddrShift StubOPtimizerLabelImplement::ReadVariable(StubVariable *var)
{
if (valueMap_.find(var) != valueMap_.end()) {
return valueMap_.at(var);
}
return ReadVariableRecursive(var);
}
AddrShift StubOPtimizerLabelImplement::ReadVariableRecursive(StubVariable *var)
{
AddrShift val;
OpCode opcode = CircuitBuilder::GetSelectOpCodeFromMachineType(var->Type());
if (!IsSealed()) {
// only loopheader gate will be not sealed
int valueCounts = static_cast<int>(this->predecessors.size()) + 1;
val = env_->GetCircuitBuilder().NewSelectorGate(opcode, predeControl_, valueCounts);
env_->AddSelectorToLabel(val, StubOptimizerLabel(this));
incompletePhis_[var] = val;
} else if (predecessors.size() == 1) {
val = predecessors[0]->ReadVariable(var);
} else {
val = env_->GetCircuitBuilder().NewSelectorGate(opcode, predeControl_, this->predecessors.size());
env_->AddSelectorToLabel(val, StubOptimizerLabel(this));
WriteVariable(var, val);
val = var->AddPhiOperand(val);
}
WriteVariable(var, val);
return val;
}
void StubOPtimizerLabelImplement::Bind()
{
ASSERT(!predecessors.empty());
if (IsNeedSeal()) {
Seal();
MergeAllControl();
}
}
void StubOPtimizerLabelImplement::MergeAllControl()
{
if (predecessors.size() < 2) { // 2 : Loop Head only support two predecessors
return;
}
if (IsLoopHead()) {
ASSERT(predecessors.size() == 2); // 2 : Loop Head only support two predecessors
ASSERT(otherPredeControls_.size() == 1);
env_->GetCircuit().NewIn(predeControl_, 1, otherPredeControls_[0]);
return;
}
// merge all control of predecessors
std::vector<AddrShift> inGates(predecessors.size());
size_t i = 0;
ASSERT(predeControl_ != -1);
ASSERT((otherPredeControls_.size() + 1) == predecessors.size());
inGates[i++] = predeControl_;
for (auto in : otherPredeControls_) {
inGates[i++] = in;
}
AddrShift merge = env_->GetCircuitBuilder().NewMerge(inGates.data(), inGates.size());
predeControl_ = merge;
control_ = merge;
}
void StubOPtimizerLabelImplement::AppendPredecessor(StubOptimizerLabelImplement *predecessor)
{
if (predecessor != nullptr) {
predecessors.push_back(predecessor);
}
}
bool StubOPtimizerLabelImplement::IsNeedSeal() const
{
auto control = env_->GetCircuit().LoadGatePtr(predeControl_);
auto numsInList = control->GetOpCode().GetOpCodeNumInsArray(control->GetBitField());
return predecessors.size() >= numsInList[0];
}
bool StubOPtimizerLabelImplement::IsLoopHead() const
{
return env_->GetCircuit().IsLoopHead(predeControl_);
}
Environment::Environment(const char *name, size_t arguments)
: builder_(&circuit_), arguments_(arguments), method_name_(name)
{
for (size_t i = 0; i < arguments; i++) {
arguments_[i] = builder_.NewArguments(i);
}
entry_ = StubOptimizerLabel(NewStubOptimizerLabel(this, Circuit::GetCircuitRoot(OpCode(OpCode::STATE_ENTRY))));
currentLabel_ = &entry_;
currentLabel_->Seal();
}
Environment::Environment(Environment const &env)
: circuit_(env.circuit_), builder_(&circuit_), arguments_(env.arguments_), method_name_(env.method_name_)
{
entry_ = StubOptimizerLabel(NewStubOptimizerLabel(this, Circuit::GetCircuitRoot(OpCode(OpCode::STATE_ENTRY))));
currentLabel_ = &entry_;
currentLabel_->Seal();
}
Environment &Environment::operator=(const Environment &env)
{
if (&env != this) {
this->circuit_ = env.circuit_;
this->arguments_ = env.arguments_;
this->method_name_ = env.method_name_;
entry_ = StubOptimizerLabel(NewStubOptimizerLabel(this, Circuit::GetCircuitRoot(OpCode(OpCode::STATE_ENTRY))));
currentLabel_ = &entry_;
currentLabel_->Seal();
}
return *this;
}
Environment::~Environment()
{
for (auto label : rawlabels_) {
delete label;
}
}
void StubOptimizer::Jump(Label *label)
{
ASSERT(label);
auto currentLabel = env_->GetCurrentLabel();
auto currentControl = currentLabel->GetControl();
auto jump = env_->GetCircuitBuilder().Goto(currentControl);
currentLabel->SetControl(jump);
label->AppendPredecessor(currentLabel);
label->MergeControl(currentLabel->GetControl());
env_->SetCurrentLabel(nullptr);
}
void StubOptimizer::Branch(AddrShift condition, Label *trueLabel, Label *falseLabel)
{
auto currentLabel = env_->GetCurrentLabel();
auto currentControl = currentLabel->GetControl();
AddrShift ifBranch = env_->GetCircuitBuilder().Branch(currentControl, condition);
currentLabel->SetControl(ifBranch);
AddrShift ifTrue = env_->GetCircuitBuilder().NewIfTrue(ifBranch);
trueLabel->AppendPredecessor(env_->GetCurrentLabel());
trueLabel->MergeControl(ifTrue);
AddrShift ifFalse = env_->GetCircuitBuilder().NewIfFalse(ifBranch);
falseLabel->AppendPredecessor(env_->GetCurrentLabel());
falseLabel->MergeControl(ifFalse);
env_->SetCurrentLabel(nullptr);
}
void StubOptimizer::Switch(AddrShift index, Label *defaultLabel, int32_t *keysValue, Label *keysLabel, int numberOfKeys)
{
auto currentLabel = env_->GetCurrentLabel();
auto currentControl = currentLabel->GetControl();
AddrShift switchBranch = env_->GetCircuitBuilder().SwitchBranch(currentControl, index, numberOfKeys);
currentLabel->SetControl(switchBranch);
for (int i = 0; i < numberOfKeys; i++) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
AddrShift switchCase = env_->GetCircuitBuilder().NewSwitchCase(switchBranch, keysValue[i]);
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
keysLabel[i].AppendPredecessor(currentLabel);
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
keysLabel[i].MergeControl(switchCase);
}
AddrShift defaultCase = env_->GetCircuitBuilder().NewDefaultCase(switchBranch);
defaultLabel->AppendPredecessor(currentLabel);
defaultLabel->MergeControl(defaultCase);
env_->SetCurrentLabel(nullptr);
}
void StubOptimizer::LoopBegin(Label *loopHead)
{
ASSERT(loopHead);
auto loopControl = env_->GetCircuitBuilder().LoopBegin(loopHead->GetControl());
loopHead->SetControl(loopControl);
loopHead->SetPreControl(loopControl);
loopHead->Bind();
env_->SetCurrentLabel(loopHead);
}
void StubOptimizer::LoopEnd(Label *loopHead)
{
ASSERT(loopHead);
auto currentLabel = env_->GetCurrentLabel();
auto currentControl = currentLabel->GetControl();
auto loopend = env_->GetCircuitBuilder().LoopEnd(currentControl);
currentLabel->SetControl(loopend);
loopHead->AppendPredecessor(currentLabel);
loopHead->MergeControl(loopend);
loopHead->Seal();
loopHead->MergeAllControl();
env_->SetCurrentLabel(nullptr);
}
AddrShift StubOptimizer::FixLoadType(AddrShift x)
{
if (PtrValueCode() == ValueCode::INT64) {
return SExtInt32ToInt64(x);
}
if (PtrValueCode() == ValueCode::INT32) {
return TruncInt64ToInt32(x);
}
UNREACHABLE();
}
AddrShift StubOptimizer::LoadFromObject(MachineType type, AddrShift object, AddrShift offset)
{
AddrShift elementsOffset = GetInteger32Constant(panda::ecmascript::JSObject::ELEMENTS_OFFSET);
if (PtrValueCode() == ValueCode::INT64) {
elementsOffset = SExtInt32ToInt64(elementsOffset);
}
// load elements in object
AddrShift elements = Load(MachineType::UINT64_TYPE, object, elementsOffset);
// load index in tagged array
AddrShift dataOffset =
Int32Add(GetInteger32Constant(panda::coretypes::Array::GetDataOffset()),
Int32Mul(offset, GetInteger32Constant(panda::ecmascript::JSTaggedValue::TaggedTypeSize())));
if (PtrValueCode() == ValueCode::INT64) {
dataOffset = SExtInt32ToInt64(dataOffset);
}
return Load(type, ChangeInt64ToPointer(elements), dataOffset);
}
AddrShift StubOptimizer::FindElementFromNumberDictionary(AddrShift thread, AddrShift elements, AddrShift key,
Label *next)
{
auto env = GetEnvironment();
DEFVARIABLE(result, INT32_TYPE, GetInteger32Constant(-1));
AddrShift capcityoffset =
PtrMul(GetPtrConstant(panda::ecmascript::JSTaggedValue::TaggedTypeSize()),
GetPtrConstant(panda::ecmascript::TaggedHashTable<panda::ecmascript::NumberDictionary>::SIZE_INDEX));
AddrShift dataoffset = GetPtrConstant(panda::coretypes::Array::GetDataOffset());
AddrShift capacity = TaggedCastToInt32(Load(TAGGED_TYPE, elements, PtrAdd(dataoffset, capcityoffset)));
DEFVARIABLE(count, INT32_TYPE, GetInteger32Constant(1));
AddrShift pKey = Alloca(static_cast<int>(MachineRep::K_WORD32));
AddrShift keyStore = Store(INT32_TYPE, pKey, GetPtrConstant(0), TaggedCastToInt32(key));
StubInterfaceDescriptor *getHash32Descriptor = GET_STUBDESCRIPTOR(GetHash32);
AddrShift len = GetInteger32Constant(sizeof(int) / sizeof(uint8_t));
AddrShift hash =
CallRuntime(getHash32Descriptor, thread, GetWord64Constant(FAST_STUB_ID(GetHash32)), keyStore, {pKey, len});
DEFVARIABLE(entry, INT32_TYPE, Word32And(hash, Int32Sub(capacity, GetInteger32Constant(1))));
Label loopHead(env);
Label loopEnd(env);
Label afterLoop(env);
Jump(&loopHead);
LoopBegin(&loopHead);
Label afterGetKey(env);
AddrShift element = GetKeyFromNumberDictionary(elements, *entry, &afterGetKey);
Label isHole(env);
Label notHole(env);
Branch(TaggedIsHole(element), &isHole, ¬Hole);
Bind(&isHole);
Jump(&loopEnd);
Bind(¬Hole);
Label isUndefined(env);
Label notUndefined(env);
Branch(TaggedIsUndefined(element), &isUndefined, ¬Undefined);
Bind(&isUndefined);
result = GetInteger32Constant(-1);
Jump(next);
Bind(¬Undefined);
Label afterIsMatch(env);
Label isMatch(env);
Label notMatch(env);
Branch(IsMatchInNumberDictionary(key, element, &afterIsMatch), &isMatch, ¬Match);
Bind(&isMatch);
result = *entry;
Jump(next);
Bind(¬Match);
Jump(&loopEnd);
Bind(&loopEnd);
entry = Word32And(Int32Add(*entry, *count), Int32Sub(capacity, GetInteger32Constant(1)));
count = Int32Add(*count, GetInteger32Constant(1));
LoopEnd(&loopHead);
Bind(next);
return *result;
}
AddrShift StubOptimizer::IsMatchInNumberDictionary(AddrShift key, AddrShift other, Label *next)
{
auto env = GetEnvironment();
DEFVARIABLE(result, BOOL_TYPE, FalseConstant());
Label isHole(env);
Label notHole(env);
Label isUndefined(env);
Label notUndefined(env);
Branch(TaggedIsHole(key), &isHole, ¬Hole);
Bind(&isHole);
Jump(next);
Bind(¬Hole);
Branch(TaggedIsUndefined(key), &isUndefined, ¬Undefined);
Bind(&isUndefined);
Jump(next);
Bind(¬Undefined);
Label keyIsInt(env);
Label keyNotInt(env);
Label otherIsInt(env);
Label otherNotInt(env);
Branch(TaggedIsInt(key), &keyIsInt, &keyNotInt);
Bind(&keyIsInt);
Branch(TaggedIsInt(other), &otherIsInt, &otherNotInt);
Bind(&otherIsInt);
result = Word32Equal(TaggedCastToInt32(key), TaggedCastToInt32(other));
Jump(next);
Bind(&otherNotInt);
Jump(next);
Bind(&keyNotInt);
Jump(next);
Bind(next);
return *result;
}
AddrShift StubOptimizer::GetKeyFromNumberDictionary(AddrShift elements, AddrShift entry, Label *next)
{
auto env = GetEnvironment();
DEFVARIABLE(result, TAGGED_TYPE, GetUndefinedConstant());
Label ltZero(env);
Label notLtZero(env);
Label gtLength(env);
Label notGtLength(env);
AddrShift dictionaryLength = Load(INT32_TYPE, elements, GetPtrConstant(panda::coretypes::Array::GetLengthOffset()));
AddrShift arrayIndex =
Int32Add(GetInteger32Constant(panda::ecmascript::NumberDictionary::TABLE_HEADER_SIZE),
Int32Mul(entry, GetInteger32Constant(panda::ecmascript::NumberDictionary::ENTRY_SIZE)));
Branch(Int32LessThan(arrayIndex, GetInteger32Constant(0)), <Zero, ¬LtZero);
Bind(<Zero);
Jump(next);
Bind(¬LtZero);
Branch(Int32GreaterThan(arrayIndex, dictionaryLength), >Length, ¬GtLength);
Bind(>Length);
Jump(next);
Bind(¬GtLength);
result = GetValueFromTaggedArray(elements, arrayIndex);
Jump(next);
Bind(next);
return *result;
}
void StubOptimizer::ThrowTypeAndReturn(AddrShift thread, int messageId, AddrShift val)
{
StubInterfaceDescriptor *throwTypeError = GET_STUBDESCRIPTOR(ThrowTypeError);
AddrShift taggedId = IntBuildTagged(GetInteger32Constant(messageId));
CallStub(throwTypeError, GetWord64Constant(FAST_STUB_ID(ThrowTypeError)), {thread, taggedId});
Return(val);
}
AddrShift StubOptimizer::TaggedToRepresentation(AddrShift value, Label *next)
{
auto env = GetEnvironment();
DEFVARIABLE(resultRep, INT64_TYPE,
GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::OBJECT)));
Label isInt(env);
Label notInt(env);
Branch(TaggedIsInt(value), &isInt, ¬Int);
Bind(&isInt);
{
resultRep = GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::INT));
Jump(next);
}
Bind(¬Int);
{
Label isDouble(env);
Label notDouble(env);
Branch(TaggedIsDouble(value), &isDouble, ¬Double);
Bind(&isDouble);
{
resultRep = GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::DOUBLE));
Jump(next);
}
Bind(¬Double);
{
resultRep = GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::OBJECT));
Jump(next);
}
}
Bind(next);
return *resultRep;
}
AddrShift StubOptimizer::UpdateRepresention(AddrShift oldRep, AddrShift value, Label *next)
{
auto env = GetEnvironment();
DEFVARIABLE(resultRep, INT64_TYPE, oldRep);
Label isMixedRep(env);
Label notMiexedRep(env);
Branch(Word64Equal(oldRep, GetWord64Constant(static_cast<int64_t>(panda::ecmascript::Representation::MIXED))),
&isMixedRep, ¬MiexedRep);
Bind(&isMixedRep);
Jump(next);
Bind(¬MiexedRep);
{
Label newRepLabel(env);
AddrShift newRep = TaggedToRepresentation(value, &newRepLabel);
Label isNoneRep(env);
Label notNoneRep(env);
Branch(Word64Equal(oldRep, GetWord64Constant(static_cast<int64_t>(panda::ecmascript::Representation::NONE))),
&isNoneRep, ¬NoneRep);
Bind(&isNoneRep);
{
resultRep = newRep;
Jump(next);
}
Bind(¬NoneRep);
{
Label isEqaulNewRep(env);
Label notEqaualNewRep(env);
Branch(Word64NotEqual(oldRep, newRep), &isEqaulNewRep, ¬EqaualNewRep);
Bind(&isEqaulNewRep);
{
resultRep = newRep;
Jump(next);
}
Bind(¬EqaualNewRep);
{
Label defaultLabel(env);
Label intLabel(env);
Label doubleLabel(env);
Label numberLabel(env);
Label objectLabel(env);
// 4 : 4 means that there are 4 args in total.
std::array<Label, 4> repCaseLabels = {
intLabel,
doubleLabel,
numberLabel,
objectLabel,
};
// 4 : 4 means that there are 4 args in total.
std::array<int32_t, 4> keyValues = {
static_cast<int32_t>(panda::ecmascript::Representation::INT),
static_cast<int32_t>(panda::ecmascript::Representation::DOUBLE),
static_cast<int32_t>(panda::ecmascript::Representation::NUMBER),
static_cast<int32_t>(panda::ecmascript::Representation::OBJECT),
};
// 4 : 4 means that there are 4 cases in total.
Switch(oldRep, &defaultLabel, keyValues.data(), repCaseLabels.data(), 4);
Bind(&intLabel);
Jump(&numberLabel);
Bind(&doubleLabel);
Jump(&numberLabel);
Bind(&numberLabel);
{
Label isObjectNewRep(env);
Label notObjectNewRep(env);
Branch(Word64NotEqual(newRep, GetWord64Constant(
static_cast<int32_t>(panda::ecmascript::Representation::OBJECT))),
¬ObjectNewRep, &isObjectNewRep);
Bind(¬ObjectNewRep);
{
resultRep = GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::NUMBER));
Jump(next);
}
Bind(&isObjectNewRep);
{
resultRep = GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::MIXED));
Jump(next);
}
}
Bind(&objectLabel);
{
resultRep = GetWord64Constant(static_cast<int32_t>(panda::ecmascript::Representation::MIXED));
Jump(next);
}
Bind(&defaultLabel);
Jump(next);
}
}
}
Bind(next);
return *resultRep;
}
void StubOptimizer::UpdateAndStoreRepresention(AddrShift hclass, AddrShift value, Label *next)
{
AddrShift newRep = UpdateRepresention(GetElementRepresentation(hclass), value, next);
SetElementRepresentation(hclass, newRep);
}
} // namespace kungfu | 35.751236 | 120 | 0.657066 | [
"object",
"vector"
] |
25e7f1072b5898fa390d92f8899af8bf65b8afa7 | 4,622 | cpp | C++ | src/base/producer.cpp | lawarner/aft | fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603 | [
"Apache-2.0"
] | null | null | null | src/base/producer.cpp | lawarner/aft | fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603 | [
"Apache-2.0"
] | null | null | null | src/base/producer.cpp | lawarner/aft | fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Andy Warner
*
* 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 <algorithm>
#include "blob.h"
#include "consumer.h"
#include "producer.h"
#include "result.h"
#include "tobject.h"
using namespace aft::base;
BaseProducer::BaseProducer(WriterContract* writerDelegate)
: writerDelegate_(writerDelegate)
{
}
BaseProducer::~BaseProducer()
{
}
Result BaseProducer::read(TObject& object)
{
if (writerDelegate_ && writerDelegate_->hasData() == ProductType::TOBJECT)
{
return writerDelegate_->getData(object);
}
return false;
}
Result BaseProducer::read(Result& result)
{
if (writerDelegate_ && writerDelegate_->hasData() == ProductType::RESULT)
{
return writerDelegate_->getData(result);
}
return false;
}
Result BaseProducer::read(Blob& blob)
{
if (writerDelegate_ && writerDelegate_->hasData() == ProductType::BLOB)
{
return writerDelegate_->getData(blob);
}
return false;
}
bool BaseProducer::hasData()
{
if (writerDelegate_)
{
return writerDelegate_->hasData() != ProductType::NONE;
}
return false;
}
bool BaseProducer::hasObject(ProductType productType)
{
if (writerDelegate_)
{
return writerDelegate_->hasData() == productType;
}
if (productType == ProductType::NONE) return true;
return false;
}
bool BaseProducer::registerDataCallback(const ReaderContract* reader)
{
if (!reader) return false;
std::vector<ReaderContract*>::iterator it
= std::find(readers_.begin(), readers_.end(), reader);
if (it != readers_.end())
{
return false; // reader already in callback list
}
readers_.push_back(const_cast<ReaderContract*>(reader));
return true;
}
bool BaseProducer::unregisterDataCallback(const ReaderContract* reader)
{
if (!reader) return false;
std::vector<ReaderContract*>::iterator it
= std::find(readers_.begin(), readers_.end(), reader);
if (it == readers_.end())
{
return false; // reader not in callback list
}
readers_.erase(it);
return true;
}
void BaseProducer::flowData()
{
if (!writerDelegate_ || writerDelegate_->hasData() == ProductType::NONE)
{
return;
}
ProductType productType;
do
{
productType = writerDelegate_->hasData();
switch (productType)
{
case ProductType::TOBJECT:
{
TObject tobject;
if (writerDelegate_->getData(tobject))
{
// iterate thru readers until one reads the object
std::vector<ReaderContract*>::iterator it;
for (it = readers_.begin(); it != readers_.end(); ++it)
{
if ((*it)->pushData(tobject))
{
break;
}
}
}
}
break;
case ProductType::RESULT:
{
Result result;
if (writerDelegate_->getData(result))
{
// iterate thru readers until one reads the object
std::vector<ReaderContract*>::iterator it;
for (it = readers_.begin(); it != readers_.end(); ++it)
{
if ((*it)->pushData(result))
{
break;
}
}
}
}
break;
case ProductType::BLOB:
{
Blob blob("");
if (writerDelegate_->getData(blob)) {
// iterate thru readers until one reads the object
std::vector<ReaderContract*>::iterator it;
for (it = readers_.begin(); it != readers_.end(); ++it)
{
if ((*it)->pushData(blob))
{
break;
}
}
}
}
break;
case ProductType::NONE:
break;
}
} while (productType != ProductType::NONE);
}
| 25.535912 | 78 | 0.559065 | [
"object",
"vector"
] |
25f28d12d131e41d1d38ebd2591bc53540bc66c7 | 572 | cpp | C++ | tc 160+/GooseTattarrattatDiv2.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/GooseTattarrattatDiv2.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/GooseTattarrattatDiv2.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <numeric>
#include <functional>
using namespace std;
class GooseTattarrattatDiv2 {
public:
int getmin(string S) {
vector<int> a;
for (int c='a'; c<='z'; ++c) {
a.push_back(count(S.begin(), S.end(), c));
}
sort(a.begin(), a.end(), greater<int>());
return accumulate(a.begin()+1, a.end(), 0);
}
};
| 20.428571 | 54 | 0.603147 | [
"vector"
] |
25f9e341f513c3385b4ce8376b810cf983fe2ccc | 7,638 | cpp | C++ | test/unit/range/view/view_get_test.cpp | giesselmann/seqan3 | 3a26b42b7066ac424b6e604115fe516607c308c0 | [
"BSD-3-Clause"
] | null | null | null | test/unit/range/view/view_get_test.cpp | giesselmann/seqan3 | 3a26b42b7066ac424b6e604115fe516607c308c0 | [
"BSD-3-Clause"
] | null | null | null | test/unit/range/view/view_get_test.cpp | giesselmann/seqan3 | 3a26b42b7066ac424b6e604115fe516607c308c0 | [
"BSD-3-Clause"
] | null | null | null | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
//
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// Copyright (c) 2016-2018, Knut Reinert & MPI Molekulare Genetik
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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 <iostream>
#include <gtest/gtest.h>
#include <seqan3/std/view/reverse.hpp>
#include <seqan3/range/concept.hpp>
#include <seqan3/range/view/get.hpp>
#include <seqan3/range/view/to_char.hpp>
#include <seqan3/range/view/complement.hpp>
#include <seqan3/alphabet/quality/aliases.hpp>
#include <seqan3/alphabet/mask/masked.hpp>
using namespace seqan3;
using namespace seqan3::literal;
TEST(view_get, basic)
{
std::vector<dna4q> qv{{dna4::A, phred42{0}}, {dna4::C, phred42{1}}, {dna4::G, phred42{2}}, {dna4::T, phred42{3}}};
std::vector<dna4> cmp0{dna4::A, dna4::C, dna4::G, dna4::T};
std::vector<phred42> cmp1{phred42{0}, phred42{1}, phred42{2}, phred42{3}};
//functor
dna4_vector functor0 = view::get<0>(qv);
std::vector<phred42> functor1 = view::get<1>(qv);
EXPECT_EQ(cmp0, functor0);
EXPECT_EQ(cmp1, functor1);
// pipe notation
dna4_vector pipe0 = qv | view::get<0>;
std::vector<phred42> pipe1 = qv | view::get<1>;
EXPECT_EQ(cmp0, pipe0);
EXPECT_EQ(cmp1, pipe1);
// combinability
dna4_vector cmp2{"TGCA"_dna4};
dna4_vector comp = qv | view::get<0> | view::complement;
EXPECT_EQ(cmp2, comp);
std::string cmp3{"TGCA"};
std::string to_char_test = comp | view::to_char;
EXPECT_EQ(cmp3, to_char_test);
// reference return check
functor1[0] = phred42{4};
std::vector<phred42> cmp4{phred42{4}, phred42{1}, phred42{2}, phred42{3}};
EXPECT_EQ(cmp4, functor1);
}
TEST(view_get, advanced)
{
std::vector<qualified<masked<dna4>, phred42>> t{{{dna4::A, mask::MASKED}, phred42{0}},
{{dna4::C, mask::UNMASKED}, phred42{1}},
{{dna4::G, mask::MASKED}, phred42{2}},
{{dna4::T, mask::UNMASKED}, phred42{3}}};
// functor notation
std::vector<masked<dna4>> cmp0{{dna4::A, mask::MASKED}, {dna4::C, mask::UNMASKED},
{dna4::G, mask::MASKED}, {dna4::T, mask::UNMASKED}};
std::vector<masked<dna4>> functor0 = view::get<0>(t);
EXPECT_EQ(cmp0, functor0);
std::vector<phred42> cmp1{phred42{0}, phred42{1}, phred42{2}, phred42{3}};
std::vector<phred42> functor1 = view::get<1>(t);
EXPECT_EQ(cmp1, functor1);
std::vector<dna4> cmp00{dna4::A, dna4::C, dna4::G, dna4::T};
std::vector<dna4> functor00 = view::get<0>(view::get<0>(t));
EXPECT_EQ(cmp00, functor00);
// pipe notation
std::vector<masked<dna4>> pipe0 = t | view::get<0>;
EXPECT_EQ(cmp0, pipe0);
std::vector<phred42> pipe1 = t | view::get<1>;
EXPECT_EQ(cmp1, pipe1);
std::vector<dna4> pipe00 = t | view::get<0> | view::get<0>;
EXPECT_EQ(cmp00, pipe00);
// combinability
std::vector<masked<dna4>> cmprev{{dna4::T, mask::UNMASKED}, {dna4::G, mask::MASKED},
{dna4::C, mask::UNMASKED}, {dna4::A, mask::MASKED}};
std::vector<masked<dna4>> revtest = t | view::get<0> | view::reverse;
EXPECT_EQ(cmprev, revtest);
std::vector<dna4> cmprev2{dna4::T, dna4::G, dna4::C, dna4::A};
std::vector<dna4> revtest2 = t | view::get<0> | view::get<0> | view::reverse;
EXPECT_EQ(cmprev2, revtest2);
// reference check
functor0[0] = masked<dna4>{dna4::T, mask::UNMASKED};
std::vector<masked<dna4>> cmpref{{dna4::T, mask::UNMASKED}, {dna4::C, mask::UNMASKED},
{dna4::G, mask::MASKED}, {dna4::T, mask::UNMASKED}};
EXPECT_EQ(cmpref, functor0);
}
TEST(view_get, tuple_pair)
{
std::vector<std::pair<int, int>> pair_test{{0, 1}, {1, 2}, {2, 3}, {3, 4}};
std::vector<std::tuple<int, int>> tuple_test{{0, 1}, {1, 2}, {2, 3}, {3, 4}};
// functor notation
std::vector<int> cmp{0, 1, 2, 3};
std::vector<int> pair_func = view::get<0>(pair_test);
std::vector<int> tuple_func = view::get<0>(tuple_test);
EXPECT_EQ(cmp, pair_func);
EXPECT_EQ(cmp, tuple_func);
// reference test
cmp[0] = 4;
pair_func[0] = 4;
tuple_func[0] = 4;
EXPECT_EQ(cmp, pair_func);
EXPECT_EQ(cmp, tuple_func);
// pipe notation
cmp[0] = 0;
std::vector<int> pair_pipe = pair_test | view::get<0>;
std::vector<int> tuple_pipe = tuple_test | view::get<0>;
EXPECT_EQ(cmp, pair_pipe);
EXPECT_EQ(cmp, tuple_pipe);
}
TEST(view_get, concepts)
{
std::vector<std::tuple<int, int>> vec{{0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}};
EXPECT_TRUE(std::ranges::InputRange<decltype(vec)>);
EXPECT_TRUE(std::ranges::ForwardRange<decltype(vec)>);
EXPECT_TRUE(std::ranges::BidirectionalRange<decltype(vec)>);
EXPECT_TRUE(std::ranges::RandomAccessRange<decltype(vec)>);
EXPECT_FALSE(std::ranges::View<decltype(vec)>);
EXPECT_TRUE(std::ranges::SizedRange<decltype(vec)>);
EXPECT_TRUE(std::ranges::CommonRange<decltype(vec)>);
EXPECT_TRUE(const_iterable_concept<decltype(vec)>);
EXPECT_TRUE((std::ranges::OutputRange<decltype(vec), std::tuple<int, int>>));
auto v1 = vec | view::get<0>;
EXPECT_TRUE(std::ranges::InputRange<decltype(v1)>);
EXPECT_TRUE(std::ranges::ForwardRange<decltype(v1)>);
EXPECT_TRUE(std::ranges::BidirectionalRange<decltype(v1)>);
EXPECT_TRUE(std::ranges::RandomAccessRange<decltype(v1)>);
EXPECT_TRUE(std::ranges::View<decltype(v1)>);
EXPECT_TRUE(std::ranges::SizedRange<decltype(v1)>);
EXPECT_TRUE(std::ranges::CommonRange<decltype(v1)>);
EXPECT_TRUE(const_iterable_concept<decltype(v1)>);
EXPECT_FALSE((std::ranges::OutputRange<decltype(v1), std::tuple<int, int>>));
EXPECT_TRUE((std::ranges::OutputRange<decltype(v1), int>));
}
| 41.51087 | 118 | 0.628044 | [
"vector"
] |
25ff18042036e206212ce49c88b3d93be0684ee6 | 4,387 | hxx | C++ | Branch/Include/OpenICV/Basis/icvPrimitiveTensorData.hxx | Tsinghua-OpenICV/OpenICV | 37bf88122414d0c766491460248f61fa1a9fd78c | [
"MIT"
] | 12 | 2019-12-17T08:17:51.000Z | 2021-12-14T03:13:10.000Z | Branch/Include/OpenICV/Basis/icvPrimitiveTensorData.hxx | Tsinghua-OpenICV/OpenICV | 37bf88122414d0c766491460248f61fa1a9fd78c | [
"MIT"
] | null | null | null | Branch/Include/OpenICV/Basis/icvPrimitiveTensorData.hxx | Tsinghua-OpenICV/OpenICV | 37bf88122414d0c766491460248f61fa1a9fd78c | [
"MIT"
] | 7 | 2019-12-17T08:17:54.000Z | 2022-02-21T15:53:57.000Z | #ifndef icvPrimitiveTensorData_hxx
#define icvPrimitiveTensorData_hxx
#include "OpenICV/Core/icvDataObject.h"
#include <vector>
#include <cstdarg>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_pod.hpp>
namespace icv { namespace data
{
enum icvTensorIndexOrder
{
FromFirst, // Index from leftmost, i.e. the last index is contiguous, i.e. row major, i.e. lexicographical
FromLast, // Index from rightmost, i.e. the first index is contiguous, i.e column major, i.e. colexicographical
};
template<typename ElemT, icvTensorIndexOrder IndexOrder = FromFirst>
class icvPrimitiveTensorData : public icv::core::icvDataObject
{
private:
BOOST_STATIC_ASSERT_MSG(boost::is_pod<ElemT>::value, "icvPrimitiveTensorData only support POD types");
public:
icvPrimitiveTensorData(const std::vector<IndexType>& shape) :_shape(shape) {}
IndexType GetSize() const
{
IndexType total = 1;
for (auto count : _shape)
total *= count;
return total;
}
const std::vector<IndexType>& GetShape() const { return _shape; }
virtual void Reserve() ICV_OVERRIDE { if (!_data) _data = new ElemT[GetSize()]; }
virtual void Dispose() ICV_OVERRIDE { if (_data) delete[] _data; _data = ICV_NULLPTR; }
void Reshape(const std::vector<IndexType>& shape) { throw "Not Implemented yet!"; }
virtual Uint64 GetActualMemorySize() ICV_OVERRIDE
{
if (_data) return sizeof(ElemT) * GetSize();
else return 0;
}
// TODO: Not implemented yet
virtual void Serialize(std::stringstream& out, const uint32_t& version) const { throw "Not implemented yet!"; }
virtual void Deserialize(std::stringstream& in, const uint32_t& version) { throw "Not implemented yet!"; }
virtual icv::core::icvDataObject* DeepCopy() ICV_OVERRIDE
{
icvPrimitiveTensorData<ElemT, IndexOrder>* copy = new icvPrimitiveTensorData<ElemT, IndexOrder>(_shape);
copy->_sourceTime = _sourceTime;
copy->Reserve(); std::copy(_data, _data + GetSize(), copy->_data);
return copy;
}
ElemT & At(const std::vector<IndexType>& index)
{
if (index.size() != _shape.size())
ICV_THROW_MESSAGE("Input indices for At() should have the same length with the shape of tensor");
// TODO: return an iterator if length of index is smaller than shape
IndexType tidx = 0;
if (IndexOrder == FromFirst)
for (IndexType i = 0; i < index.size(); i++)
tidx = tidx * _shape[i] + index[i];
else
{
for (IndexType i = index.size() - 1; i > 0; i--) // Avoid overflow of i
tidx = tidx * _shape[i] + index[i];
tidx = tidx * _shape[0] + index[0];
}
return _data[tidx];
}
const ElemT & At(const std::vector<IndexType>& index) const
{
return const_cast<icvPrimitiveTensorData&>(*this).At(index);
}
// Note: use 'u' literal when calling this function
template<typename... T>
ElemT & At(T... indices)
{
std::vector<IndexType> ids{ indices... };
return At(ids);
}
template<typename... T>
const ElemT & At(T... indices) const
{
return const_cast<icvPrimitiveTensorData&>(*this).At(indices...);
}
virtual std::string Print() ICV_OVERRIDE
{
throw "Not implemented yet!";
}
protected:
std::vector<IndexType> _shape;
ElemT* _data = ICV_NULLPTR;
};
#define _ICV_DECLARE_TENSOR_DATA(type) typedef icvPrimitiveTensorData<type> icv##type##TensorData;
ICV_BASIC_TYPES_TEMPLATE(_ICV_DECLARE_TENSOR_DATA);
#undef _ICV_DECLARE_TENSOR_DATA
// Common uses
typedef icvPrimitiveTensorData<IndexType> icvIndexTensorData;
typedef icvPrimitiveTensorData<int> icvIntTensorData;
typedef icvPrimitiveTensorData<double> icvDoubleTensorData;
}}
#endif // icvPrimitiveTensorData_hxx
| 36.558333 | 121 | 0.591065 | [
"shape",
"vector"
] |
d304eb8790fac12cc22fe76b79355a009dc0490e | 1,453 | hpp | C++ | src/hittable_list.hpp | utilForever/ray-tracing-in-one-weekend-cpp | 2c4108ba16890be02d58d72b27b6f35d23ac6d64 | [
"MIT"
] | 12 | 2020-04-01T05:30:40.000Z | 2022-03-23T13:00:47.000Z | src/hittable_list.hpp | utilForever/ray-tracing-in-one-weekend-cpp | 2c4108ba16890be02d58d72b27b6f35d23ac6d64 | [
"MIT"
] | null | null | null | src/hittable_list.hpp | utilForever/ray-tracing-in-one-weekend-cpp | 2c4108ba16890be02d58d72b27b6f35d23ac6d64 | [
"MIT"
] | 1 | 2020-04-20T16:38:38.000Z | 2020-04-20T16:38:38.000Z | // Copyright (c) 2020 Chris Ohk
// I am making my contributions/submissions to this project solely in my
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
// It is based on Ray Tracing in One Weekend book.
// References: https://raytracing.github.io
#ifndef RAY_TRACING_HITTABLE_LIST_HPP
#define RAY_TRACING_HITTABLE_LIST_HPP
#include "hittable.hpp"
#include <memory>
#include <utility>
#include <vector>
class hittable_list final : public hittable
{
public:
hittable_list() = default;
hittable_list(std::shared_ptr<hittable> object)
{
add(std::move(object));
}
void clear()
{
objects.clear();
}
void add(std::shared_ptr<hittable>&& object)
{
objects.emplace_back(object);
}
bool hit(const ray& r, double t_min, double t_max,
hit_record& rec) const override;
std::vector<std::shared_ptr<hittable>> objects;
};
inline bool hittable_list::hit(const ray& r, double t_min, double t_max,
hit_record& rec) const
{
hit_record temp_rec;
bool hit_anything = false;
auto closest_so_far = t_max;
for (const auto& object : objects)
{
if (object->hit(r, t_min, closest_so_far, temp_rec))
{
hit_anything = true;
closest_so_far = temp_rec.t;
rec = temp_rec;
}
}
return hit_anything;
}
#endif | 22.703125 | 73 | 0.644873 | [
"object",
"vector"
] |
d3060aae3918c0dfea57d3197326ef2e0aa4c24b | 2,800 | cpp | C++ | ConversationalGame/Cap10/Adventure/Adventure/object.cpp | Gabroide/Learning-C | 63a89b9b6b84e410756e70e346173d475a1802a6 | [
"Apache-2.0"
] | null | null | null | ConversationalGame/Cap10/Adventure/Adventure/object.cpp | Gabroide/Learning-C | 63a89b9b6b84e410756e70e346173d475a1802a6 | [
"Apache-2.0"
] | null | null | null | ConversationalGame/Cap10/Adventure/Adventure/object.cpp | Gabroide/Learning-C | 63a89b9b6b84e410756e70e346173d475a1802a6 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include "object.h"
static const char *tags0[] = { "field", NULL };
static const char *tags1[] = { "cave", NULL };
static const char *tags2[] = { "silver", "coin", "silver coin", NULL };
static const char *tags3[] = { "gold", "coin", "gold coin", NULL };
static const char *tags4[] = { "guard", "burly guard", NULL };
static const char *tags5[] = { "yourself", NULL };
static const char *tags6[] = { "east", "entrance", NULL };
static const char *tags7[] = { "west", "exit", NULL };
static const char *tags8[] = { "west", "north", "south", "forest", NULL };
static const char *tags9[] = { "east", "north", "south", "rock", NULL };
OBJECT objs[] = {
{ /* 0 = field */
"an open field",
tags0,
NULL,
NULL,
NULL,
"The field is a nice and quiet place under a clear blue sky.\n",
"You see",
"You can't get much closer than this.\n",
99,
9999,
0
},
{ /* 1 = cave */
"a little cave",
tags1,
NULL,
NULL,
NULL,
"The cave is just a cold, damp, rocky chamber.\n",
"You see",
"You can't get much closer than this.\n",
99,
9999,
0
},
{ /* 2 = silver */
"a silver coin",
tags2,
field,
NULL,
NULL,
"The coin has an eagle on the obverse.\n",
"You see",
"You can't get much closer than this.\n",
1,
0,
0
},
{ /* 3 = gold */
"a gold coin",
tags3,
cave,
NULL,
NULL,
"The shiny coin seems to be a rare and priceless artefact.\n",
"You see",
"You can't get much closer than this.\n",
1,
0,
0
},
{ /* 4 = guard */
"a burly guard",
tags4,
field,
NULL,
NULL,
"The guard is a really big fellow.\n",
"He has",
"You can't get much closer than this.\n",
99,
20,
100
},
{ /* 5 = player */
"yourself",
tags5,
field,
NULL,
NULL,
"You would need a mirror to look at yourself.\n",
"You have",
"You can't get much closer than this.\n",
99,
20,
100
},
{ /* 6 = intoCave */
"a cave entrance to the east",
tags6,
field,
NULL,
cave,
"The entrance is just a narrow opening in a small outcrop.\n",
"You see",
"The guard stops you from walking into the cave.\n",
99,
0,
0
},
{ /* 7 = exitCave */
"an exit to the west",
tags7,
cave,
field,
field,
"Sunlight pours in through an opening in the cave's wall.\n",
"You see",
"You walk out of the cave.\n",
99,
0,
0
},
{ /* 8 = wallField */
"dense forest all around",
tags8,
field,
NULL,
NULL,
"The field is surrounded by trees and undergrowth.\n",
"You see",
"Dense forest is blocking the way.\n",
99,
0,
0
},
{ /* 9 = wallCave */
"solid rock all around",
tags9,
cave,
NULL,
NULL,
"Carved in stone is a secret password 'abccb'.\n",
"You see",
"Solid rock is blocking the way.\n",
99,
0,
0
}
}; | 19.310345 | 74 | 0.563929 | [
"object",
"solid"
] |
d306e985728684518bfc6704474decf6c6a6f64e | 438 | cpp | C++ | Dataset/Leetcode/train/22/186.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/22/186.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/22/186.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<string> res;
vector<string> XXX(int n) {
generate("",n,n);
return res;
}
void generate(string str,int leftnum,int rightnum){
if(rightnum==0){
res.push_back(str);
return;
}
if(leftnum>0)
generate(str+"(",leftnum-1,rightnum);
if(rightnum>leftnum)
generate(str+")",leftnum,rightnum-1);
}
};
| 21.9 | 55 | 0.518265 | [
"vector"
] |
d30a218321637e22ce4f52a78685b31faf1acf32 | 2,344 | cpp | C++ | src/cpp/4_BehavioralPatterns/7_Observer/ObserverCodingExercise.cpp | MilovanTomasevic/Design-Patterns | 4ea38e5498d82c53216c45e1024e97470eb9bc7d | [
"MIT"
] | 10 | 2021-04-17T00:02:57.000Z | 2021-11-16T13:20:14.000Z | src/cpp/4_BehavioralPatterns/7_Observer/ObserverCodingExercise.cpp | MilovanTomasevic/Design-Patterns | 4ea38e5498d82c53216c45e1024e97470eb9bc7d | [
"MIT"
] | null | null | null | src/cpp/4_BehavioralPatterns/7_Observer/ObserverCodingExercise.cpp | MilovanTomasevic/Design-Patterns | 4ea38e5498d82c53216c45e1024e97470eb9bc7d | [
"MIT"
] | 1 | 2021-12-23T13:22:26.000Z | 2021-12-23T13:22:26.000Z | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct IRat
{
virtual void rat_enters(IRat* sender) = 0;
virtual void rat_dies(IRat* sender) = 0;
virtual void notify(IRat* target) = 0;
};
struct Game
{
vector<IRat*> rats;
virtual void fire_rat_enters(IRat* sender)
{
for (auto rat : rats) rat->rat_enters(sender);
}
virtual void fire_rat_dies(IRat* sender)
{
for (auto rat : rats) rat->rat_dies(sender);
}
virtual void fire_notify(IRat* target)
{
for (auto rat : rats) rat->notify(target);
}
};
struct Rat : IRat
{
Game& game;
int attack{1};
Rat(Game &game) : game(game)
{
game.rats.push_back(this);
game.fire_rat_enters(this);
}
~Rat()
{
game.fire_rat_dies(this);
game.rats.erase(std::remove(game.rats.begin(),game.rats.end(),this));
}
void rat_enters(IRat *sender) override {
if (sender != this)
{
++attack;
game.fire_notify(sender);
}
}
void rat_dies(IRat *sender) override {
--attack;
}
void notify(IRat *target) override {
if (target == this) ++attack;
}
};
#include "gtest/gtest.h"
//#include "helpers/iohelper.h"
//#include "exercise.cpp"
namespace {
class Evaluate : public ::testing::Test {};
TEST_F(Evaluate, SingleRatTest)
{
Game game;
Rat rat{game};
ASSERT_EQ(1, rat.attack);
}
TEST_F(Evaluate, TwoRatTest)
{
Game game;
Rat rat{game};
Rat rat2{game};
ASSERT_EQ(2, rat.attack);
ASSERT_EQ(2, rat2.attack);
}
TEST_F(Evaluate, ThreeRatsOneDies)
{
Game game;
Rat rat{game};
ASSERT_EQ(1, rat.attack);
Rat rat2{game};
ASSERT_EQ(2, rat.attack);
ASSERT_EQ(2, rat2.attack);
{
Rat rat3{game};
ASSERT_EQ(3, rat.attack);
ASSERT_EQ(3, rat2.attack);
ASSERT_EQ(3, rat3.attack);
}
ASSERT_EQ(2, rat.attack);
ASSERT_EQ(2, rat2.attack);
}
} // namespace
int main(int ac, char* av[])
{
//::testing::GTEST_FLAG(catch_exceptions) = false;
testing::InitGoogleTest(&ac, av);
return RUN_ALL_TESTS();
} | 19.697479 | 76 | 0.550341 | [
"vector"
] |
d30fc766e9f586935694b41fbe2832dca976e1eb | 2,348 | cpp | C++ | graph-source-code/374-C/8871444.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/374-C/8871444.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/374-C/8871444.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: MS C++
#include<iostream>
#include<cstdio>
#include<list>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<cmath>
#include<memory.h>
#include<set>
#include<cctype>
#define ll long long
#define eps 1e-8
const int inf = 1<<30;
const ll INF = 1ll<<61;
using namespace std;
//vector<pair<int,int> > G;
//typedef pair<int,int > P;
//vector<pair<int,int> > ::iterator iter;
//
//map<ll,int >mp;
//map<ll,int >::iterator p;
vector<pair<int,int >> G;
char mp[1000 + 55][1000 + 55];
int n,m;
int cnt;
int mark = 0;
int dir[4][2] = {-1,0,0,-1,1,0,0,1};
int dp[1000 + 55][1000 + 55];
bool flag[200][200];
bool vis[1000 + 55][1000 + 55];
void init() {
G.clear();
memset(vis,false,sizeof(vis));
memset(flag,false,sizeof(flag));
memset(dp,-1,sizeof(dp));
flag['D' - 'A']['I' - 'A'] = true;
flag['I' - 'A']['M' - 'A'] = true;
flag['M' - 'A']['A' - 'A'] = true;
flag['A' - 'A']['D' - 'A'] = true;
}
bool input() {
while(cin>>n>>m) {
for(int i=0;i<n;i++) {
scanf("%s",mp[i]);
for(int j=0;j<m;j++) {
if(mp[i][j] == 'D')
G.push_back(make_pair(i,j));
}
}
return false;
}
return true;
}
int dfs(int posx,int posy,char ch) {
if(dp[posx][posy] != -1)return dp[posx][posy];
dp[posx][posy] = 0;
if(mp[posx][posy] == 'A') {
dp[posx][posy] = 1;
cnt = 1;
}
int ret = 0;
for(int i=0;i<4;i++) {
int dx = posx + dir[i][0];
int dy = posy + dir[i][1];
if(!flag[ch - 'A'][mp[dx][dy] - 'A'])continue;
if(dx < 0 || dx >= n || dy < 0 || dy >= m)continue;
if(vis[dx][dy]){mark = 1;break;}
vis[dx][dy] = true;
int tmp = dfs(dx,dy,mp[dx][dy]);
ret = max(ret,tmp);
vis[dx][dy] = false;
}
return dp[posx][posy] += ret;
}
void cal() {
int ans = 0;
cnt = 0;
mark = 0;
for(int i=0;i<G.size();i++) {
int u = G[i].first;
int v = G[i].second;
if(!vis[u][v]) {
vis[u][v] = true;
dfs(u,v,'D');
int now = dp[u][v];
ans = max(ans,now);
vis[u][v] = false;
}
}
if(!cnt)puts("Poor Dima!");
else if(mark)puts("Poor Inna!");
else cout<<ans<<endl;
}
void output() {
}
int main() {
while(true) {
init();
if(input())return 0;
cal();
output();
}
return 0;
}
| 17.522388 | 54 | 0.513629 | [
"vector"
] |
d3157d4e404ad62240c88d8ea368f76fb56e6883 | 1,679 | cpp | C++ | cpp/data/load_data.cpp | equivalence1/ml_lib | 92d75ab73bc2d77ba8fa66022c803c06cad66f21 | [
"Apache-2.0"
] | null | null | null | cpp/data/load_data.cpp | equivalence1/ml_lib | 92d75ab73bc2d77ba8fa66022c803c06cad66f21 | [
"Apache-2.0"
] | null | null | null | cpp/data/load_data.cpp | equivalence1/ml_lib | 92d75ab73bc2d77ba8fa66022c803c06cad66f21 | [
"Apache-2.0"
] | null | null | null | #include "load_data.h"
#include <torch/torch.h>
#include <core/vec_factory.h>
#include <stdexcept>
DataSet loadFeaturesTxt(const std::string& file) {
std::ifstream in(file);
if (!in) {
throw std::runtime_error("Failed to open file " + file);
}
std::vector<float> pool;
std::vector<float> target;
int64_t linesCount = 0;
int64_t fCount = 0;
std::string tempString;
std::string line;
while (std::getline(in, line) && line.size()) {
std::istringstream parseTokens(line);
float t = 0;
//qid
parseTokens>>tempString;
//target
parseTokens >>t;
//url
parseTokens>>tempString;
//gid
parseTokens>>tempString;
std::vector<double> lineFeatures(std::istream_iterator<double>{parseTokens},
std::istream_iterator<double>());
if (linesCount == 0) {
fCount = lineFeatures.size();
} else {
assert(lineFeatures.size() == fCount);
}
for (auto val : lineFeatures) {
pool.push_back(val);
}
target.push_back(t);
++linesCount;
}
std::cout << "read #" << linesCount << " lines" << std::endl;
std::cout << "fCount #" << fCount << std::endl;
auto data = VecFactory::create(ComputeDeviceType::Cpu, pool.size());
VecRef<float> dst = data.arrayRef();
std::copy(pool.begin(), pool.end(), dst.begin());
auto targetVec = VecFactory::create(ComputeDeviceType::Cpu, target.size());
std::copy(target.begin(), target.end(), targetVec.arrayRef().begin());
Mx mx(data, linesCount, fCount);
return DataSet(mx, targetVec);
}
| 25.439394 | 84 | 0.58249 | [
"vector"
] |
d322e5c396a39b36cdb81da9dcdd20094c0f33f3 | 3,603 | cpp | C++ | info.cpp | ft/amded | 8394ae4c761c960c4b72fc2ebf2694bb9769f2b4 | [
"BSD-2-Clause"
] | 7 | 2015-07-09T18:31:05.000Z | 2022-02-09T12:08:00.000Z | info.cpp | ft/amded | 8394ae4c761c960c4b72fc2ebf2694bb9769f2b4 | [
"BSD-2-Clause"
] | null | null | null | info.cpp | ft/amded | 8394ae4c761c960c4b72fc2ebf2694bb9769f2b4 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2009-2019 amded workers, All rights reserved.
* Terms for redistribution and use can be found in LICENCE.
*/
/**
* @file info.cpp
* @brief display various informational messages
*/
#include <iostream>
#include <vector>
#include "amded.h"
#include "info.h"
#ifdef VENDOR_BUILD
#include "amded-vendor.h"
#endif /* VENDOR_BUILD */
#ifdef GIT_SOURCE
#include "git-version.h"
#endif /* GIT_SOURCE */
/** usage information */
std::vector<std::string> usage = {
"usage: amded OPTION(s) FILE(s)",
"",
" informational options:",
" -h, display this help text",
" -L, show amded's licence information",
" -V, print version information",
" -s <aspect> produce list of supported aspects",
" configuration options:",
" -R <readmap> configure tag reading order",
" -W <writemap> configure which tag types should be written",
" -o <param-list> pass in a comma-separated list of parameters",
" action options:",
" -l list tags in human readable form",
" -m list tags in machine readable form",
" -j list tags in JSON format",
" -S strip all tags from the file",
" -t <tag>=<value> set a tag to a value",
" -d <tag> delete a tag from the file",
};
/** licence information */
std::vector<std::string> licence = {
" Copyright 2009-2018 amded workers, All rights reserved.",
"",
" Redistribution and use in source and binary forms, with or without",
" modification, are permitted provided that the following conditions",
" are met:",
"",
" 1. Redistributions of source code must retain the above copyright",
" notice, this list of conditions and the following disclaimer.",
" 2. Redistributions in binary form must reproduce the above copyright",
" notice, this list of conditions and the following disclaimer in the",
" documentation and/or other materials provided with the distribution.",
"",
" THIS SOFTWARE IS PROVIDED \"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 AUTHOR OR CONTRIBUTORS OF THE PROJECT 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.",
};
/** Print version information about amded */
void
amded_version(void)
{
std::cout << PROJECT << " version ";
#ifdef GIT_SOURCE
std::cout << GIT_VERSION;
#else
std::cout << VERSION;
#endif /* GIT_SOURCE */
#ifdef VENDOR_BUILD
std::cout << " (" << VENDOR_VERSION << ")";
#endif /* VENDOR_VERSION */
std::cout << std::endl;
#ifdef GIT_SOURCE
std::cout << "Based on commit: " << GIT_DESCRIPTION << std::endl;
#endif /* GIT_SOURCE */
}
static void
print_vector(std::vector<std::string> v)
{
for (auto &it : v) {
std::cout << it << std::endl;
}
}
/** Print out usage information (contained in the usage vector above) */
void
amded_usage(void)
{
print_vector(usage);
}
/** Print out licencing information (contained in the licence vector above) */
void
amded_licence(void)
{
print_vector(licence);
}
| 31.060345 | 78 | 0.668332 | [
"vector"
] |
d3304a996f566b9a4215d34e70ea4c82bdceb630 | 22,856 | cpp | C++ | src/amd/compiler/aco_print_ir.cpp | PWN-Hunter/mesa3d | be12e189989e3476d7c9d40e1c0c3a35143ee51a | [
"MIT"
] | null | null | null | src/amd/compiler/aco_print_ir.cpp | PWN-Hunter/mesa3d | be12e189989e3476d7c9d40e1c0c3a35143ee51a | [
"MIT"
] | null | null | null | src/amd/compiler/aco_print_ir.cpp | PWN-Hunter/mesa3d | be12e189989e3476d7c9d40e1c0c3a35143ee51a | [
"MIT"
] | null | null | null | #include "aco_ir.h"
#include "aco_builder.h"
#include "sid.h"
#include "ac_shader_util.h"
namespace aco {
static const char *reduce_ops[] = {
[iadd32] = "iadd32",
[iadd64] = "iadd64",
[imul32] = "imul32",
[imul64] = "imul64",
[fadd32] = "fadd32",
[fadd64] = "fadd64",
[fmul32] = "fmul32",
[fmul64] = "fmul64",
[imin32] = "imin32",
[imin64] = "imin64",
[imax32] = "imax32",
[imax64] = "imax64",
[umin32] = "umin32",
[umin64] = "umin64",
[umax32] = "umax32",
[umax64] = "umax64",
[fmin32] = "fmin32",
[fmin64] = "fmin64",
[fmax32] = "fmax32",
[fmax64] = "fmax64",
[iand32] = "iand32",
[iand64] = "iand64",
[ior32] = "ior32",
[ior64] = "ior64",
[ixor32] = "ixor32",
[ixor64] = "ixor64",
};
static void print_reg_class(const RegClass rc, FILE *output)
{
switch (rc) {
case RegClass::s1: fprintf(output, " s1: "); return;
case RegClass::s2: fprintf(output, " s2: "); return;
case RegClass::s3: fprintf(output, " s3: "); return;
case RegClass::s4: fprintf(output, " s4: "); return;
case RegClass::s6: fprintf(output, " s6: "); return;
case RegClass::s8: fprintf(output, " s8: "); return;
case RegClass::s16: fprintf(output, "s16: "); return;
case RegClass::v1: fprintf(output, " v1: "); return;
case RegClass::v2: fprintf(output, " v2: "); return;
case RegClass::v3: fprintf(output, " v3: "); return;
case RegClass::v4: fprintf(output, " v4: "); return;
case RegClass::v5: fprintf(output, " v5: "); return;
case RegClass::v6: fprintf(output, " v6: "); return;
case RegClass::v7: fprintf(output, " v7: "); return;
case RegClass::v8: fprintf(output, " v8: "); return;
case RegClass::v1_linear: fprintf(output, " v1: "); return;
case RegClass::v2_linear: fprintf(output, " v2: "); return;
}
}
void print_physReg(unsigned reg, unsigned size, FILE *output)
{
if (reg == 124) {
fprintf(output, ":m0");
} else if (reg == 106) {
fprintf(output, ":vcc");
} else if (reg == 253) {
fprintf(output, ":scc");
} else if (reg == 126) {
fprintf(output, ":exec");
} else {
bool is_vgpr = reg / 256;
reg = reg % 256;
fprintf(output, ":%c[%d", is_vgpr ? 'v' : 's', reg);
if (size > 1)
fprintf(output, "-%d]", reg + size -1);
else
fprintf(output, "]");
}
}
static void print_constant(uint8_t reg, FILE *output)
{
if (reg >= 128 && reg <= 192) {
fprintf(output, "%d", reg - 128);
return;
} else if (reg >= 192 && reg <= 208) {
fprintf(output, "%d", 192 - reg);
return;
}
switch (reg) {
case 240:
fprintf(output, "0.5");
break;
case 241:
fprintf(output, "-0.5");
break;
case 242:
fprintf(output, "1.0");
break;
case 243:
fprintf(output, "-1.0");
break;
case 244:
fprintf(output, "2.0");
break;
case 245:
fprintf(output, "-2.0");
break;
case 246:
fprintf(output, "4.0");
break;
case 247:
fprintf(output, "-4.0");
break;
case 248:
fprintf(output, "1/(2*PI)");
break;
}
}
static void print_operand(const Operand *operand, FILE *output)
{
if (operand->isLiteral()) {
fprintf(output, "0x%x", operand->constantValue());
} else if (operand->isConstant()) {
print_constant(operand->physReg().reg, output);
} else if (operand->isUndefined()) {
print_reg_class(operand->regClass(), output);
fprintf(output, "undef");
} else {
fprintf(output, "%%%d", operand->tempId());
if (operand->isFixed())
print_physReg(operand->physReg(), operand->size(), output);
}
}
static void print_definition(const Definition *definition, FILE *output)
{
print_reg_class(definition->regClass(), output);
fprintf(output, "%%%d", definition->tempId());
if (definition->isFixed())
print_physReg(definition->physReg(), definition->size(), output);
}
static void print_barrier_reorder(bool can_reorder, barrier_interaction barrier, FILE *output)
{
if (can_reorder)
fprintf(output, " reorder");
if (barrier & barrier_buffer)
fprintf(output, " buffer");
if (barrier & barrier_image)
fprintf(output, " image");
if (barrier & barrier_atomic)
fprintf(output, " atomic");
if (barrier & barrier_shared)
fprintf(output, " shared");
if (barrier & barrier_gs_data)
fprintf(output, " gs_data");
if (barrier & barrier_gs_sendmsg)
fprintf(output, " gs_sendmsg");
}
static void print_instr_format_specific(struct Instruction *instr, FILE *output)
{
switch (instr->format) {
case Format::SOPK: {
SOPK_instruction* sopk = static_cast<SOPK_instruction*>(instr);
fprintf(output, " imm:%d", sopk->imm & 0x8000 ? (sopk->imm - 65536) : sopk->imm);
break;
}
case Format::SOPP: {
SOPP_instruction* sopp = static_cast<SOPP_instruction*>(instr);
uint16_t imm = sopp->imm;
switch (instr->opcode) {
case aco_opcode::s_waitcnt: {
/* we usually should check the chip class for vmcnt/lgkm, but
* insert_waitcnt() should fill it in regardless. */
unsigned vmcnt = (imm & 0xF) | ((imm & (0x3 << 14)) >> 10);
if (vmcnt != 63) fprintf(output, " vmcnt(%d)", vmcnt);
if (((imm >> 4) & 0x7) < 0x7) fprintf(output, " expcnt(%d)", (imm >> 4) & 0x7);
if (((imm >> 8) & 0x3F) < 0x3F) fprintf(output, " lgkmcnt(%d)", (imm >> 8) & 0x3F);
break;
}
case aco_opcode::s_endpgm:
case aco_opcode::s_endpgm_saved:
case aco_opcode::s_endpgm_ordered_ps_done:
case aco_opcode::s_wakeup:
case aco_opcode::s_barrier:
case aco_opcode::s_icache_inv:
case aco_opcode::s_ttracedata:
case aco_opcode::s_set_gpr_idx_off: {
break;
}
case aco_opcode::s_sendmsg: {
unsigned id = imm & sendmsg_id_mask;
switch (id) {
case sendmsg_none:
fprintf(output, " sendmsg(MSG_NONE)");
break;
case _sendmsg_gs:
fprintf(output, " sendmsg(gs%s%s, %u)",
imm & 0x10 ? ", cut" : "", imm & 0x20 ? ", emit" : "", imm >> 8);
break;
case _sendmsg_gs_done:
fprintf(output, " sendmsg(gs_done%s%s, %u)",
imm & 0x10 ? ", cut" : "", imm & 0x20 ? ", emit" : "", imm >> 8);
break;
case sendmsg_save_wave:
fprintf(output, " sendmsg(save_wave)");
break;
case sendmsg_stall_wave_gen:
fprintf(output, " sendmsg(stall_wave_gen)");
break;
case sendmsg_halt_waves:
fprintf(output, " sendmsg(halt_waves)");
break;
case sendmsg_ordered_ps_done:
fprintf(output, " sendmsg(ordered_ps_done)");
break;
case sendmsg_early_prim_dealloc:
fprintf(output, " sendmsg(early_prim_dealloc)");
break;
case sendmsg_gs_alloc_req:
fprintf(output, " sendmsg(gs_alloc_req)");
break;
}
break;
}
default: {
if (imm)
fprintf(output, " imm:%u", imm);
break;
}
}
if (sopp->block != -1)
fprintf(output, " block:BB%d", sopp->block);
break;
}
case Format::SMEM: {
SMEM_instruction* smem = static_cast<SMEM_instruction*>(instr);
if (smem->glc)
fprintf(output, " glc");
if (smem->dlc)
fprintf(output, " dlc");
if (smem->nv)
fprintf(output, " nv");
print_barrier_reorder(smem->can_reorder, smem->barrier, output);
break;
}
case Format::VINTRP: {
Interp_instruction* vintrp = static_cast<Interp_instruction*>(instr);
fprintf(output, " attr%d.%c", vintrp->attribute, "xyzw"[vintrp->component]);
break;
}
case Format::DS: {
DS_instruction* ds = static_cast<DS_instruction*>(instr);
if (ds->offset0)
fprintf(output, " offset0:%u", ds->offset0);
if (ds->offset1)
fprintf(output, " offset1:%u", ds->offset1);
if (ds->gds)
fprintf(output, " gds");
break;
}
case Format::MUBUF: {
MUBUF_instruction* mubuf = static_cast<MUBUF_instruction*>(instr);
if (mubuf->offset)
fprintf(output, " offset:%u", mubuf->offset);
if (mubuf->offen)
fprintf(output, " offen");
if (mubuf->idxen)
fprintf(output, " idxen");
if (mubuf->addr64)
fprintf(output, " addr64");
if (mubuf->glc)
fprintf(output, " glc");
if (mubuf->dlc)
fprintf(output, " dlc");
if (mubuf->slc)
fprintf(output, " slc");
if (mubuf->tfe)
fprintf(output, " tfe");
if (mubuf->lds)
fprintf(output, " lds");
if (mubuf->disable_wqm)
fprintf(output, " disable_wqm");
print_barrier_reorder(mubuf->can_reorder, mubuf->barrier, output);
break;
}
case Format::MIMG: {
MIMG_instruction* mimg = static_cast<MIMG_instruction*>(instr);
unsigned identity_dmask = !instr->definitions.empty() ?
(1 << instr->definitions[0].size()) - 1 :
0xf;
if ((mimg->dmask & identity_dmask) != identity_dmask)
fprintf(output, " dmask:%s%s%s%s",
mimg->dmask & 0x1 ? "x" : "",
mimg->dmask & 0x2 ? "y" : "",
mimg->dmask & 0x4 ? "z" : "",
mimg->dmask & 0x8 ? "w" : "");
switch (mimg->dim) {
case ac_image_1d:
fprintf(output, " 1d");
break;
case ac_image_2d:
fprintf(output, " 2d");
break;
case ac_image_3d:
fprintf(output, " 3d");
break;
case ac_image_cube:
fprintf(output, " cube");
break;
case ac_image_1darray:
fprintf(output, " 1darray");
break;
case ac_image_2darray:
fprintf(output, " 2darray");
break;
case ac_image_2dmsaa:
fprintf(output, " 2dmsaa");
break;
case ac_image_2darraymsaa:
fprintf(output, " 2darraymsaa");
break;
}
if (mimg->unrm)
fprintf(output, " unrm");
if (mimg->glc)
fprintf(output, " glc");
if (mimg->dlc)
fprintf(output, " dlc");
if (mimg->slc)
fprintf(output, " slc");
if (mimg->tfe)
fprintf(output, " tfe");
if (mimg->da)
fprintf(output, " da");
if (mimg->lwe)
fprintf(output, " lwe");
if (mimg->r128 || mimg->a16)
fprintf(output, " r128/a16");
if (mimg->d16)
fprintf(output, " d16");
if (mimg->disable_wqm)
fprintf(output, " disable_wqm");
print_barrier_reorder(mimg->can_reorder, mimg->barrier, output);
break;
}
case Format::EXP: {
Export_instruction* exp = static_cast<Export_instruction*>(instr);
unsigned identity_mask = exp->compressed ? 0x5 : 0xf;
if ((exp->enabled_mask & identity_mask) != identity_mask)
fprintf(output, " en:%c%c%c%c",
exp->enabled_mask & 0x1 ? 'r' : '*',
exp->enabled_mask & 0x2 ? 'g' : '*',
exp->enabled_mask & 0x4 ? 'b' : '*',
exp->enabled_mask & 0x8 ? 'a' : '*');
if (exp->compressed)
fprintf(output, " compr");
if (exp->done)
fprintf(output, " done");
if (exp->valid_mask)
fprintf(output, " vm");
if (exp->dest <= V_008DFC_SQ_EXP_MRT + 7)
fprintf(output, " mrt%d", exp->dest - V_008DFC_SQ_EXP_MRT);
else if (exp->dest == V_008DFC_SQ_EXP_MRTZ)
fprintf(output, " mrtz");
else if (exp->dest == V_008DFC_SQ_EXP_NULL)
fprintf(output, " null");
else if (exp->dest >= V_008DFC_SQ_EXP_POS && exp->dest <= V_008DFC_SQ_EXP_POS + 3)
fprintf(output, " pos%d", exp->dest - V_008DFC_SQ_EXP_POS);
else if (exp->dest >= V_008DFC_SQ_EXP_PARAM && exp->dest <= V_008DFC_SQ_EXP_PARAM + 31)
fprintf(output, " param%d", exp->dest - V_008DFC_SQ_EXP_PARAM);
break;
}
case Format::PSEUDO_BRANCH: {
Pseudo_branch_instruction* branch = static_cast<Pseudo_branch_instruction*>(instr);
/* Note: BB0 cannot be a branch target */
if (branch->target[0] != 0)
fprintf(output, " BB%d", branch->target[0]);
if (branch->target[1] != 0)
fprintf(output, ", BB%d", branch->target[1]);
break;
}
case Format::PSEUDO_REDUCTION: {
Pseudo_reduction_instruction* reduce = static_cast<Pseudo_reduction_instruction*>(instr);
fprintf(output, " op:%s", reduce_ops[reduce->reduce_op]);
if (reduce->cluster_size)
fprintf(output, " cluster_size:%u", reduce->cluster_size);
break;
}
case Format::FLAT:
case Format::GLOBAL:
case Format::SCRATCH: {
FLAT_instruction* flat = static_cast<FLAT_instruction*>(instr);
if (flat->offset)
fprintf(output, " offset:%u", flat->offset);
if (flat->glc)
fprintf(output, " glc");
if (flat->dlc)
fprintf(output, " dlc");
if (flat->slc)
fprintf(output, " slc");
if (flat->lds)
fprintf(output, " lds");
if (flat->nv)
fprintf(output, " nv");
if (flat->disable_wqm)
fprintf(output, " disable_wqm");
print_barrier_reorder(flat->can_reorder, flat->barrier, output);
break;
}
case Format::MTBUF: {
MTBUF_instruction* mtbuf = static_cast<MTBUF_instruction*>(instr);
fprintf(output, " dfmt:");
switch (mtbuf->dfmt) {
case V_008F0C_BUF_DATA_FORMAT_8: fprintf(output, "8"); break;
case V_008F0C_BUF_DATA_FORMAT_16: fprintf(output, "16"); break;
case V_008F0C_BUF_DATA_FORMAT_8_8: fprintf(output, "8_8"); break;
case V_008F0C_BUF_DATA_FORMAT_32: fprintf(output, "32"); break;
case V_008F0C_BUF_DATA_FORMAT_16_16: fprintf(output, "16_16"); break;
case V_008F0C_BUF_DATA_FORMAT_10_11_11: fprintf(output, "10_11_11"); break;
case V_008F0C_BUF_DATA_FORMAT_11_11_10: fprintf(output, "11_11_10"); break;
case V_008F0C_BUF_DATA_FORMAT_10_10_10_2: fprintf(output, "10_10_10_2"); break;
case V_008F0C_BUF_DATA_FORMAT_2_10_10_10: fprintf(output, "2_10_10_10"); break;
case V_008F0C_BUF_DATA_FORMAT_8_8_8_8: fprintf(output, "8_8_8_8"); break;
case V_008F0C_BUF_DATA_FORMAT_32_32: fprintf(output, "32_32"); break;
case V_008F0C_BUF_DATA_FORMAT_16_16_16_16: fprintf(output, "16_16_16_16"); break;
case V_008F0C_BUF_DATA_FORMAT_32_32_32: fprintf(output, "32_32_32"); break;
case V_008F0C_BUF_DATA_FORMAT_32_32_32_32: fprintf(output, "32_32_32_32"); break;
case V_008F0C_BUF_DATA_FORMAT_RESERVED_15: fprintf(output, "reserved15"); break;
}
fprintf(output, " nfmt:");
switch (mtbuf->nfmt) {
case V_008F0C_BUF_NUM_FORMAT_UNORM: fprintf(output, "unorm"); break;
case V_008F0C_BUF_NUM_FORMAT_SNORM: fprintf(output, "snorm"); break;
case V_008F0C_BUF_NUM_FORMAT_USCALED: fprintf(output, "uscaled"); break;
case V_008F0C_BUF_NUM_FORMAT_SSCALED: fprintf(output, "sscaled"); break;
case V_008F0C_BUF_NUM_FORMAT_UINT: fprintf(output, "uint"); break;
case V_008F0C_BUF_NUM_FORMAT_SINT: fprintf(output, "sint"); break;
case V_008F0C_BUF_NUM_FORMAT_SNORM_OGL: fprintf(output, "snorm"); break;
case V_008F0C_BUF_NUM_FORMAT_FLOAT: fprintf(output, "float"); break;
}
if (mtbuf->offset)
fprintf(output, " offset:%u", mtbuf->offset);
if (mtbuf->offen)
fprintf(output, " offen");
if (mtbuf->idxen)
fprintf(output, " idxen");
if (mtbuf->glc)
fprintf(output, " glc");
if (mtbuf->dlc)
fprintf(output, " dlc");
if (mtbuf->slc)
fprintf(output, " slc");
if (mtbuf->tfe)
fprintf(output, " tfe");
if (mtbuf->disable_wqm)
fprintf(output, " disable_wqm");
print_barrier_reorder(mtbuf->can_reorder, mtbuf->barrier, output);
break;
}
default: {
break;
}
}
if (instr->isVOP3()) {
VOP3A_instruction* vop3 = static_cast<VOP3A_instruction*>(instr);
switch (vop3->omod) {
case 1:
fprintf(output, " *2");
break;
case 2:
fprintf(output, " *4");
break;
case 3:
fprintf(output, " *0.5");
break;
}
if (vop3->clamp)
fprintf(output, " clamp");
} else if (instr->isDPP()) {
DPP_instruction* dpp = static_cast<DPP_instruction*>(instr);
if (dpp->dpp_ctrl <= 0xff) {
fprintf(output, " quad_perm:[%d,%d,%d,%d]",
dpp->dpp_ctrl & 0x3, (dpp->dpp_ctrl >> 2) & 0x3,
(dpp->dpp_ctrl >> 4) & 0x3, (dpp->dpp_ctrl >> 6) & 0x3);
} else if (dpp->dpp_ctrl >= 0x101 && dpp->dpp_ctrl <= 0x10f) {
fprintf(output, " row_shl:%d", dpp->dpp_ctrl & 0xf);
} else if (dpp->dpp_ctrl >= 0x111 && dpp->dpp_ctrl <= 0x11f) {
fprintf(output, " row_shr:%d", dpp->dpp_ctrl & 0xf);
} else if (dpp->dpp_ctrl >= 0x121 && dpp->dpp_ctrl <= 0x12f) {
fprintf(output, " row_ror:%d", dpp->dpp_ctrl & 0xf);
} else if (dpp->dpp_ctrl == dpp_wf_sl1) {
fprintf(output, " wave_shl:1");
} else if (dpp->dpp_ctrl == dpp_wf_rl1) {
fprintf(output, " wave_rol:1");
} else if (dpp->dpp_ctrl == dpp_wf_sr1) {
fprintf(output, " wave_shr:1");
} else if (dpp->dpp_ctrl == dpp_wf_rr1) {
fprintf(output, " wave_ror:1");
} else if (dpp->dpp_ctrl == dpp_row_mirror) {
fprintf(output, " row_mirror");
} else if (dpp->dpp_ctrl == dpp_row_half_mirror) {
fprintf(output, " row_half_mirror");
} else if (dpp->dpp_ctrl == dpp_row_bcast15) {
fprintf(output, " row_bcast:15");
} else if (dpp->dpp_ctrl == dpp_row_bcast31) {
fprintf(output, " row_bcast:31");
} else {
fprintf(output, " dpp_ctrl:0x%.3x", dpp->dpp_ctrl);
}
if (dpp->row_mask != 0xf)
fprintf(output, " row_mask:0x%.1x", dpp->row_mask);
if (dpp->bank_mask != 0xf)
fprintf(output, " bank_mask:0x%.1x", dpp->bank_mask);
if (dpp->bound_ctrl)
fprintf(output, " bound_ctrl:1");
} else if ((int)instr->format & (int)Format::SDWA) {
fprintf(output, " (printing unimplemented)");
}
}
void aco_print_instr(struct Instruction *instr, FILE *output)
{
if (!instr->definitions.empty()) {
for (unsigned i = 0; i < instr->definitions.size(); ++i) {
print_definition(&instr->definitions[i], output);
if (i + 1 != instr->definitions.size())
fprintf(output, ", ");
}
fprintf(output, " = ");
}
fprintf(output, "%s", instr_info.name[(int)instr->opcode]);
if (instr->operands.size()) {
bool abs[instr->operands.size()];
bool neg[instr->operands.size()];
if ((int)instr->format & (int)Format::VOP3A) {
VOP3A_instruction* vop3 = static_cast<VOP3A_instruction*>(instr);
for (unsigned i = 0; i < instr->operands.size(); ++i) {
abs[i] = vop3->abs[i];
neg[i] = vop3->neg[i];
}
} else if (instr->isDPP()) {
DPP_instruction* dpp = static_cast<DPP_instruction*>(instr);
assert(instr->operands.size() <= 2);
for (unsigned i = 0; i < instr->operands.size(); ++i) {
abs[i] = dpp->abs[i];
neg[i] = dpp->neg[i];
}
} else {
for (unsigned i = 0; i < instr->operands.size(); ++i) {
abs[i] = false;
neg[i] = false;
}
}
for (unsigned i = 0; i < instr->operands.size(); ++i) {
if (i)
fprintf(output, ", ");
else
fprintf(output, " ");
if (neg[i])
fprintf(output, "-");
if (abs[i])
fprintf(output, "|");
print_operand(&instr->operands[i], output);
if (abs[i])
fprintf(output, "|");
}
}
print_instr_format_specific(instr, output);
}
static void print_block_kind(uint16_t kind, FILE *output)
{
if (kind & block_kind_uniform)
fprintf(output, "uniform, ");
if (kind & block_kind_top_level)
fprintf(output, "top-level, ");
if (kind & block_kind_loop_preheader)
fprintf(output, "loop-preheader, ");
if (kind & block_kind_loop_header)
fprintf(output, "loop-header, ");
if (kind & block_kind_loop_exit)
fprintf(output, "loop-exit, ");
if (kind & block_kind_continue)
fprintf(output, "continue, ");
if (kind & block_kind_break)
fprintf(output, "break, ");
if (kind & block_kind_continue_or_break)
fprintf(output, "continue_or_break, ");
if (kind & block_kind_discard)
fprintf(output, "discard, ");
if (kind & block_kind_branch)
fprintf(output, "branch, ");
if (kind & block_kind_merge)
fprintf(output, "merge, ");
if (kind & block_kind_invert)
fprintf(output, "invert, ");
if (kind & block_kind_uses_discard_if)
fprintf(output, "discard_if, ");
if (kind & block_kind_needs_lowering)
fprintf(output, "needs_lowering, ");
if (kind & block_kind_uses_demote)
fprintf(output, "uses_demote, ");
}
void aco_print_block(const struct Block* block, FILE *output)
{
fprintf(output, "BB%d\n", block->index);
fprintf(output, "/* logical preds: ");
for (unsigned pred : block->logical_preds)
fprintf(output, "BB%d, ", pred);
fprintf(output, "/ linear preds: ");
for (unsigned pred : block->linear_preds)
fprintf(output, "BB%d, ", pred);
fprintf(output, "/ kind: ");
print_block_kind(block->kind, output);
fprintf(output, "*/\n");
for (auto const& instr : block->instructions) {
fprintf(output, "\t");
aco_print_instr(instr.get(), output);
fprintf(output, "\n");
}
}
void aco_print_program(Program *program, FILE *output)
{
for (Block const& block : program->blocks)
aco_print_block(&block, output);
if (program->constant_data.size()) {
fprintf(output, "\n/* constant data */\n");
for (unsigned i = 0; i < program->constant_data.size(); i += 32) {
fprintf(output, "[%06d] ", i);
unsigned line_size = std::min<size_t>(program->constant_data.size() - i, 32);
for (unsigned j = 0; j < line_size; j += 4) {
unsigned size = std::min<size_t>(program->constant_data.size() - (i + j), 4);
uint32_t v = 0;
memcpy(&v, &program->constant_data[i + j], size);
fprintf(output, " %08x", v);
}
fprintf(output, "\n");
}
}
fprintf(output, "\n");
}
}
| 34.682853 | 95 | 0.569785 | [
"3d"
] |
d336c07f4b930101a37b07f219998007e19bed25 | 37,682 | cpp | C++ | Source/AllProjects/CIDBuild/CIDBuild_VCppDriver.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | null | null | null | Source/AllProjects/CIDBuild/CIDBuild_VCppDriver.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | null | null | null | Source/AllProjects/CIDBuild/CIDBuild_VCppDriver.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | null | null | null | //
// FILE NAME: CIDBuild_VCppDriver.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/29/1998
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the TVCppDriver class.
//
// CAVEATS/GOTCHAS:
//
// 1) Each driver includes its own header directly, so that it does not
// show up to other code. Only the TToolsDriver.cpp file includes all
// of the concrete driver instantiation headers, and uses conditional
// compilation to include only the one that is required.
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDBuild.hpp"
#include "CIDBuild_VCppDriver.hpp"
// ---------------------------------------------------------------------------
// CLASS: TVCppDriver
// PREFIX: tdrv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TVCppDriver: Constructors and Destructor
// ---------------------------------------------------------------------------
TVCppDriver::TVCppDriver() :
m_bDebug(kCIDLib::False)
{
//
// Get a short cut indicator for whether we are doing a debug or prod
// build, since we use it a lot below.
//
m_bDebug = (facCIDBuild.eBldMode() == tCIDBuild::EBldModes::Develop);
}
TVCppDriver::~TVCppDriver()
{
}
// ---------------------------------------------------------------------------
// TVCppDriver: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TVCppDriver::bBuild(const TProjectInfo& projiTarget)
{
// Store away the target project for internal use while we are here
m_pprojiTarget = &projiTarget;
//
// Build up the output file. If its versioned, then add the version
// postfix.
//
m_strTargetFile = projiTarget.strProjectName();
if (projiTarget.bVersioned())
m_strTargetFile.Append(facCIDBuild.strVersionSuffix());
if ((projiTarget.eType() == tCIDBuild::EProjTypes::SharedLib)
|| (projiTarget.eType() == tCIDBuild::EProjTypes::SharedObj))
{
m_strTargetFile.Append(kCIDBuild::pszDllExt);
}
else if (projiTarget.eType() == tCIDBuild::EProjTypes::StaticLib)
{
m_strTargetFile.Append(kCIDBuild::pszLibExt);
}
else if ((projiTarget.eType() == tCIDBuild::EProjTypes::Executable)
|| (projiTarget.eType() == tCIDBuild::EProjTypes::Service))
{
m_strTargetFile.Append(kCIDBuild::pszExeExt);
}
else
{
stdOut << L"Unknown project type, can't set output prefix"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::Internal;
}
// Compile any shader files
if (!bCompileShaders())
return kCIDLib::False;
//
// Lets do our Cpp compilations. We just run through each of the Cpp
// files, which our parent class has has already set up, and ask if
// each one needs to be compiled. If so, we build it.
//
tCIDLib::TBoolean bObjBuilt = bCompileCpps();
//
// NOTE: We change to the main output directory before we link, so all
// of the file names are relative to that. This makes the link line
// a LOT smaller.
//
if (!TUtils::bChangeDir(facCIDBuild.strOutDir()))
{
stdOut << L"Could not change to output directory for link step"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::Internal;
}
if ((bObjBuilt) && facCIDBuild.bVerbose())
stdOut << L" Linking because an Obj was rebuilt" << kCIDBuild::EndLn;
//
// Now lets see if the target file is out of date with any of its Obj,
// Lib, Res, etc... files. If so, then we have to build it. If any
// Obj files were built, then don't bother checking since we know that
// we have to link.
//
// If the Force option is on, then of course we have to rebuild and
// there is no reason to check anything.
//
tCIDLib::TBoolean bUpdate = (bObjBuilt || facCIDBuild.bForce());
if (!bUpdate)
{
// See if the target exists, if not obviously we have to build
TFindInfo fndiTarget;
if (!TFindInfo::bFindAFile(m_strTargetFile, fndiTarget))
{
bUpdate = kCIDLib::True;
if (facCIDBuild.bVerbose())
{
stdOut << L" Target file not present: "
<< m_strTargetFile << kCIDBuild::EndLn;
}
}
//
// If nothing to do yet, then see if any of the Lib or Obj files
// are newer than the target.
//
if (!bUpdate)
{
if (bObjsNewer(fndiTarget) || bLibsNewer(fndiTarget))
bUpdate = kCIDLib::True;
}
}
if (bUpdate)
{
if ((projiTarget.eType() == tCIDBuild::EProjTypes::SharedLib)
|| (projiTarget.eType() == tCIDBuild::EProjTypes::SharedObj)
|| (projiTarget.eType() == tCIDBuild::EProjTypes::Executable)
|| (projiTarget.eType() == tCIDBuild::EProjTypes::Service))
{
Link(kCIDLib::False);
}
else if (projiTarget.eType() == tCIDBuild::EProjTypes::StaticLib)
{
LinkStatic();
}
else
{
// This is bad, we don't know what it is
stdOut << L"Unknown project type, can't link"
<< kCIDBuild::EndLn;
throw tCIDBuild::EErrors::Internal;
}
// Call the post link step, to allow for per-platform twiddling
PostLink(projiTarget, m_strTargetFile);
}
// It went ok, so return success
return kCIDLib::True;
}
//
// A convenience to invoke the debugger
//
tCIDLib::TBoolean TVCppDriver::bInvokeDebugger(const TProjectInfo& projiTarget)
{
//
// The base class changed us to the project source directory. We just need to
// invoke the debugger. First, let's just see if the target exists. If not,
// can't really do much.
//
TBldStr strTarFile = facCIDBuild.strOutDir();
strTarFile.Append(projiTarget.strProjectName());
strTarFile.Append(L".exe");
if (!TUtils::bExists(strTarFile))
{
stdOut << L"The output file doesn't exist, can't debug it"
<< kCIDBuild::EndLn;
return kCIDLib::False;
}
// Build up the path to the solution file for this project
TBldStr strSln = facCIDBuild.strOutDir();
strSln.Append(projiTarget.strProjectName());
strSln.Append(L".sln");
// If the force flag was set, then delete it to force a new session
if (facCIDBuild.bForce() && TUtils::bExists(strSln))
TUtils::bDeleteFile(strSln);
//
// We build up the parameters, which are taken as an array of string pointers.
// The scenarios are either:
//
// devenv.exe [slnfile]
// devenv.exe /debugexe [tarfile] [options...]
//
// So worst case is three plus the options count.
//
const tCIDLib::TCard4 c4MaxParms = 3 + facCIDBuild.listDebugParms().c4ElemCount();
const tCIDLib::TCh** apszParams = new const tCIDLib::TCh*[c4MaxParms];
tCIDLib::TCard4 c4ParamCnt = 0;
apszParams[c4ParamCnt++] = L"devenv.exe";
if (TUtils::bExists(strSln))
{
// The easy scenario, just debugger and sln file
apszParams[c4ParamCnt++] = strSln.pszBuffer();
}
else
{
// First is the target file with debug prefix then any passed parameters
apszParams[c4ParamCnt++] = L"/debugexe";
apszParams[c4ParamCnt++] = strTarFile.pszBuffer();
TListCursor<TBldStr> cursParms(&facCIDBuild.listDebugParms());
if (cursParms.bResetIter())
{
do
{
apszParams[c4ParamCnt++] = cursParms->pszBuffer();
} while (cursParms.bNext());
}
}
if (c4ParamCnt > c4MaxParms)
{
stdOut << L"Debug input parameters overflow" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::Internal;
}
//
// And now let's invoke the debugger. Async in this case, so we won't get back
// any result code.
//
const tCIDLib::TCard4 c4ExecFlags = kCIDBuild::c4ExecFlag_Async;
tCIDLib::TCard4 c4Result;
if (!TUtils::bExec(apszParams, c4ParamCnt, c4Result, c4ExecFlags))
{
stdOut << L"Could not execute the debugger" << kCIDBuild::EndLn;
return kCIDLib::False;
}
return kCIDLib::True;
}
tCIDLib::TVoid TVCppDriver::ResetDebugInfo(const TProjectInfo& projiToReset)
{
//
// Build up the path to the .sln file and see if it exists. If so, delete
// it.
//
TBldStr strSln = facCIDBuild.strOutDir();
strSln.Append(L"*.sln");
if (TUtils::bExists(strSln))
TUtils::bDeleteFile(strSln);
}
// ---------------------------------------------------------------------------
// TVCppDriver: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TVCppDriver::bCompileOne(const tCIDLib::TCh** apszArgs
, const tCIDLib::TCard4 c4ArgCnt
, tCIDLib::TCard4& c4ErrCode)
{
if (facCIDBuild.bVerbose())
{
for (tCIDLib::TCard4 c4Ind = 0; c4Ind < c4ArgCnt; c4Ind++)
stdOut << apszArgs[c4Ind] << L" ";
stdOut << kCIDBuild::EndLn;
}
// Ok, lets do the compilation
tCIDLib::TCard4 c4ExecFlags = kCIDBuild::c4ExecFlag_None;
if (facCIDBuild.bLowPrio())
c4ExecFlags |= kCIDBuild::c4ExecFlag_LowPrio;
if (!TUtils::bExec(apszArgs, c4ArgCnt, c4ErrCode, c4ExecFlags))
{
stdOut << L"Could not execute the compiler" << kCIDBuild::EndLn;
return kCIDLib::False;
}
if (c4ErrCode)
return kCIDLib::False;
// Make sure we have a line after the output if in verbose mode
if (facCIDBuild.bVerbose())
stdOut << kCIDBuild::EndLn;
return kCIDLib::True;
}
tCIDLib::TBoolean TVCppDriver::bCompileCpps()
{
TBldStr strTmp;
//
// First we want to build up the list of command line parameters that
// will be used to compile a Cpp file. For our Visual C++ compiler, the
// order of stuff is not important, so we can just build up the stuff
// that will stay the same.
//
// Some of the strings have to be allocated, so we also have a flag
// array to remember which ones.
//
const tCIDLib::TCard4 c4MaxParms = 256;
tCIDLib::TBoolean abDynAlloc[c4MaxParms];
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4MaxParms; c4Index++)
abDynAlloc[c4Index] = kCIDLib::False;
const tCIDLib::TCh* apszArgs[c4MaxParms];
tCIDLib::TCard4 c4CurArg = 0;
apszArgs[c4CurArg++] = L"CL.Exe";
apszArgs[c4CurArg++] = L"/c";
apszArgs[c4CurArg++] = L"/EHa"; // Needed for /GR+
apszArgs[c4CurArg++] = L"/GR"; // Enable RTTI
apszArgs[c4CurArg++] = L"/DSTRICT";
apszArgs[c4CurArg++] = L"/nologo";
apszArgs[c4CurArg++] = L"/DWIN32";
apszArgs[c4CurArg++] = L"/Zp8"; // Pack on 8 bytes unless forced otherwise
//
// Now that we are enabling pre-compiled headers, this seems to be an issue
// though in theory it's ok.
//
/*
TBldStr strMP = L"/MP";
if (!facCIDBuild.bLowPrio() && !facCIDBuild.bSingle())
{
tCIDLib::TCard4 c4Count = facCIDBuild.c4CPUCount();
if (c4Count > 1)
c4Count >>= 1;
strMP.Append(c4Count);
apszArgs[c4CurArg++] = strMP.pszBuffer();
}
*/
//
// Enable SSE2 support which should be available on anything that CIDLib based apps
// would run on these days. We cannot enable /fp:fast because we enable strict
// ANSI for all facilities that are not explicitly marked as not being compliant,
// and fast mode is not ANSI compliant.
//
apszArgs[c4CurArg++] = L"/arch:SSE2";
//
// We always want wchar_t to be an intrinsic type and to use the UNICODE version
// of all of the system APIs.
//
apszArgs[c4CurArg++] = L"/Zc:wchar_t";
apszArgs[c4CurArg++] = L"/DUNICODE";
apszArgs[c4CurArg++] = L"/D_UNICODE";
//
// Set some stuff according to the platforms we support. These are used
// by the system headers, and a little bit of code in our Win32 platform
// specific driver code, where we have to call slightly different APIs
// according to targeted platform.
//
if (facCIDBuild.strFullPlatform().bIEquals(L"WIN32_WIN7"))
{
apszArgs[c4CurArg++] = L"/DNTDDI_VERSION=NTDDI_WIN7";
}
else
{
stdOut << facCIDBuild.strFullPlatform()
<< L" is not a platform understood by the VC++ driver" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::BuildError;
}
// If a service, support conditional compilation for that
if (m_pprojiTarget->eType() == tCIDBuild::EProjTypes::Service)
apszArgs[c4CurArg++] = L"/DCIDSERVICE";
// Set either normal or maximum warning level
if (facCIDBuild.bMaxWarn())
apszArgs[c4CurArg++] = L"/W4";
else
apszArgs[c4CurArg++] = L"/W3";
// For libraries we do some extra bits
if ((m_pprojiTarget->eType() == tCIDBuild::EProjTypes::SharedLib)
|| (m_pprojiTarget->eType() == tCIDBuild::EProjTypes::SharedObj))
{
apszArgs[c4CurArg++] = L"/D_WINDOWS";
apszArgs[c4CurArg++] = L"/LD";
}
// Set up the debug/prod flags
if (m_bDebug)
{
apszArgs[c4CurArg++] = L"/Od";
apszArgs[c4CurArg++] = L"/D_DEBUG";
apszArgs[c4CurArg++] = L"/Zi";
apszArgs[c4CurArg++] = L"/RTC1";
// If asked, invoke code analysis
if (facCIDBuild.eCodeAnalysis() != tCIDBuild::EAnalysisLevels::None)
{
TBldStr* pstrRules = new TBldStr(L"/analyze:ruleset\"");
pstrRules->Append(facCIDBuild.strCIDLibSrcDir());
if (facCIDBuild.eCodeAnalysis() == tCIDBuild::EAnalysisLevels::Level1)
{
pstrRules->Append(L"Source\\Cmd\\Win32\\Standard.ruleset\"");
}
else if (facCIDBuild.eCodeAnalysis() == tCIDBuild::EAnalysisLevels::Level2)
{
pstrRules->Append(L"Source\\Cmd\\Win32\\Standard2.ruleset\"");
}
else if (facCIDBuild.eCodeAnalysis() == tCIDBuild::EAnalysisLevels::Temp)
{
pstrRules->Append(L"Source\\Cmd\\Win32\\Temp.ruleset\"");
}
else
{
stdOut << L"Unknown code analysis level" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::BuildError;
}
apszArgs[c4CurArg++] = pstrRules->pszBuffer();
// And tell it the analysis plugin to use, which it doesn't seem to do on its own
apszArgs[c4CurArg++] = L"/analyze:plugin";
apszArgs[c4CurArg++] = L"EspXEngine.dll";
}
}
else
{
//
// Enable plenty of optimization
///
apszArgs[c4CurArg++] = L"/O2";
apszArgs[c4CurArg++] = L"/DNDEBUG";
}
//
// If a pure ANSI project, then disable extension. This is temporary
// until all per-platform stuff is split out into per-platfrom dirs.
//
if (m_pprojiTarget->bPureCpp())
apszArgs[c4CurArg++] = L"/Za";
//
// Turn off the permissive mode which allows a bunch of non-conforming
// behavior that will be non-portable.
//
apszArgs[c4CurArg++] = L"/permissive-";
// For now always build in C++17 mode
apszArgs[c4CurArg++] = L"/std:c++17";
//
// Set the version defines. This passes the release version info from the
// build environment on to the stuff compiled, so that they can use them
// if they want (and most do.)
//
TBldStr strMajVer(L"/DCID_MAJVER=");
strTmp.Format(facCIDBuild.c4MajVer());
strMajVer.Append(strTmp);
apszArgs[c4CurArg++] = strMajVer.pszBuffer();
TBldStr strMinVer(L"/DCID_MINVER=");
strTmp.Format(facCIDBuild.c4MinVer());
strMinVer.Append(strTmp);
apszArgs[c4CurArg++] = strMinVer.pszBuffer();
TBldStr strRevision(L"/DCID_REVISION=");
strTmp.Format(facCIDBuild.c4Revision());
strRevision.Append(strTmp);
apszArgs[c4CurArg++] = strRevision.pszBuffer();
TBldStr strVerString(L"/DCID_VERSTRING=");
strTmp.Format(facCIDBuild.c4MajVer());
strVerString.Append(strTmp);
strVerString.Append(L".");
strTmp.Format(facCIDBuild.c4MinVer());
strVerString.Append(strTmp);
strVerString.Append(L".");
strTmp.Format(facCIDBuild.c4Revision());
strVerString.Append(strTmp);
apszArgs[c4CurArg++] = strVerString.pszBuffer();
TBldStr strVerSuff(L"/DCID_VERSUFF=");
strVerSuff.Append(facCIDBuild.strVersionSuffix());
apszArgs[c4CurArg++] = strVerSuff.pszBuffer();
//
// Set up our standard include directories, for public and private
// includes and their respective per-platform subdirectories
//
TBldStr strInclude(L"/I");
strInclude.Append(facCIDBuild.strIncludeDir());
apszArgs[c4CurArg++] = strInclude.pszBuffer();
TBldStr strPPInclude(L"/I");
strPPInclude.Append(facCIDBuild.strPPIncludeDir());
apszArgs[c4CurArg++] = strPPInclude.pszBuffer();
TBldStr strPrivInclude(L"/I");
strPrivInclude.Append(facCIDBuild.strPrivIncludeDir());
apszArgs[c4CurArg++] = strPrivInclude.pszBuffer();
TBldStr strPPPrivInclude(L"/I");
strPPPrivInclude.Append(facCIDBuild.strPPPrivIncludeDir());
apszArgs[c4CurArg++] = strPPPrivInclude.pszBuffer();
// If there are any per-project include paths, then add them in as well.
if (m_pprojiTarget->listIncludePaths().c4ElemCount())
{
TList<TBldStr>::TCursor cursIncludePaths(&m_pprojiTarget->listIncludePaths());
cursIncludePaths.bResetIter();
do
{
tCIDLib::TCh* pszNew = new tCIDLib::TCh
[
TRawStr::c4StrLen(cursIncludePaths.tCurElement().pszBuffer()) + 16
];
TRawStr::CopyStr(pszNew, L"/I");
TRawStr::CatStr(pszNew, cursIncludePaths.tCurElement().pszBuffer());
abDynAlloc[c4CurArg] = kCIDLib::True;
apszArgs[c4CurArg++] = pszNew;
} while (cursIncludePaths.bNext());
}
// And do the same for any system wide includes
if (facCIDBuild.listExtIncludePaths().c4ElemCount())
{
TList<TBldStr>::TCursor cursIncludePaths(&facCIDBuild.listExtIncludePaths());
cursIncludePaths.bResetIter();
do
{
tCIDLib::TCh* pszNew = new tCIDLib::TCh
[
TRawStr::c4StrLen(cursIncludePaths.tCurElement().pszBuffer()) + 8
];
TRawStr::CopyStr(pszNew, L"/I");
TRawStr::CatStr(pszNew, cursIncludePaths.tCurElement().pszBuffer());
abDynAlloc[c4CurArg] = kCIDLib::True;
apszArgs[c4CurArg++] = pszNew;
} while (cursIncludePaths.bNext());
}
//
// Set up the flags for the runtime library mode. We always do multi-threaded
// dynamic linking.
//
if (m_bDebug)
apszArgs[c4CurArg++] = L"/MDd";
else
apszArgs[c4CurArg++] = L"/MD";
//
// Set the parameters for the display type. Under Visual C++ we just
// need to indicate if it is a console, otherwise its assumed to be
// a GUI display.
//
if (m_pprojiTarget->eDisplayType() == tCIDBuild::EDisplayTypes::Console)
apszArgs[c4CurArg++] = L"/D_CONSOLE";
//
// Every project has a define which is in the form PROJ_XXX, where XXX
// is the name of the project uppercased.
//
TBldStr strProjDef(L"/DPROJ_");
strProjDef.Append(m_pprojiTarget->strProjectName());
strProjDef.UpperCase();
apszArgs[c4CurArg++] = strProjDef.pszBuffer();
//
// Set up the debug database. Let the compiler choose the name to
// avoid weirdness that showed up in 2019, where compiler and linker
// could use the same name if we name this one in the way we normally
// would. Then the linker overwrites the compiler one which then doesn't
// match the PCH's version, which causes a mess.
//
TBldStr strPDBName(L"/Fd");
strPDBName.Append(facCIDBuild.strOutDir());
apszArgs[c4CurArg++] = strPDBName.pszBuffer();
// Set up the Obj output directory param
TBldStr strOutDir(L"/Fo");
strOutDir.Append(m_pprojiTarget->strOutDir());
if (strOutDir.chLast() == kCIDBuild::chPathSep)
apszArgs[c4CurArg++] = strOutDir.pszBuffer();
//
// And now check each Cpp file and see if we have to build it. If so
// add it to a list of files to comiler.
//
tCIDLib::TBoolean bBuildErr = kCIDLib::False;
TList<TBldStr> listToBuild;
TList<TDepInfo>::TCursor cursCpps(&listCpps());
if (cursCpps.bResetIter())
{
do
{
const TDepInfo& depiCur = cursCpps.tCurElement();
if (bMustCompile(*m_pprojiTarget, depiCur))
listToBuild.Add(new TBldStr(depiCur.strFileName()));
} while (cursCpps.bNext());
if (!listToBuild.bEmpty())
{
// See if PCH's are disabled
tCIDLib::TBoolean bDoPCH(m_pprojiTarget->pkvpFindOption(L"NOPCH") == nullptr);
// Build up the name of the header that will drive them
TBldStr strPCHHeader = m_pprojiTarget->strProjectName().pszBuffer();
if (m_pprojiTarget->eType() == tCIDBuild::EProjTypes::SharedLib)
strPCHHeader.Append(L'_');
strPCHHeader.Append(L".hpp");
//
// Build the name of the main cpp file that we will use to create the
// precompiled headers.
//
TBldStr strPCHCpp = m_pprojiTarget->strProjectName().pszBuffer();
strPCHCpp.Append(L".cpp");
// If that doesn't exist, then no PCH
if (!TUtils::bExists(strPCHHeader))
{
bDoPCH = kCIDLib::False;
if (facCIDBuild.bVerbose())
stdOut << L"!!Precompiled header was not found" << kCIDBuild::EndLn;
}
// This one gets passed to all but the main cpp file
TBldStr strPCHUse = L"/Yu";
strPCHUse.Append(strPCHHeader);
// This is used for just the main cpp file
TBldStr strPCHCreate = L"/Yc";
strPCHCreate.Append(strPCHHeader);
// The actual PCH file we want to create and use. It's always included
TBldStr strPCHFile = L"/Fp";
strPCHFile.Append(m_pprojiTarget->strOutDir());
strPCHFile.AppendPathComp(m_pprojiTarget->strProjectName().pszBuffer());
strPCHFile.Append(L".pch");
TList<TBldStr>::TCursor cursBuildList(&listToBuild);
cursBuildList.bResetIter();
do
{
const TBldStr& strCurFl = cursBuildList.tCurElement();
// Reset our per-file options index
tCIDLib::TCard4 c4RealCnt = c4CurArg;
if (bDoPCH)
{
// We have a few .c files that we need to skip, so only do cpp files
const tCIDLib::TCh* pszExt = TRawStr::pszFindChar(strCurFl.pszBuffer(), L'.');
if (!TRawStr::iCompIStr(pszExt, L".cpp"))
{
// Either create or use the precompiled headers
if (*cursBuildList == strPCHCpp)
apszArgs[c4RealCnt++] = strPCHCreate.pszBuffer();
else
apszArgs[c4RealCnt++] = strPCHUse.pszBuffer();
// The PCH file we either use or create
apszArgs[c4RealCnt++] = strPCHFile.pszBuffer();
}
}
// Add the current file as the target to compile
apszArgs[c4RealCnt++] = strCurFl.pszBuffer();
tCIDLib::TCard4 c4ErrCode = 0;
if (!bCompileOne(apszArgs, c4RealCnt, c4ErrCode))
{
stdOut << L"Failed compilation of target: "
<< strCurFl << L". Error Code: "
<< c4ErrCode << kCIDBuild::EndLn;
bBuildErr = kCIDLib::True;
}
} while (cursBuildList.bNext());
}
}
// Delete any dynamically allocated parameters
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4MaxParms; c4Index++)
{
if (abDynAlloc[c4Index])
delete [] apszArgs[c4Index];
}
if (bBuildErr)
throw tCIDBuild::EErrors::BuildError;
// REturn true if we built something
return !listToBuild.bEmpty();
}
// Builds any defined shader files, which for now are assumed to be for Vulkan
tCIDLib::TBoolean TVCppDriver::bCompileShaders()
{
TBldStr strTmp;
// Loop through all of the shader files and invoke glslc for each
TList<TBldStr>::TCursor cursShaders(&m_pprojiTarget->listShaders());
if (!cursShaders.bResetIter())
return kCIDLib::True;
constexpr tCIDLib::TCard4 c4MaxArgs = 8;
const tCIDLib::TCh* apszArgs[c4MaxArgs] = { nullptr };
do
{
// Build up the path to the source and destination files
TBldStr strSrc = m_pprojiTarget->strProjectDir();
strSrc.AppendPathComp(cursShaders->pszBuffer());
TBldStr strDest = m_pprojiTarget->strOutDir();
strDest.AppendPathComp(m_pprojiTarget->strProjectName().pszBuffer());
tCIDLib::TCard4 c4NameOfs = 0, c4ExtOfs = 0;
TUtils::FindPathParts(strSrc, c4NameOfs, c4ExtOfs);
if (c4ExtOfs != kCIDBuild::c4NotFound)
{
strDest.Append(&strSrc.pszBuffer()[c4ExtOfs]);
}
tCIDLib::TCard4 c4ArgCnt = 0;
apszArgs[c4ArgCnt++] = L"glslc.exe";
apszArgs[c4ArgCnt++] = strSrc.pszBuffer();
apszArgs[c4ArgCnt++] = L"-o";
apszArgs[c4ArgCnt++] = strDest.pszBuffer();
if (c4ArgCnt > c4MaxArgs)
throw tCIDBuild::EErrors::IndexError;
if (facCIDBuild.bVerbose() )
{
stdOut << L" ";
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4ArgCnt; c4Index++)
{
stdOut << apszArgs[c4Index] << L" ";
}
stdOut << kCIDBuild::EndLn;
}
tCIDLib::TCard4 c4ErrCode = 0;
if (!TUtils::bExec(apszArgs, c4ArgCnt, c4ErrCode, kCIDBuild::c4ExecFlag_None))
{
stdOut << L"Could not compile shader file: "
<< strSrc
<< kCIDBuild::EndLn;
return kCIDLib::False;
}
} while (cursShaders.bNext());
return kCIDLib::True;
}
tCIDLib::TBoolean TVCppDriver::bLibsNewer(const TFindInfo& fndiTarget) const
{
// Get a cursor for the libs list
TList<TFindInfo>::TCursor cursLibs(&listLibs());
// If no libs listed, then couldn't be newer
if (!cursLibs.bResetIter())
return kCIDLib::False;
do
{
//
// See if this Lib file is newer than the target. If so, then
// return kCIDLib::True, since we only have to find one to know that we
// have to relink.
//
if (cursLibs.tCurElement() > fndiTarget)
{
if (facCIDBuild.bVerbose())
{
stdOut << L" Dependent library is newer: "
<< cursLibs.tCurElement().strFileName() << kCIDBuild::EndLn;
}
return kCIDLib::True;
}
} while (cursLibs.bNext());
return kCIDLib::False;
}
tCIDLib::TBoolean TVCppDriver::bObjsNewer(const TFindInfo& fndiTarget) const
{
// Get a cursor for the Cpp list
TList<TDepInfo>::TCursor cursCpps(&listCpps());
// If no obect files listed, then couldn't be newer
if (!cursCpps.bResetIter())
return kCIDLib::False;
TFindInfo fndiTmp;
do
{
// Get a ref to the current element
const TDepInfo& depiCur = cursCpps.tCurElement();
// Try to find the current obj
if (!TFindInfo::bFindAFile(depiCur.strObjFileName(), fndiTmp))
{
stdOut << L"Could not find object file: "
<< depiCur.strObjFileName() << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::NotFound;
}
//
// See if the Obj file is newer than the target. If so, then
// return kCIDLib::True, since we only have to find one to know that we
// have to relink.
//
if (fndiTmp > fndiTarget)
{
if (facCIDBuild.bVerbose())
{
stdOut << L" Object file is newer: "
<< depiCur.strObjFileName() << kCIDBuild::EndLn;
}
return kCIDLib::True;
}
} while (cursCpps.bNext());
return kCIDLib::False;
}
tCIDLib::TVoid TVCppDriver::Link(const tCIDLib::TBoolean bHaveResFile)
{
const tCIDLib::TCard4 c4MaxParms(128);
const tCIDLib::TCh* apszArgs[c4MaxParms];
tCIDLib::TCard4 c4CurArg = 0;
TBldStr strTmp;
// Set up the standard stuff
apszArgs[c4CurArg++] = L"Link.Exe";
apszArgs[c4CurArg++] = L"/nologo";
apszArgs[c4CurArg++] = L"/machine:X86";
// apszArgs[c4CurArg++] = L"/NODEFAULTLIB:LIBCMT";
//
// Set up the map file output. If this is a versioned project, then
// add the version postfix.
//
TBldStr strMap(L"/map:");
strMap.Append(m_pprojiTarget->strProjectName());
if (m_pprojiTarget->bVersioned())
strMap.Append(facCIDBuild.strVersionSuffix());
strMap.Append(L".map");
apszArgs[c4CurArg++] = strMap.pszBuffer();
// Set up the output file.
TBldStr strOut(L"/out:");
strOut.Append(m_strTargetFile);
apszArgs[c4CurArg++] = strOut.pszBuffer();
// Set flags based on the type of the program
if ((m_pprojiTarget->eType() == tCIDBuild::EProjTypes::Executable)
|| (m_pprojiTarget->eType() == tCIDBuild::EProjTypes::Service))
{
if (m_pprojiTarget->eDisplayType() == tCIDBuild::EDisplayTypes::Console)
apszArgs[c4CurArg++] = L"/subsystem:console";
else
apszArgs[c4CurArg++] = L"/subsystem:windows";
}
else if ((m_pprojiTarget->eType() == tCIDBuild::EProjTypes::SharedLib)
|| (m_pprojiTarget->eType() == tCIDBuild::EProjTypes::SharedObj))
{
apszArgs[c4CurArg++] = L"/dll";
//
// In libraries, force retension of unreferenced functions because
// they may be needed in the field later, if not now.
//
apszArgs[c4CurArg++] = L"/OPT:NOREF";
}
// Don't generate a manifest
apszArgs[c4CurArg++] = L"/MANIFEST:NO";
// And the debug vs. production flags
if (m_bDebug)
apszArgs[c4CurArg++] = L"/DEBUG";
// Set the PDB to force it into the output directory
TBldStr strPDBName(L"/pdb:");
strPDBName.Append(facCIDBuild.strOutDir());
strPDBName.Append(m_pprojiTarget->strProjectName());
if (m_pprojiTarget->bVersioned())
strPDBName.Append(facCIDBuild.strVersionSuffix());
strPDBName.Append(L".pdb");
apszArgs[c4CurArg++] = strPDBName.pszBuffer();
//
// See if this one needs the underlying standard system libraries. If
// so, then add them in as a single parameter. Anything beyond these basic
// libraries will be done by pragmas in the system API wrapper classes.
//
if (m_pprojiTarget->bUseSysLibs())
{
apszArgs[c4CurArg++] = L"kernel32.lib";
apszArgs[c4CurArg++] = L"user32.lib";
apszArgs[c4CurArg++] = L"advapi32.lib";
apszArgs[c4CurArg++] = L"ole32.lib";
apszArgs[c4CurArg++] = L"oleaut32.lib";
}
//
// If the 'VARARGS' settings is on, then we have to link the SetArgV.obj
// file into the target.
//
if (m_pprojiTarget->bVarArgs())
apszArgs[c4CurArg++] = L"SetArgV.obj";
// If this project has a resource file, then add it to the list
TBldStr strResFile;
if (bHaveResFile)
{
strResFile = m_pprojiTarget->strProjectName();
strResFile.Append(L".res");
apszArgs[c4CurArg++] = strResFile.pszBuffer();
}
// Add in all of the library files that are from dependent projects.
TList<TFindInfo>::TCursor cursLibs(&listLibs());
if (cursLibs.bResetIter())
{
do
{
apszArgs[c4CurArg++] = cursLibs.tCurElement().strFileName().pszBuffer();
} while (cursLibs.bNext());
}
// Add in all of the per-project external library files
TList<TBldStr>::TCursor cursExtLibs(&m_pprojiTarget->listExtLibs());
if (cursExtLibs.bResetIter())
{
do
{
apszArgs[c4CurArg++] = cursExtLibs.tCurElement().pszDupBuffer();
} while (cursExtLibs.bNext());
}
// And do the same for any system wide libs
TList<TBldStr>::TCursor cursSysExtLibs(&facCIDBuild.listExtLibs());
if (cursSysExtLibs.bResetIter())
{
do
{
apszArgs[c4CurArg++] = cursSysExtLibs.tCurElement().pszDupBuffer();
} while (cursSysExtLibs.bNext());
}
// And do system wide lib paths
TList<TBldStr>::TCursor cursSysExtLibPaths(&facCIDBuild.listExtLibPaths());
if (cursSysExtLibPaths.bResetIter())
{
do
{
strTmp = L"/LIBPATH:";
strTmp.Append(cursSysExtLibPaths.tCurElement());
apszArgs[c4CurArg++] = strTmp.pszDupBuffer();
} while (cursSysExtLibPaths.bNext());
}
//
// All all of the Obj files that we've already built. Remember this
// argument index, in case of verbose logging below.
//
const tCIDLib::TCard4 c4ObjStartInd = c4CurArg;
TList<TDepInfo>::TCursor cursCpps(&listCpps());
if (cursCpps.bResetIter())
{
do
{
// Get a ref to the current element
const TDepInfo& depiCur = cursCpps.tCurElement();
// And add its object file name to the list of args
apszArgs[c4CurArg++] = depiCur.strObjFileName().pszBuffer();
} while (cursCpps.bNext());
}
if (facCIDBuild.bVerbose())
{
tCIDLib::TCard4 c4Ind;
for (c4Ind = 0; c4Ind < c4ObjStartInd; c4Ind++)
stdOut << apszArgs[c4Ind] << L" ";
stdOut << L"\n";
for (; c4Ind < c4CurArg; c4Ind++)
stdOut << L" " << apszArgs[c4Ind] << L"\n";
stdOut << kCIDBuild::EndLn;
}
// And invoke the link
tCIDLib::TCard4 c4Result;
tCIDLib::TCard4 c4ExecFlags = kCIDBuild::c4ExecFlag_None;
if (facCIDBuild.bLowPrio())
c4ExecFlags |= kCIDBuild::c4ExecFlag_LowPrio;
if (!TUtils::bExec(apszArgs, c4CurArg, c4Result, c4ExecFlags))
{
stdOut << L"Could not execute the linker" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::BuildError;
}
if (c4Result)
{
stdOut << L"Link step failed. Error Code:" << c4Result << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::BuildError;
}
}
tCIDLib::TVoid TVCppDriver::LinkStatic()
{
//
// In this case, we want to run the Lib utility on all of the obj files
// and output them to the correct output file.
//
const tCIDLib::TCh* apszArgs[128];
tCIDLib::TCard4 c4CurArg = 0;
// Set up the standard stuff
apszArgs[c4CurArg++] = L"Lib.Exe";
apszArgs[c4CurArg++] = L"/nologo";
TBldStr strOut(L"/Out:");
strOut.Append(m_strTargetFile);
apszArgs[c4CurArg++] = strOut.pszBuffer();
//
// All all of the Obj files that we've already built. Remember this
// argument index, in case of verbose logging below.
//
const tCIDLib::TCard4 c4ObjStartInd = c4CurArg;
TList<TDepInfo>::TCursor cursCpps(&listCpps());
if (cursCpps.bResetIter())
{
do
{
// Get a ref to the current element
const TDepInfo& depiCur = cursCpps.tCurElement();
// And add its object file name to the list of args
apszArgs[c4CurArg++] = depiCur.strObjFileName().pszBuffer();
} while (cursCpps.bNext());
}
if (facCIDBuild.bVerbose())
{
tCIDLib::TCard4 c4Ind;
for (c4Ind = 0; c4Ind < c4ObjStartInd; c4Ind++)
stdOut << apszArgs[c4Ind] << L" ";
stdOut << L"\n";
for (; c4Ind < c4CurArg; c4Ind++)
stdOut << L" " << apszArgs[c4Ind] << L"\n";
stdOut << kCIDBuild::EndLn;
}
// And invoke the link
tCIDLib::TCard4 c4ExecFlags = kCIDBuild::c4ExecFlag_None;
if (facCIDBuild.bLowPrio())
c4ExecFlags |= kCIDBuild::c4ExecFlag_LowPrio;
tCIDLib::TCard4 c4Result;
if (!TUtils::bExec(apszArgs, c4CurArg, c4Result, c4ExecFlags))
{
stdOut << L"Could not execute the librarian" << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::BuildError;
}
if (c4Result)
{
stdOut << L"Librarian step failed. Error Code:" << c4Result << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::BuildError;
}
}
| 33.67471 | 98 | 0.586487 | [
"object"
] |
d3386b22fbbca4bb131c7ca26e1b225974b7b254 | 1,739 | hpp | C++ | mainapp/Classes/Games/ComprehensionTest/Reordering/ReorderingScene.hpp | JaagaLabs/GLEXP-Team-KitkitSchool | f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0 | [
"Apache-2.0"
] | 45 | 2019-05-16T20:49:31.000Z | 2021-11-05T21:40:54.000Z | mainapp/Classes/Games/ComprehensionTest/Reordering/ReorderingScene.hpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 10 | 2019-05-17T13:38:22.000Z | 2021-07-31T19:38:27.000Z | mainapp/Classes/Games/ComprehensionTest/Reordering/ReorderingScene.hpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 29 | 2019-05-16T17:49:26.000Z | 2021-12-30T16:36:24.000Z | //
// ReorderingScene.hpp
// KitkitSchool
//
// Created by HyeonGyu Yu on 20/12/2016.
//
//
#ifndef ReorderingScene_hpp
#define ReorderingScene_hpp
#include <stdio.h>
#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "../ComprehensionScene.hpp"
#include "ImageBlock.hpp"
#include "TextBlock.hpp"
#include <string>
USING_NS_CC;
using namespace std;
using namespace cocos2d::ui;
namespace ComprehensionTest
{
namespace Reordering
{
enum class GameType
{
None = -1,
Image,
Text,
};
class ReorderingScene : Layer
{
public:
bool init() override;
CREATE_FUNC(ReorderingScene);
static cocos2d::Layer* createLayer(ComprehensionScene *parent);
void onEnter() override;
private:
ComprehensionScene* _comprehensionScene;
//string _questionText;
vector<string> _itemVector;
Node* _gameNode;
vector<ImageBlock*> _imageSlots;
vector<TextBlock*> _textSlots;
GameType _currentType;
void initData();
void createImageSlots();
void createTextSlots(float wrapperNodeCorrectionY, float scaleFactor);
Node* createImageBlock(string imageFile);
Node* createTextBlock(int index, string text, float scaleFactor);
bool isSolved();
void onSolve();
void createFixedResources();
void determineItemType();
void drawBlocksByGameType();
void writePlayLog();
string makeWorkPath();
};
}
}
#endif /* ReorderingScene_hpp */
| 24.152778 | 82 | 0.580794 | [
"vector"
] |
d338cba0e36de955240d1cdf431329e0b56a495f | 1,018 | cpp | C++ | PAT1089.cpp | Geeks-Z/PAT | c02f08f11c4a628203f8d2dccbd7fecfc0943b34 | [
"MIT"
] | null | null | null | PAT1089.cpp | Geeks-Z/PAT | c02f08f11c4a628203f8d2dccbd7fecfc0943b34 | [
"MIT"
] | null | null | null | PAT1089.cpp | Geeks-Z/PAT | c02f08f11c4a628203f8d2dccbd7fecfc0943b34 | [
"MIT"
] | null | null | null | /*
* @Descripttion: 狼人杀-简单版
* @version: 1.0
* @Author: Geeks_Z
* @Date: 2021-05-06 15:28:15
* @LastEditors: Geeks_Z
* @LastEditTime: 2021-05-06 15:30:51
*/
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n + 1);
for (int i = 1; i <= n; i++)
cin >> v[i];
// 每个人说的数字保存在v数组中,i从1~n、j从i+1~n遍历,分别假设i和j是狼人
for (int i = 1; i <= n; i++)
{
for (int j = i + 1; j <= n; j++)
{
//a数组表示该人是狼人还是好人,等于1表示是好人,等于-1表示是狼人
vector<int> lie, a(n + 1, 1);
a[i] = a[j] = -1;
for (int k = 1; k <= n; k++)
//k从1~n分别判断k所说的话是真是假,k说的话和真实情况不同(即v[k] * a[abs(v[k])] < 0)
//则表示k在说谎,则将k放在lie数组中
if (v[k] * a[abs(v[k])] < 0)
lie.push_back(k);
//遍历完成后判断lie数组,如果说谎人数等于2并且这两个说谎的人一个是好人一个是狼人(即a[lie[0]] + a[lie[1]] == 0)
if (lie.size() == 2 && a[lie[0]] + a[lie[1]] == 0)
{
cout << i << " " << j;
return 0;
}
}
}
cout << "No Solution";
return 0;
} | 23.674419 | 78 | 0.5 | [
"vector"
] |
d33c914e6d5b227ab119861a58cd28ebcc30f555 | 10,644 | cc | C++ | tensorflow/dtensor/mlir/shape_utils.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | 3 | 2022-03-09T01:39:56.000Z | 2022-03-30T23:17:58.000Z | tensorflow/dtensor/mlir/shape_utils.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | 1 | 2020-08-01T05:40:12.000Z | 2020-08-01T05:40:12.000Z | tensorflow/dtensor/mlir/shape_utils.cc | TheRakeshPurohit/tensorflow | bee6d5a268122df99e1e55a7b92517e84ad25bab | [
"Apache-2.0"
] | 1 | 2022-03-22T00:45:15.000Z | 2022-03-22T00:45:15.000Z | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/dtensor/mlir/shape_utils.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
#include "mlir/IR/Builders.h" // from @llvm-project
#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "mlir/IR/Location.h" // from @llvm-project
#include "mlir/IR/MLIRContext.h" // from @llvm-project
#include "mlir/IR/OperationSupport.h" // from @llvm-project
#include "mlir/IR/Value.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/utils/shape_inference_utils.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/dtensor/cc/constants.h"
#include "tensorflow/dtensor/mlir/ir/tf_dtensor.h"
#include "tensorflow/dtensor/mlir/value_utils.h"
namespace tensorflow {
namespace dtensor {
StatusOr<llvm::ArrayRef<int64_t>> ExtractGlobalInputShape(
mlir::OpOperand& input_value) {
const int operand_index = input_value.getOperandNumber();
auto input_defining_op = input_value.get().getDefiningOp();
if (input_defining_op) {
if (auto layout_op =
llvm::dyn_cast<mlir::TF::DTensorLayout>(input_defining_op)) {
auto global_shape = layout_op.global_shape();
if (!global_shape)
return errors::Internal("global_shape does not have static rank");
return *global_shape;
}
return ExtractGlobalOutputShape(input_value.get().cast<mlir::OpResult>());
}
// If we reach this point, we're working with a function argument.
auto op = input_value.getOwner();
auto enclosing_function = op->getParentOfType<mlir::func::FuncOp>();
if (!enclosing_function)
return errors::InvalidArgument(
llvm::formatv("Could not find global shape of {0}-th input to op: {1}",
operand_index, op->getName())
.str());
auto block_arg = input_value.get().dyn_cast<mlir::BlockArgument>();
auto global_shape_attr =
enclosing_function.getArgAttrOfType<mlir::TF::ShapeAttr>(
block_arg.getArgNumber(), kGlobalShapeDialectAttr);
if (!global_shape_attr)
return errors::InvalidArgument(
"`tf._global_shape` attribute of operation not found.");
return global_shape_attr.getShape();
}
StatusOr<llvm::ArrayRef<int64_t>> ExtractGlobalOutputShape(
mlir::OpResult result_value) {
auto op = result_value.getOwner();
const int output_index = result_value.getResultNumber();
if (op->getOpResult(output_index).hasOneUse()) {
auto user = op->getOpResult(output_index).getUses().begin().getUser();
if (auto layout_op = mlir::dyn_cast<mlir::TF::DTensorLayout>(user)) {
auto global_shape = layout_op.global_shape();
if (!global_shape)
return errors::Internal("global_shape does not have static rank");
return *global_shape;
}
}
auto global_shape_attr = op->getAttrOfType<mlir::ArrayAttr>(kGlobalShape);
if (!global_shape_attr)
return errors::InvalidArgument(
"`_global_shape` attribute of operation not found.");
const int num_results = op->getNumResults();
assert(global_shape_attr.size() == num_results);
if (output_index >= op->getNumResults())
return errors::InvalidArgument(
llvm::formatv("Requested global shape of {0} output but op has only "
"{1} return values.",
output_index, num_results)
.str());
auto shape_attr = global_shape_attr[output_index];
return shape_attr.cast<mlir::TF::ShapeAttr>().getShape();
}
namespace {
// Extracts attributes from a MLIR operation, including derived attributes, into
// one NamedAttrList.
mlir::NamedAttrList GetAllAttributesFromOperation(mlir::Operation* op) {
mlir::NamedAttrList attr_list;
attr_list.append(op->getAttrDictionary().getValue());
if (auto derived = llvm::dyn_cast<mlir::DerivedAttributeOpInterface>(op)) {
auto materialized = derived.materializeDerivedAttributes();
attr_list.append(materialized.getValue());
}
return attr_list;
}
// Infers output shape of `op` given its local operand shape. For shape
// inference function that requires input operation to be a constant, if input
// operation is `DTensorLayout` op, then we use input of DTensorLayout op
// instead for correct constant matching.
mlir::LogicalResult InferShapeOfTFOpWithCustomOperandConstantFn(
llvm::Optional<mlir::Location> location, mlir::Operation* op,
int64_t graph_version,
llvm::SmallVectorImpl<mlir::ShapedTypeComponents>& inferred_return_shapes) {
if (auto type_op = llvm::dyn_cast<mlir::InferTypeOpInterface>(op)) {
auto attributes = GetAllAttributesFromOperation(op);
llvm::SmallVector<mlir::Type, 4> inferred_return_types;
auto result = type_op.inferReturnTypes(
op->getContext(), location, op->getOperands(),
mlir::DictionaryAttr::get(op->getContext(), attributes),
op->getRegions(), inferred_return_types);
if (failed(result)) return mlir::failure();
inferred_return_shapes.resize(inferred_return_types.size());
for (const auto& inferred_return_type :
llvm::enumerate(inferred_return_types)) {
if (auto shaped_type =
inferred_return_type.value().dyn_cast<mlir::ShapedType>()) {
if (shaped_type.hasRank()) {
inferred_return_shapes[inferred_return_type.index()] =
mlir::ShapedTypeComponents(shaped_type.getShape(),
shaped_type.getElementType());
} else {
inferred_return_shapes[inferred_return_type.index()] =
mlir::ShapedTypeComponents(shaped_type.getElementType());
}
}
}
return mlir::success();
}
if (auto shape_type_op =
llvm::dyn_cast<mlir::InferShapedTypeOpInterface>(op)) {
auto attributes = GetAllAttributesFromOperation(op);
return shape_type_op.inferReturnTypeComponents(
op->getContext(), location, op->getOperands(),
mlir::DictionaryAttr::get(op->getContext(), attributes),
op->getRegions(), inferred_return_shapes);
}
// If `operand` is from DTensorLayout op, use input value of DTensorLayout op
// instead.
auto operand_as_constant_fn = [](mlir::Value operand) -> mlir::Attribute {
while (auto input_op = llvm::dyn_cast_or_null<mlir::TF::DTensorLayout>(
operand.getDefiningOp())) {
operand = input_op.input();
}
mlir::Attribute attr;
if (matchPattern(operand, m_Constant(&attr))) return attr;
return nullptr;
};
auto op_result_as_shape_fn =
[](shape_inference::InferenceContext& ic,
mlir::OpResult op_result) -> shape_inference::ShapeHandle {
auto rt = op_result.getType().dyn_cast<mlir::RankedTensorType>();
if (!rt || rt.getRank() != 1 || !rt.hasStaticShape()) return {};
std::vector<shape_inference::DimensionHandle> dims(rt.getDimSize(0),
ic.UnknownDim());
mlir::Attribute attr;
if (matchPattern(op_result, m_Constant(&attr))) {
auto elements = attr.dyn_cast<mlir::DenseIntElementsAttr>();
if (elements)
for (const auto& element :
llvm::enumerate(elements.getValues<llvm::APInt>()))
dims[element.index()] = ic.MakeDim(element.value().getSExtValue());
}
return ic.MakeShape(dims);
};
auto result_element_type_fn = [](int) -> mlir::Type { return nullptr; };
return mlir::TF::InferReturnTypeComponentsForTFOp(
location, op, graph_version, operand_as_constant_fn,
op_result_as_shape_fn, result_element_type_fn, inferred_return_shapes);
}
} // namespace
mlir::Operation* InferSPMDExpandedLocalShape(mlir::Operation* op) {
llvm::SmallVector<mlir::ShapedTypeComponents, 4> inferred_return_types;
(void)InferShapeOfTFOpWithCustomOperandConstantFn(
op->getLoc(), op, TF_GRAPH_DEF_VERSION, inferred_return_types);
assert(inferred_return_types.size() == op->getNumResults());
for (auto it : llvm::zip(inferred_return_types, op->getOpResults())) {
const auto& return_type = std::get<0>(it);
auto& op_result = std::get<1>(it);
const auto element_type =
op_result.getType().cast<mlir::TensorType>().getElementType();
if (return_type.hasRank()) {
op_result.setType(
mlir::RankedTensorType::get(return_type.getDims(), element_type));
} else {
op_result.setType(mlir::UnrankedTensorType::get(element_type));
}
}
return op;
}
StatusOr<llvm::ArrayRef<int64_t>> GetShapeOfValue(const mlir::Value& value,
bool fail_on_dynamic) {
// Getting the subtype or self allows supporting extracting the underlying
// shape that variant or resource tensors point to.
mlir::Type type = GetSubtypeOrSelf(value);
if (auto ranked_type = type.dyn_cast<mlir::RankedTensorType>()) {
if (ranked_type.hasStaticShape() || !fail_on_dynamic)
return ranked_type.getShape();
else
return errors::InvalidArgument("value shape is not static");
}
return errors::InvalidArgument("value type is not a RankedTensorType");
}
StatusOr<llvm::ArrayRef<int64_t>> GetGlobalShapeOfValueFromDTensorLayout(
const mlir::Value& value) {
if (value.isa<mlir::OpResult>() &&
mlir::isa<mlir::TF::DTensorLayout>(value.getDefiningOp())) {
auto layout_op = mlir::cast<mlir::TF::DTensorLayout>(value.getDefiningOp());
if (layout_op.global_shape()) return layout_op.global_shape().getValue();
} else if (value.hasOneUse() &&
mlir::isa<mlir::TF::DTensorLayout>(*value.getUsers().begin())) {
auto layout_op =
mlir::cast<mlir::TF::DTensorLayout>(*value.getUsers().begin());
if (layout_op.global_shape()) return layout_op.global_shape().getValue();
}
return errors::InvalidArgument(
"consumer or producer of value is not a DTensorLayout");
}
} // namespace dtensor
} // namespace tensorflow
| 40.318182 | 80 | 0.691469 | [
"shape",
"vector"
] |
d33f7f91076596fb0d20cd51e3ffdfa9ee408f77 | 7,254 | cpp | C++ | libs/graph_parallel/drivers/gizmo.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | 1 | 2021-09-03T10:22:04.000Z | 2021-09-03T10:22:04.000Z | libs/graph_parallel/drivers/gizmo.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | libs/graph_parallel/drivers/gizmo.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.
// Boost Software License - Version 1.0 - August 17th, 2003
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// Authors: Thejaka Kanewala
// Andrew Lumsdaine
#include "./common/synthetic_generator.hpp"
#include "./common/graph_loader.hpp"
#include "./common/parser.hpp"
#include "gizmo/utils/utils.hpp"
#include "gizmo/utils/file_reader.hpp"
#include "gizmo/stats/stat.hpp"
#include "gizmo/applications/bfs.hpp"
#include "gizmo/models/machine/shared_memory.hpp"
#include "gizmo/models/machine/distributed_real.hpp"
#include "gizmo/models/machine/ram_machine.hpp"
#include <limits.h>
void* util::p_callback = NULL;
struct swo_1 {
public:
bool operator()(int i, int j) {
return (i < j);
}
};
//chaotic
struct swo_2 {
public:
bool operator()(int i, int j) {
return false;
}
};
//similar to delta
struct swo_3 {
public:
bool operator()(int i, int j) {
return ((i/3) < (j/3));
}
};
class test_buckets {
public:
void run_simple_integrated_tests() {
test_buckets tbuckets;
tbuckets.run_tests();
typedef boost::adjacency_list < boost::listS, boost::vecS, boost::directedS,
boost::no_property, boost::property < boost::edge_weight_t, int > > graph_t;
typedef std::pair<int, int> Edge;
const int num_nodes = 5;
Edge edge_array[] = { Edge(1, 3), Edge(2, 2), Edge(2, 4), Edge(2, 5),
Edge(3, 2), Edge(3, 4), Edge(4, 5), Edge(5, 1), Edge(5, 2)
};
int weights[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int num_arcs = sizeof(edge_array) / sizeof(Edge);
graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes);
stat_reader sr;
gizmo_config gizmocfg;
bfs_simulator< graph_t> bfssim;
bfssim.template simulate<chaotic_ordering_gen, distributed_real_machine_gen>(g, sr, gizmocfg);
}
void run_test_1() {
buckets<int, swo_1> all_buckets;
for (int i=0; i < 10; ++i) {
all_buckets.push(i);
}
buckets<int, swo_1>::bucket_iterator_t bbegin, bend;
int j = 0;
while(!all_buckets.empty()) {
std::tie(bbegin, bend) = all_buckets.top_bucket();
std::cout << "Bucket :" << j << " - {";
while (bbegin != bend) {
std::cout << *bbegin << ", ";
++bbegin;
}
std::cout << "}" << std::endl;
all_buckets.pop_bucket();
++j;
}
}
void run_test_2() {
buckets<int, swo_2> all_buckets;
for (int i=0; i < 10; ++i) {
all_buckets.push(i);
}
buckets<int, swo_1>::bucket_iterator_t bbegin, bend;
int j = 0;
while(!all_buckets.empty()) {
std::tie(bbegin, bend) = all_buckets.top_bucket();
std::cout << "Bucket :" << j << " - {";
while (bbegin != bend) {
std::cout << *bbegin << ", ";
++bbegin;
}
std::cout << "}" << std::endl;
all_buckets.pop_bucket();
++j;
}
//all_buckets.print_buckets();
}
void run_test_3() {
buckets<int, swo_3> all_buckets;
for (int i=0; i < 10; ++i) {
all_buckets.push(i);
}
buckets<int, swo_1>::bucket_iterator_t bbegin, bend;
int j = 0;
while(!all_buckets.empty()) {
std::tie(bbegin, bend) = all_buckets.top_bucket();
std::cout << "Bucket :" << j << " - {";
while (bbegin != bend) {
std::cout << *bbegin << ", ";
++bbegin;
}
std::cout << "}" << std::endl;
all_buckets.pop_bucket();
++j;
}
}
void run_tests() {
info("Running Tests : Every integer is a separate equivalence class");
run_test_1();
info("Running Tests : All integers are in the same equivalence classs (Chaotic)");
run_test_2();
info("Running Tests : All integers are in three equivalence classses (~Delta)");
run_test_3();
}
};
template<typename Graph>
void simulate(Graph& g, gizmo_config& config) {
info("Invoking simulation ...");
stat_reader sr;
bfs_simulator<Graph> bfssim;
time_type start = get_time();
if (config.get_machine_model() == distributed_real) {
info("Invoking simulation on distributed real machine model ...");
bfssim.template simulate<chaotic_ordering_gen,
distributed_real_machine_gen>(g, sr, config);
} else if (config.get_machine_model() == ram) {
info("Invoking simulation on ram machine model ...");
bfssim.template simulate<chaotic_ordering_gen,
ram_machine_gen>(g, sr, config);
} else {
std::cout << "[ERROR] Invalid machine model." << std::endl;
return;
}
time_type end = get_time();
std::cout << "[INFO] Simulation done in : "<< (end-start) << " sec. " << std::endl;
sr.print();
}
uint64_t execution_time = 0;
int main(int argc, char* argv[]) {
info("Starting AGM simulator ...");
runtime_config_params rcp;
rcp.parse(argc, argv);
amplusplus::environment env = amplusplus::mpi_environment(argc, argv, true,
1/*recvdepth*/,
1/*polls*/,
rcp.get_flow_control());
amplusplus::transport trans = env.create_transport();
_RANK = trans.rank();
rcp.print();
gizmo_config gizmocfg;
config_file_reader cfr;
if (cfr.parse(argc, argv))
cfr.read_configurations(gizmocfg);
gizmocfg.print();
// Are we reading a graph from a file ?
graph_reader_params readeparams;
if (!readeparams.parse(argc, argv))
return -1;
// No we are not -- then generate the graph
if (!readeparams.read_graph) {
synthetic_generator sg(trans);
graph_gen_params gparams;
if (!gparams.parse(argc, argv))
return -1;
gparams.print();
sg.generate_graph(gparams);
if(_RANK == 0)
std::cout << "[INFO] Done generating the graph ..." << std::endl;
simulate(*sg.graph(), gizmocfg);
sg.finalize();
} else {
graph_reader gr(trans, readeparams);
// we are reading a graph from a file
readeparams.print();
gr.read_graph();
simulate(*gr.graph(), gizmocfg);
gr.finalize();
}
}
| 27.687023 | 98 | 0.64461 | [
"object",
"model"
] |
d34a1e695fc0153a709941ca1135e7f0be9bebf0 | 3,065 | cpp | C++ | Math/GeometryBasic.cpp | igortakeo/Algorithms | 6608132e442df7b0fb295aa63f287fa65a941939 | [
"MIT"
] | null | null | null | Math/GeometryBasic.cpp | igortakeo/Algorithms | 6608132e442df7b0fb295aa63f287fa65a941939 | [
"MIT"
] | null | null | null | Math/GeometryBasic.cpp | igortakeo/Algorithms | 6608132e442df7b0fb295aa63f287fa65a941939 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
using namespace std;
//Referencia: https://github.com/icmcgema/gema/blob/master/13-Geometria_Computacional.ipynb
struct Point{
ll x, y;
Point(ll x, ll y){
this->x = x;
this->y = y;
}
Point operator+(const Point& b) const{
return Point(x+b.x, y+b.y);
}
Point operator-(const Point& b) const{
return Point(x-b.x, y-b.y);
}
//dot - produto escalar
ll operator*(const Point& b) const{
return x*b.x + y*b.y;
}
//cross - produto vetorial
// o modulo do produto vetorial entre a e b nos da area do paralelogramo
// definido entre estes dois pontos.
ll operator^(const Point &b) const{
return x*b.y - y*b.x;
}
ll norm(){
return sqrt(x*x+y*y);
}
};
//Menor distancia entre ponto e reta
double MinDist(Point a, Point b, Point point){
Point BA = b-a, CA = point-a, CB = point-b, AB = a-b;
if(BA*CA >= 0 && CB*AB >= 0){
ll area = BA^CA;
ll h = area/BA.norm();
return h;
}
else{
return min(CA.norm(), CB.norm());
}
}
//Verifica se um ponto esta dentro de um poligono convexo
//Complexidade: O(n)
bool isInside(vector<Point>polygon, Point x){
int n = polygon.size();
bool ans = true;
for(int i=0; i<n; i++){
Point seg1 = polygon[(i+1)%n] - polygon[i];
Point seg2 = x - polygon[i];
if((seg1^seg2) < 0){
ans = false;
break;
}
}
return ans;
}
bool isInsideTriangle(Point a, Point b, Point c, Point x){
Point BA = b-a, XA = x-a, CB = c-b, XB = x-b, AC = a-c, XC = x-c;
if((BA^XA) < 0) return false;
else if((CB^XB) < 0) return false;
else if((AC^XC) < 0) return false;
return true;
}
//Verifica se um ponto esta dentro de um poligono convexo
//Complexidade: O(logn)
bool isInsideOptimization(vector<Point>polygon, Point x){
int n = polygon.size();
int l = 1, r = n-2;
int i=1;
while(l <= r){
int mid = (l+r)/2;
Point v = polygon[mid] - polygon[0];
Point w = x - polygon[0];
if((v^w) >= 0){
i = mid;
l = mid + 1;
}
else r = mid - 1;
}
bool ans = isInsideTriangle(polygon[0], polygon[i], polygon[i+1], x);
return ans;
}
int axis(Point v){
if(v.y > 0) return 1;
else if(v.y < 0) return 2;
else if(v.x >= 0) return 1;
else return 2;
}
bool cmp(const Point& u, const Point& v){
if(axis(u) == axis(v)){
return ((u^v) > 0);
}
return axis(u) < axis(v);
}
//Ordena os angulos em ordem decrescente].
void SortAngles(vector<Point>&points){
sort(points.begin(), points.end(), cmp);
}
int main(){
Point a(-1,-1);
Point b(1,3);
Point c(-3,2);
Point d(2,1);
//Teste
vector<Point>v;
v.push_back(a);
v.push_back(b);
v.push_back(c);
v.push_back(d);
SortAngles(v);
for(auto it : v){
cout << it.x << ' ' << it.y << endl;
}
return 0;
} | 20.85034 | 91 | 0.531811 | [
"vector"
] |
d3501266583e4e05b9eba4da77a143f308bb191c | 1,104 | hpp | C++ | test/MockFrequencyGovernor.hpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | test/MockFrequencyGovernor.hpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | test/MockFrequencyGovernor.hpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef MOCKFREQUENCYGOVERNOR_HPP_INCLUDE
#define MOCKFREQUENCYGOVERNOR_HPP_INCLUDE
#include "gmock/gmock.h"
#include "FrequencyGovernor.hpp"
class MockFrequencyGovernor : public geopm::FrequencyGovernor
{
public:
MOCK_METHOD(void, init_platform_io, (), (override));
MOCK_METHOD(int, frequency_domain_type, (), (const, override));
MOCK_METHOD(void, adjust_platform,
(const std::vector<double> &frequency_request), (override));
MOCK_METHOD(bool, do_write_batch, (), (const, override));
MOCK_METHOD(bool, set_frequency_bounds,
(double freq_min, double freq_max), (override));
MOCK_METHOD(double, get_frequency_min, (), (const, override));
MOCK_METHOD(double, get_frequency_max, (), (const, override));
MOCK_METHOD(double, get_frequency_step, (), (const, override));
MOCK_METHOD(void, validate_policy, (double &freq_min, double &freq_max),
(const, override));
};
#endif
| 35.612903 | 80 | 0.671196 | [
"vector"
] |
d353ef63b23e78b7685c2619726646be25771e84 | 8,613 | cpp | C++ | src/conformance/conformance_test/test_ViewConfigurations.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 35 | 2020-07-07T18:10:11.000Z | 2022-03-13T10:48:45.000Z | src/conformance/conformance_test/test_ViewConfigurations.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 29 | 2020-09-10T16:36:59.000Z | 2022-03-31T18:17:32.000Z | src/conformance/conformance_test/test_ViewConfigurations.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 9 | 2020-09-10T16:01:57.000Z | 2022-01-21T18:28:35.000Z | // Copyright (c) 2019-2021, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 "utils.h"
#include "conformance_utils.h"
#include "conformance_framework.h"
#include <array>
#include <vector>
#include <set>
#include <string>
#include <cstring>
#include <catch2/catch.hpp>
#include <openxr/openxr.h>
namespace Conformance
{
TEST_CASE("ViewConfigurations", "")
{
// XrResult xrEnumerateViewConfigurations(XrInstance instance, XrSystemId systemId, uint32_t viewConfigurationTypeCapacityInput,
// uint32_t* viewConfigurationTypeCountOutput, XrViewConfigurationType* viewConfigurationTypes); XrResult
// xrGetViewConfigurationProperties(XrInstance instance, XrSystemId systemId, XrViewConfigurationType viewConfigurationType,
// XrViewConfigurationProperties* configurationProperties); XrResult xrEnumerateViewConfigurationViews(XrInstance instance,
// XrSystemId systemId, XrViewConfigurationType viewConfigurationType, uint32_t viewCapacityInput, uint32_t* viewCountOutput,
// XrViewConfigurationView* views);
AutoBasicInstance instance(AutoBasicInstance::createSystemId);
uint32_t countOutput = 0;
std::vector<XrViewConfigurationType> vctArray;
// xrEnumerateViewConfigurations
{
// Test the 0-sized input mode.
REQUIRE(xrEnumerateViewConfigurations(instance, instance.systemId, 0, &countOutput, nullptr) == XR_SUCCESS);
if (countOutput) {
REQUIRE_NOTHROW(vctArray.resize(countOutput, XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM));
countOutput = 0;
if (countOutput >= 2) // The -1 below needs the result to be >0 because 0 is a special case as exercised above.
{
// Exercise XR_ERROR_SIZE_INSUFFICIENT.
REQUIRE(xrEnumerateViewConfigurations(instance, instance.systemId, countOutput - 1, &countOutput, vctArray.data()) ==
XR_ERROR_SIZE_INSUFFICIENT);
REQUIRE_MSG(vctArray[countOutput - 1] == XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM,
"xrEnumerateViewConfigurations write past capacity");
std::fill(vctArray.begin(), vctArray.end(), XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM);
countOutput = 0;
}
REQUIRE(xrEnumerateViewConfigurations(instance, instance.systemId, countOutput, &countOutput, vctArray.data()) ==
XR_SUCCESS);
REQUIRE(countOutput == vctArray.size());
}
}
// xrGetViewConfigurationProperties
{
// XrResult xrGetViewConfigurationProperties(XrInstance instance, XrSystemId systemId, XrViewConfigurationType
// viewConfigurationType, XrViewConfigurationProperties* configurationProperties);
if (vctArray.size()) {
XrViewConfigurationProperties vcp{XR_TYPE_VIEW_CONFIGURATION_PROPERTIES};
// Need to enumerate again because the array was reset above.
/// @todo restructure to use sections and avoid this.
REQUIRE(xrEnumerateViewConfigurations(instance, instance.systemId, (uint32_t)vctArray.size(), &countOutput,
vctArray.data()) == XR_SUCCESS);
for (XrViewConfigurationType vct : vctArray) {
REQUIRE(xrGetViewConfigurationProperties(instance, instance.systemId, vct, &vcp) == XR_SUCCESS);
REQUIRE(vcp.viewConfigurationType == vct);
// We have nothing to say here about vcp.fovMutable. However, we will later want
// to use that when submitting frames to mutate the fov.
}
SECTION("Unrecognized extension")
{
// Runtimes should ignore unrecognized struct extensins.
InsertUnrecognizableExtension(&vcp);
REQUIRE(xrGetViewConfigurationProperties(instance, instance.systemId, vctArray[0], &vcp) == XR_SUCCESS);
REQUIRE(vcp.viewConfigurationType == vctArray[0]);
}
// Exercise XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED
REQUIRE(xrGetViewConfigurationProperties(instance, instance.systemId, XR_VIEW_CONFIGURATION_TYPE_MAX_ENUM, &vcp) ==
XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED);
}
}
// xrEnumerateViewConfigurationViews
{
// XrResult xrEnumerateViewConfigurationViews(instance, instance.systemId, XrViewConfigurationType viewConfigurationType,
// uint32_t viewCapacityInput, uint32_t* viewCountOutput, XrViewConfigurationView* views);
for (XrViewConfigurationType vct : vctArray) {
std::vector<XrViewConfigurationView> vcvArray;
REQUIRE(xrEnumerateViewConfigurationViews(instance, instance.systemId, vct, 0, &countOutput, nullptr) == XR_SUCCESS);
CHECK_MSG(countOutput > 0, "Viewport configuration provides no views.");
if (countOutput) {
const XrViewConfigurationView initView{
XR_TYPE_VIEW_CONFIGURATION_VIEW, nullptr, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX};
REQUIRE_NOTHROW(vcvArray.resize(countOutput, initView));
countOutput = 0;
if (countOutput >= 2) // The -1 below needs the result to be >0 because 0 is a special case as exercised above.
{
SECTION("Exercise XR_ERROR_SIZE_INSUFFICIENT")
{
REQUIRE(xrEnumerateViewConfigurationViews(instance, instance.systemId, vct, countOutput - 1, &countOutput,
vcvArray.data()) == XR_ERROR_SIZE_INSUFFICIENT);
REQUIRE_MSG(vcvArray[countOutput - 1].recommendedImageRectWidth == UINT32_MAX,
"xrEnumerateViewConfigurationViews write past capacity");
}
}
SECTION("Normal call")
{
REQUIRE(xrEnumerateViewConfigurationViews(instance, instance.systemId, vct, countOutput, &countOutput,
vcvArray.data()) == XR_SUCCESS);
REQUIRE(countOutput == vcvArray.size());
// At this point we have an array of XrViewConfigurationView.
for (XrViewConfigurationView view : vcvArray) {
// To do: validate these to the extent possible.
REQUIRE(view.type == XR_TYPE_VIEW_CONFIGURATION_VIEW);
REQUIRE(view.next == nullptr);
(void)view.recommendedImageRectWidth;
(void)view.maxImageRectWidth;
(void)view.recommendedImageRectHeight;
(void)view.maxImageRectHeight;
(void)view.recommendedSwapchainSampleCount;
(void)view.maxSwapchainSampleCount;
}
}
SECTION("Unrecognized extension")
{
// Runtimes should ignore unrecognized struct extensins.
InsertUnrecognizableExtensionArray(vcvArray.data(), vcvArray.size());
REQUIRE(xrEnumerateViewConfigurationViews(instance, instance.systemId, vct, countOutput, &countOutput,
vcvArray.data()) == XR_SUCCESS);
}
}
}
}
}
} // namespace Conformance
| 50.964497 | 138 | 0.600836 | [
"vector"
] |
d35bdf651d173c0c61808d94732537fd56bca17d | 20,310 | cpp | C++ | src/gate.cpp | makzator/quandary | e3b1a0917991ad0b939b93cd55f5fce3fa821e58 | [
"MIT"
] | null | null | null | src/gate.cpp | makzator/quandary | e3b1a0917991ad0b939b93cd55f5fce3fa821e58 | [
"MIT"
] | null | null | null | src/gate.cpp | makzator/quandary | e3b1a0917991ad0b939b93cd55f5fce3fa821e58 | [
"MIT"
] | null | null | null | #include "gate.hpp"
Gate::Gate(){
dim_ess = 0;
dim_rho = 0;
}
Gate::Gate(std::vector<int> nlevels_, std::vector<int> nessential_, double time_, std::vector<double> gate_rot_freq_){
MPI_Comm_rank(PETSC_COMM_WORLD, &mpirank_petsc);
nessential = nessential_;
nlevels = nlevels_;
final_time = time_;
gate_rot_freq = gate_rot_freq_;
for (int i=0; i<gate_rot_freq.size(); i++){
gate_rot_freq[i] *= 2.*M_PI;
}
/* Dimension of gate = \prod_j nessential_j */
dim_ess = 1;
for (int i=0; i<nessential.size(); i++) {
dim_ess *= nessential[i];
}
/* Dimension of system matrix rho */
dim_rho = 1;
for (int i=0; i<nlevels.size(); i++) {
dim_rho *= nlevels[i];
}
/* Allocate input Gate in essential level dimension, sequential matrix (real and imaginary parts), copied on all processors */
MatCreateSeqDense(PETSC_COMM_SELF, dim_ess, dim_ess, NULL, &V_re);
MatCreateSeqDense(PETSC_COMM_SELF, dim_ess, dim_ess, NULL, &V_im);
MatSetUp(V_re);
MatSetUp(V_im);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
/* Allocate vectorized Gate in full dimensions G = VxV, where V is the full-dimension gate (inserting zero rows and colums for all non-essential levels) */
// parallel matrix, essential levels dimension TODO: Preallocate!
MatCreate(PETSC_COMM_WORLD, &VxV_re);
MatCreate(PETSC_COMM_WORLD, &VxV_im);
MatSetSizes(VxV_re, PETSC_DECIDE, PETSC_DECIDE, dim_rho*dim_rho, dim_rho*dim_rho);
MatSetSizes(VxV_im, PETSC_DECIDE, PETSC_DECIDE, dim_rho*dim_rho, dim_rho*dim_rho);
MatSetUp(VxV_re);
MatSetUp(VxV_im);
MatAssemblyBegin(VxV_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(VxV_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(VxV_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(VxV_im, MAT_FINAL_ASSEMBLY);
/* Allocate auxiliare vectors */
MatCreateVecs(VxV_re, &x, NULL);
/* Create vector strides for accessing real and imaginary part of co-located state */
PetscInt ilow, iupp;
MatGetOwnershipRange(VxV_re, &ilow, &iupp);
PetscInt dimis = iupp - ilow;
ISCreateStride(PETSC_COMM_WORLD, dimis, 2*ilow, 2, &isu);
ISCreateStride(PETSC_COMM_WORLD, dimis, 2*ilow+1, 2, &isv);
}
Gate::~Gate(){
if (dim_rho == 0) return;
MatDestroy(&VxV_re);
MatDestroy(&VxV_im);
MatDestroy(&V_re);
MatDestroy(&V_im);
VecDestroy(&x);
ISDestroy(&isu);
ISDestroy(&isv);
}
void Gate::assembleGate(){
/* Rorate the gate to rotational frame. */
const PetscScalar* vals_vre, *vals_vim;
PetscScalar *out_re, *out_im;
PetscInt *cols;
PetscMalloc1(dim_ess, &out_re);
PetscMalloc1(dim_ess, &out_im);
PetscMalloc1(dim_ess, &cols);
// get the frequency of the diagonal scaling e^{iwt} for each row rotation matrix R=R1\otimes R2\otimes...
for (PetscInt row=0; row<dim_ess; row++){
int r = row;
double freq = 0.0;
for (int iosc=0; iosc<nlevels.size(); iosc++){
// compute dimension of essential levels of all following subsystems
int dim_post = 1;
for (int josc=iosc+1; josc<nlevels.size();josc++) {
dim_post *= nessential[josc];
}
// compute the frequency
int rk = (int) r / dim_post;
freq = freq + rk * gate_rot_freq[iosc];
r = r % dim_post;
}
double ra = cos(freq*final_time);
double rb = sin(freq*final_time);
/* Get row in V that is to be scaled by the rotation */
MatGetRow(V_re, row, NULL, NULL, &vals_vre); // V_re, V_im is stored dense , so ncols = dim_ess!
MatGetRow(V_im, row, NULL, NULL, &vals_vim);
// Compute the rotated real and imaginary part
for (int c=0; c<dim_ess; c++){
out_re[c] = ra * vals_vre[c] - rb * vals_vim[c];
out_im[c] = ra * vals_vim[c] + rb * vals_vre[c];
cols[c] = c;
}
MatRestoreRow(V_re, row, NULL, NULL, &vals_vre);
MatRestoreRow(V_im, row, NULL, NULL, &vals_vim);
// Insert the new values
MatSetValues(V_re, 1, &row, dim_ess, cols, out_re, INSERT_VALUES);
MatSetValues(V_im, 1, &row, dim_ess, cols, out_im, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
}
// clean up
PetscFree(out_re);
PetscFree(out_im);
PetscFree(cols);
#ifdef SANITY_CHECK
bool isunitary = isUnitary(V_re, V_im);
if (!isunitary) {
printf("ERROR: Rotated Gate is not unitary!\n");
exit(1);
}
else printf("Rotated Gate is unitary.\n");
#endif
/* Assemble vectorized gate G=V\kron V where V = PV_eP^T for essential dimension gate V_e (user input) and projection P lifting V_e to the full dimension by inserting identity blocks for non-essential levels. */
// Each element in V\kron V is a product V(i,j)*V(r,c), for rows and columns i,j,r,c!
PetscInt ilow, iupp;
MatGetOwnershipRange(VxV_re, &ilow, &iupp);
double val;
double vre_ij, vim_ij;
double vre_rc, vim_rc;
// iterate over rows of V_e (essential dimension gate)
for (PetscInt row_f=0;row_f<dim_rho; row_f++) {
if (isEssential(row_f, nlevels, nessential)) { // place \bar v_xx*V_f blocks for all cols in V_e[row_e]
PetscInt row_e = mapFullToEss(row_f, nlevels, nessential);
assert(row_f == mapEssToFull(row_e, nlevels, nessential));
// iterate over columns in this row_e
for (PetscInt col_e=0; col_e<dim_ess; col_e++) {
vre_ij = 0.0; vim_ij = 0.0;
MatGetValues(V_re, 1, &row_e, 1, &col_e, &vre_ij);
MatGetValues(V_im, 1, &row_e, 1, &col_e, &vim_ij);
// for all nonzeros in this row, place block \bar Ve_{i,j} * (V_f) at starting position G[a,b]
if (fabs(vre_ij) > 1e-14 || fabs(vim_ij) > 1e-14 ) {
int a = row_f * dim_rho;
int b = mapEssToFull(col_e, nlevels, nessential) * dim_rho;
// iterate over rows in V_f
for (PetscInt r=0; r<dim_rho; r++) {
PetscInt rowout = a + r; // row in G
if (ilow <= rowout && rowout < iupp) {
if (isEssential(r, nlevels, nessential)){ // place ve_ij*ve_rc at G[a+r, b+map(ce)]
PetscInt re = mapFullToEss(r, nlevels, nessential);
for (PetscInt ce=0; ce<dim_ess; ce++) {
PetscInt colout = b + mapEssToFull(ce, nlevels, nessential); // column in G
vre_rc = 0.0; vim_rc = 0.0;
MatGetValues(V_re, 1, &re, 1, &ce, &vre_rc);
MatGetValues(V_im, 1, &re, 1, &ce, &vim_rc);
val = vre_ij*vre_rc + vim_ij*vim_rc;
if (fabs(val) > 1e-14) MatSetValue(VxV_re, rowout, colout, val, INSERT_VALUES);
val = vre_ij*vim_rc - vim_ij*vre_rc;
if (fabs(val) > 1e-14) MatSetValue(VxV_im, rowout, colout, val, INSERT_VALUES);
}
} else { // place ve_ij*1.0 at G[a+row, a+row]
PetscInt colout = b + r;
val = vre_ij;
if (fabs(val) > 1e-14) MatSetValue(VxV_re, rowout, colout, val, INSERT_VALUES);
val = vim_rc;
if (fabs(val) > 1e-14) MatSetValue(VxV_im, rowout, colout, val, INSERT_VALUES);
}
}
}
}
}
} else { // place Vf block starting at G[a,a], a=row_f * N
int a = row_f * dim_rho;
// iterate over rows in V_f
for (int r=0; r<dim_rho; r++) {
PetscInt rowout = a + r; // row in G
if (ilow <= rowout && rowout < iupp) {
if (isEssential(r, nlevels, nessential)){ // place ve_rc at G[a+r, a+map(ce)]
PetscInt re = mapFullToEss(r, nlevels, nessential);
for (PetscInt ce=0; ce<dim_ess; ce++) {
PetscInt colout = a + mapEssToFull(ce, nlevels, nessential); // column in G
vre_rc = 0.0; vim_rc = 0.0;
MatGetValues(V_re, 1, &re, 1, &ce, &vre_rc);
MatGetValues(V_im, 1, &re, 1, &ce, &vim_rc);
val = vre_rc;
if (fabs(val) > 1e-14) MatSetValue(VxV_re, rowout, colout, val, INSERT_VALUES);
val = vim_rc;
if (fabs(val) > 1e-14) MatSetValue(VxV_im, rowout, colout, val, INSERT_VALUES);
}
} else { // place 1.0 at G[a+r, a+r]
PetscInt colout = a + r;
val = 1.0;
if (fabs(val) > 1e-14) MatSetValue(VxV_re, rowout, colout, val, INSERT_VALUES);
}
}
}
}
}
MatAssemblyBegin(VxV_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(VxV_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(VxV_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(VxV_im, MAT_FINAL_ASSEMBLY);
}
void Gate::applyGate(const Vec state, Vec VrhoV){
/* Exit, if this is a dummy gate */
if (dim_rho == 0) return;
/* Get real and imag part of the state q = u + iv */
Vec u, v;
VecGetSubVector(state, isu, &u);
VecGetSubVector(state, isv, &v);
/* (a) Real part Re(VxV q) = VxV_re u - VxV_im v */
MatMult(VxV_im, v, x); //
VecScale(x, -1.0); // x = -VxV_im * v
MatMultAdd(VxV_re, u, x, x); // x += VxV_re * u
VecISCopy(VrhoV, isu, SCATTER_FORWARD, x);
/* (b) Imaginary part Im(VxV q) = VxV_re v + VxV_im u */
MatMult(VxV_re, v, x); // x = VxV_re * v
MatMultAdd(VxV_im, u, x, x); // x += VxV_im * u
VecISCopy(VrhoV, isv, SCATTER_FORWARD, x);
/* Restore state from index set */
VecRestoreSubVector(state, isu, &u);
VecRestoreSubVector(state, isv, &v);
}
XGate::XGate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq) : Gate(nlevels, nessential, time, gate_rot_freq) {
assert(dim_ess == 2);
/* Fill V_re = Re(V) and V_im = Im(V), V = V_re + iVb */
/* V_re = 0 1 V_im = 0 0
* 1 0 0 0
*/
if (mpirank_petsc == 0) {
MatSetValue(V_re, 0, 1, 1.0, INSERT_VALUES);
MatSetValue(V_re, 1, 0, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
}
/* Assemble vectorized rotated target gate \bar VP \kron VP from V = V_re + i V_im */
assembleGate();
}
XGate::~XGate() {}
YGate::YGate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq ) : Gate(nlevels, nessential, time, gate_rot_freq) {
assert(dim_ess == 2);
/* Fill A = Re(V) and B = Im(V), V = A + iB */
/* A = 0 0 B = 0 -1
* 0 0 1 0
*/
if (mpirank_petsc == 0) {
MatSetValue(V_im, 0, 1, -1.0, INSERT_VALUES);
MatSetValue(V_im, 1, 0, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
}
/* Assemble vectorized rotated arget gate \bar VP \kron VP from V = V_re + i V_im*/
assembleGate();
}
YGate::~YGate() {}
ZGate::ZGate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq ) : Gate(nlevels, nessential, time, gate_rot_freq) {
assert(dim_ess == 2);
/* Fill A = Re(V) and B = Im(V), V = A + iB */
/* A = 1 0 B = 0 0
* 0 -1 0 0
*/
if (mpirank_petsc == 0) {
MatSetValue(V_im, 0, 0, 1.0, INSERT_VALUES);
MatSetValue(V_im, 1, 1, -1.0, INSERT_VALUES);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
}
/* Assemble vectorized rotated target gate \bar VP \kron VP from V = V_re + i V_im*/
assembleGate();
}
ZGate::~ZGate() {}
HadamardGate::HadamardGate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq ) : Gate(nlevels, nessential, time, gate_rot_freq) {
assert(dim_ess == 2);
/* Fill A = Re(V) and B = Im(V), V = A + iB */
/* A = 1 0 B = 0 0
* 0 -1 0 0
*/
if (mpirank_petsc == 0) {
double val = 1./sqrt(2);
MatSetValue(V_re, 0, 0, val, INSERT_VALUES);
MatSetValue(V_re, 0, 1, val, INSERT_VALUES);
MatSetValue(V_re, 1, 0, val, INSERT_VALUES);
MatSetValue(V_re, 1, 1, -val, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
}
/* Assemble vectorized rotated target gate \bar VP \kron VP from V = V_re + i V_im*/
assembleGate();
}
HadamardGate::~HadamardGate() {}
CNOT::CNOT(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq) : Gate(nlevels, nessential,time, gate_rot_freq) {
assert(dim_ess == 4);
/* Fill A = Re(V) and B = Im(V), V = A + iB */
/* A = 1 0 0 0 B = 0 0 0 0
* 0 1 0 0 0 0 0 0
* 0 0 0 1 0 0 0 0
* 0 0 1 0 0 0 0 0
*/ if (mpirank_petsc == 0) {
MatSetValue(V_re, 0, 0, 1.0, INSERT_VALUES);
MatSetValue(V_re, 1, 1, 1.0, INSERT_VALUES);
MatSetValue(V_re, 2, 3, 1.0, INSERT_VALUES);
MatSetValue(V_re, 3, 2, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
}
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
CNOT::~CNOT(){}
SWAP::SWAP(std::vector<int> nlevels_, std::vector<int> nessential_, double time_, std::vector<double> gate_rot_freq_) : Gate(nlevels_, nessential_, time_, gate_rot_freq_) {
assert(dim_ess == 4);
/* Fill lab-frame swap gate in essential dimension system V_re = Re(V), V_im = Im(V) = 0 */
MatSetValue(V_re, 0, 0, 1.0, INSERT_VALUES);
MatSetValue(V_re, 1, 2, 1.0, INSERT_VALUES);
MatSetValue(V_re, 2, 1, 1.0, INSERT_VALUES);
MatSetValue(V_re, 3, 3, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
SWAP::~SWAP(){}
SWAP_0Q::SWAP_0Q(std::vector<int> nlevels_, std::vector<int> nessential_, double time_, std::vector<double> gate_rot_freq_) : Gate(nlevels_, nessential_, time_, gate_rot_freq_) {
int Q = nlevels.size(); // Number of total oscillators
/* Fill lab-frame swap 0<->Q-1 gate in essential dimension system V_re = Re(V), V_im = Im(V) = 0 */
// diagonal elements. don't swap on states |0xx0> and |1xx1>
for (int i=0; i< (int) pow(2, Q-2); i++) {
MatSetValue(V_re, 2*i, 2*i, 1.0, INSERT_VALUES);
}
for (int i=(int) pow(2, Q-2); i< pow(2, Q-1); i++) {
MatSetValue(V_re, 2*i+1, 2*i+1, 1.0, INSERT_VALUES);
}
// off-diagonal elements, swap on |0xx1> and |1xx0>
for (int i=0; i< pow(2, Q-2); i++) {
MatSetValue(V_re, 2*i + 1, 2*i + (int) pow(2,Q-1), 1.0, INSERT_VALUES);
MatSetValue(V_re, 2*i + (int) pow(2,Q-1), 2*i + 1, 1.0, INSERT_VALUES);
}
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
bool isunitary = isUnitary(V_re, V_im);
if (!isunitary) {
printf("ERROR: Gate is not unitary!\n");
exit(1);
}
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
SWAP_0Q::~SWAP_0Q(){}
CQNOT::CQNOT(std::vector<int> nlevels_, std::vector<int> nessential_, double time_, std::vector<double> gate_rot_freq_) : Gate(nlevels_, nessential_, time_, gate_rot_freq_) {
/* Fill lab-frame CQNOT gate in essential dimension system V_re = Re(V), V_im = Im(V) = 0 */
/* V = [1 0 0 ...
0 1 0 ...
0 0 1 ...
..........
0 1
1 0 ]
*/
for (int k=0; k<dim_ess-2; k++) {
MatSetValue(V_re, k, k, 1.0, INSERT_VALUES);
}
MatSetValue(V_re, dim_ess-2, dim_ess-1, 1.0, INSERT_VALUES);
MatSetValue(V_re, dim_ess-1, dim_ess-2, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
CQNOT::~CQNOT(){}
//LMS
SQRTCNOT::SQRTCNOT(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq) : Gate(nlevels, nessential,time, gate_rot_freq) {
assert(dim_ess == 4);
/* Fill A = Re(V) and B = Im(V), V = A + iB */
/* A = 1 0 0 0 B = 0 0 0 0
* 0 1 0 0 0 0 0 0
* 0 0 1/2 1/2 0 0 1/2 -1/2
* 0 0 1/2 1/2 0 0 -1/2 1/2
*/ if (mpirank_petsc == 0) {
MatSetValue(V_re, 0, 0, 1.0, INSERT_VALUES);
MatSetValue(V_re, 1, 1, 1.0, INSERT_VALUES);
MatSetValue(V_re, 2, 2, 0.5, INSERT_VALUES);
MatSetValue(V_re, 3, 3, 0.5, INSERT_VALUES);
MatSetValue(V_re, 2, 3, 0.5, INSERT_VALUES);
MatSetValue(V_re, 3, 2, 0.5, INSERT_VALUES);
MatSetValue(V_im, 2, 2, 0.5, INSERT_VALUES);
MatSetValue(V_im, 3, 3, 0.5, INSERT_VALUES);
MatSetValue(V_im, 2, 3, -0.5, INSERT_VALUES);
MatSetValue(V_im, 3, 2, -0.5, INSERT_VALUES);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
}
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
SQRTCNOT::~SQRTCNOT(){}
EncodingGate::EncodingGate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq) : Gate(nlevels, nessential,time, gate_rot_freq) {
assert(dim_ess == 8);
/* U = 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1
*/
if (mpirank_petsc == 0) {
MatSetValue(V_re, 0, 0, 1.0, INSERT_VALUES);
MatSetValue(V_re, 1, 1, 1.0, INSERT_VALUES);
MatSetValue(V_re, 2, 4, 1.0, INSERT_VALUES);
MatSetValue(V_re, 3, 5, 1.0, INSERT_VALUES);
MatSetValue(V_re, 4, 2, 1.0, INSERT_VALUES);
MatSetValue(V_re, 5, 3, 1.0, INSERT_VALUES);
MatSetValue(V_re, 6, 6, 1.0, INSERT_VALUES);
MatSetValue(V_re, 7, 7, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
}
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
EncodingGate::~EncodingGate(){}
X23Gate::X23Gate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq) : Gate(nlevels, nessential,time, gate_rot_freq) {
assert(dim_ess == 4);
/* U = 1 0 0 0
0 1 0 0
0 0 0 1
0 0 1 0
*/
if (mpirank_petsc == 0) {
MatSetValue(V_re, 0, 0, 1.0, INSERT_VALUES);
MatSetValue(V_re, 1, 1, 1.0, INSERT_VALUES);
MatSetValue(V_re, 2, 3, 1.0, INSERT_VALUES);
MatSetValue(V_re, 3, 2, 1.0, INSERT_VALUES);
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
}
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
X23Gate::~X23Gate(){}
ArbitraryGate::ArbitraryGate(std::vector<int> nlevels, std::vector<int> nessential, double time, std::vector<double> gate_rot_freq, std::vector<double> V_re_rows, std::vector<double> V_im_rows) : Gate(nlevels, nessential,time, gate_rot_freq) {
assert(V_re_rows.size() == V_im_rows.size());
int dim_gate = int(sqrt(V_re_rows.size()));
assert(dim_gate*dim_gate == V_re_rows.size());
assert(dim_ess == dim_gate);
if (mpirank_petsc == 0) {
for (int i=0; i<dim_gate; i++) {
for (int j=0; j<dim_gate; j++) {
MatSetValue(V_re, i, j, V_re_rows[i*dim_gate+j], INSERT_VALUES);
MatSetValue(V_im, i, j, V_im_rows[i*dim_gate+j], INSERT_VALUES);
}
}
MatAssemblyBegin(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_re, MAT_FINAL_ASSEMBLY);
MatAssemblyBegin(V_im, MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(V_im, MAT_FINAL_ASSEMBLY);
}
/* assemble vectorized rotated target gate \bar VP \kron VP from V=V_re + i V_im */
assembleGate();
}
ArbitraryGate::~ArbitraryGate(){} | 35.631579 | 243 | 0.629838 | [
"vector"
] |
d36658c4fc5a1f7a3e8249c7b2f8036507064de8 | 52,188 | cpp | C++ | Sources/Elastos/Packages/Service/Telephony/src/elastos/droid/teleservice/phone/CMobileNetworkSettings.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Packages/Service/Telephony/src/elastos/droid/teleservice/phone/CMobileNetworkSettings.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Packages/Service/Telephony/src/elastos/droid/teleservice/phone/CMobileNetworkSettings.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos 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 "elastos/droid/teleservice/phone/CMobileNetworkSettings.h"
#include "elastos/droid/teleservice/phone/PhoneGlobals.h"
#include "elastos/droid/teleservice/phone/CCdmaOptions.h"
#include "elastos/droid/teleservice/phone/CGsmUmtsOptions.h"
#include "elastos/droid/os/AsyncResult.h"
#include "elastos/droid/text/TextUtils.h"
#include "elastos/droid/R.h"
#include "Elastos.Droid.App.h"
#include "Elastos.Droid.Internal.h"
#include "Elastos.Droid.Net.h"
#include "Elastos.Droid.Provider.h"
#include "Elastos.Droid.Telephony.h"
#include <elastos/core/StringBuilder.h>
#include <elastos/core/CoreUtils.h>
#include <elastos/core/StringUtils.h>
#include <elastos/utility/logging/Logger.h>
#include "R.h"
using Elastos::Droid::App::IActionBar;
using Elastos::Droid::App::IActionBar;
using Elastos::Droid::App::CAlertDialogBuilder;
using Elastos::Droid::App::IAlertDialogBuilder;
using Elastos::Droid::Content::ISharedPreferencesEditor;
using Elastos::Droid::Content::IContentResolver;
using Elastos::Droid::Content::EIID_IDialogInterfaceOnClickListener;
using Elastos::Droid::Content::EIID_IDialogInterfaceOnDismissListener;
using Elastos::Droid::Net::IUri;
using Elastos::Droid::Net::CUriHelper;
using Elastos::Droid::Net::IUriHelper;
using Elastos::Droid::Os::AsyncResult;
using Elastos::Droid::Os::IAsyncResult;
using Elastos::Droid::Os::ISystemProperties;
using Elastos::Droid::Os::CSystemProperties;
using Elastos::Droid::Os::IUserHandleHelper;
using Elastos::Droid::Os::CUserHandleHelper;
using Elastos::Droid::Provider::ISettingsGlobal;
using Elastos::Droid::Provider::CSettingsGlobal;
using Elastos::Droid::Preference::IPreferenceGroup;
using Elastos::Droid::Preference::ITwoStatePreference;
using Elastos::Droid::Preference::EIID_IPreferenceOnPreferenceChangeListener;
using Elastos::Droid::Internal::Telephony::IPhoneConstants;
using Elastos::Droid::Internal::Telephony::ITelephonyIntents;
using Elastos::Droid::Internal::Telephony::ITelephonyProperties;
using Elastos::Droid::Text::TextUtils;
using Elastos::Droid::Telephony::ITelephonyManager;
using Elastos::Droid::Telephony::ISubscriptionManager;
using Elastos::Droid::Telephony::CSubscriptionManager;
using Elastos::Core::StringUtils;
using Elastos::Core::CoreUtils;
using Elastos::Core::StringBuilder;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace TeleService {
namespace Phone {
CAR_INTERFACE_IMPL_3(CMobileNetworkSettings::InnerListener, Object,
IDialogInterfaceOnClickListener,
IDialogInterfaceOnDismissListener,
IPreferenceOnPreferenceChangeListener)
CMobileNetworkSettings::InnerListener::InnerListener(
/* [in] */ CMobileNetworkSettings* host)
: mHost(host)
{}
ECode CMobileNetworkSettings::InnerListener::OnClick(
/* [in] */ IDialogInterface* dialog,
/* [in] */ Int32 which)
{
return mHost->OnClick(dialog, which);
}
//@Override
ECode CMobileNetworkSettings::InnerListener::OnDismiss(
/* [in] */ IDialogInterface* dialog)
{
return mHost->OnDismiss(dialog);
}
ECode CMobileNetworkSettings::InnerListener::OnPreferenceChange(
/* [in] */ IPreference* preference,
/* [in] */ IInterface* objValue,
/* [out] */ Boolean* result)
{
return mHost->OnPreferenceChange(preference, objValue, result);
}
CMobileNetworkSettings::MyHandler::MyHandler(
CMobileNetworkSettings* host)
: mHost(host)
{
Handler::constructor();
}
ECode CMobileNetworkSettings::MyHandler::HandleMessage(
/* [in] */ IMessage* msg)
{
Int32 what;
msg->GetWhat(&what);
switch (what) {
case MESSAGE_GET_PREFERRED_NETWORK_TYPE:
HandleGetPreferredNetworkTypeResponse(msg);
break;
case MESSAGE_SET_PREFERRED_NETWORK_TYPE:
HandleSetPreferredNetworkTypeResponse(msg);
break;
}
return NOERROR;
}
void CMobileNetworkSettings::MyHandler::HandleGetPreferredNetworkTypeResponse(
/* [in] */ IMessage* msg)
{
AutoPtr<IInterface> obj;
msg->GetObj((IInterface**)&obj);
AutoPtr<AsyncResult> ar = (AsyncResult*)IAsyncResult::Probe(obj);
if (ar->mException == NULL) {
AutoPtr<IArrayOf> array = IArrayOf::Probe(ar->mResult);
AutoPtr<IInterface> obj;
array->Get(0, (IInterface**)&obj);
AutoPtr<IInteger32> num = IInteger32::Probe(obj);
Int32 modemNetworkMode;
num->GetValue(&modemNetworkMode);
if (DBG) {
Log(String("handleGetPreferredNetworkTypeResponse: modemNetworkMode = ") +
StringUtils::ToString(modemNetworkMode));
}
AutoPtr<IContext> context;
mHost->mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
if (DBG) {
Log(String("handleGetPreferredNetworkTypeReponse: settingsNetworkMode = ") +
StringUtils::ToString(settingsNetworkMode));
}
//check that modemNetworkMode is from an accepted value
if (modemNetworkMode == IPhone::NT_MODE_WCDMA_PREF ||
modemNetworkMode == IPhone::NT_MODE_GSM_ONLY ||
modemNetworkMode == IPhone::NT_MODE_WCDMA_ONLY ||
modemNetworkMode == IPhone::NT_MODE_GSM_UMTS ||
modemNetworkMode == IPhone::NT_MODE_CDMA ||
modemNetworkMode == IPhone::NT_MODE_CDMA_NO_EVDO ||
modemNetworkMode == IPhone::NT_MODE_EVDO_NO_CDMA ||
modemNetworkMode == IPhone::NT_MODE_GLOBAL ||
modemNetworkMode == IPhone::NT_MODE_LTE_CDMA_AND_EVDO ||
modemNetworkMode == IPhone::NT_MODE_LTE_GSM_WCDMA ||
modemNetworkMode == IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA ||
modemNetworkMode == IPhone::NT_MODE_LTE_ONLY ||
modemNetworkMode == IPhone::NT_MODE_LTE_WCDMA) {
if (DBG) {
Log(String("handleGetPreferredNetworkTypeResponse: if 1: modemNetworkMode = ") +
StringUtils::ToString(modemNetworkMode));
}
//check changes in modemNetworkMode
if (modemNetworkMode != settingsNetworkMode) {
if (DBG) {
Log(String("handleGetPreferredNetworkTypeResponse: if 2: ") +
String("modemNetworkMode != settingsNetworkMode"));
}
settingsNetworkMode = modemNetworkMode;
if (DBG) {
StringBuilder sb;
sb += "handleGetPreferredNetworkTypeResponse: if 2: ";
sb += "settingsNetworkMode = ";
sb += settingsNetworkMode;
Log(sb.ToString());
}
}
mHost->UpdatePreferredNetworkModeSummary(modemNetworkMode);
mHost->UpdateEnabledNetworksValueAndSummary(modemNetworkMode);
// changes the mButtonPreferredNetworkMode accordingly to modemNetworkMode
mHost->mButtonPreferredNetworkMode->SetValue(StringUtils::ToString(modemNetworkMode));
}
else {
if (DBG) Log(String("handleGetPreferredNetworkTypeResponse: else: reset to default"));
ResetNetworkModeToDefault();
}
}
}
void CMobileNetworkSettings::MyHandler::HandleSetPreferredNetworkTypeResponse(
/* [in] */ IMessage* msg)
{
AutoPtr<IInterface> obj;
msg->GetObj((IInterface**)&obj);
AutoPtr<AsyncResult> ar = (AsyncResult*)IAsyncResult::Probe(obj);
if (ar->mException == NULL) {
String value;
mHost->mButtonPreferredNetworkMode->GetValue(&value);
Int32 networkMode = StringUtils::ParseInt32(value);
AutoPtr<IContext> context;
mHost->mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Boolean res;
helper->PutInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
networkMode, &res);
String value2;
mHost->mButtonEnabledNetworks->GetValue(&value2);
networkMode = StringUtils::ParseInt32(value2);
helper->PutInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
networkMode, &res);
}
else {
AutoPtr<IMessage> m;
ObtainMessage(MESSAGE_GET_PREFERRED_NETWORK_TYPE, (IMessage**)&m);
mHost->mPhone->GetPreferredNetworkType(m);
}
}
void CMobileNetworkSettings::MyHandler::ResetNetworkModeToDefault()
{
//set the mButtonPreferredNetworkMode
mHost->mButtonPreferredNetworkMode->SetValue(StringUtils::ToString(sPreferredNetworkMode));
mHost->mButtonEnabledNetworks->SetValue(StringUtils::ToString(sPreferredNetworkMode));
//set the Settings.System
AutoPtr<IContext> context;
mHost->mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Boolean res;
helper->PutInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &res);
//Set the Modem
AutoPtr<IMessage> m;
ObtainMessage(MyHandler::MESSAGE_SET_PREFERRED_NETWORK_TYPE, (IMessage**)&m);
mHost->mPhone->SetPreferredNetworkType(sPreferredNetworkMode, m);
}
const String CMobileNetworkSettings::TAG("NetworkSettings");
const Boolean CMobileNetworkSettings::DBG = TRUE;
const String CMobileNetworkSettings::BUTTON_PREFERED_NETWORK_MODE("preferred_network_mode_key");
const String CMobileNetworkSettings::BUTTON_ROAMING_KEY("button_roaming_key");
const String CMobileNetworkSettings::BUTTON_CDMA_LTE_DATA_SERVICE_KEY("cdma_lte_data_service_key");
const String CMobileNetworkSettings::BUTTON_ENABLED_NETWORKS_KEY("enabled_networks_key");
const String CMobileNetworkSettings::BUTTON_4G_LTE_KEY("enhanced_4g_lte");
const String CMobileNetworkSettings::BUTTON_CELL_BROADCAST_SETTINGS("cell_broadcast_settings");
const Int32 CMobileNetworkSettings::sPreferredNetworkMode = IPhone::PREFERRED_NT_MODE;
const String CMobileNetworkSettings::UP_ACTIVITY_PACKAGE("Elastos.Droid.Settings");
const String CMobileNetworkSettings::UP_ACTIVITY_CLASS("Elastos.Droid.Settings.CSettingsWirelessSettingsActivity");
const String CMobileNetworkSettings::sIface("rmnet0"); //TODO: this will go away
CAR_INTERFACE_IMPL(CMobileNetworkSettings, PreferenceActivity, IMobileNetworkSettings)
CAR_OBJECT_IMPL(CMobileNetworkSettings)
CMobileNetworkSettings::CMobileNetworkSettings()
: mOkClicked(FALSE)
, mShow4GForLTE(FALSE)
, mIsGlobalCdma(FALSE)
, mUnavailable(FALSE)
{
}
ECode CMobileNetworkSettings::constructor()
{
return PreferenceActivity::constructor();
}
ECode CMobileNetworkSettings::OnClick(
/* [in] */ IDialogInterface* dialog,
/* [in] */ Int32 which)
{
if (which == IDialogInterface::BUTTON_POSITIVE) {
mPhone->SetDataRoamingEnabled(TRUE);
mOkClicked = TRUE;
}
else {
// Reset the toggle
ITwoStatePreference::Probe(mButtonDataRoam)->SetChecked(FALSE);
}
return NOERROR;
}
ECode CMobileNetworkSettings::OnDismiss(
/* [in] */ IDialogInterface* dialog)
{
// Assuming that onClick gets called first
return ITwoStatePreference::Probe(mButtonDataRoam)->SetChecked(mOkClicked);
}
ECode CMobileNetworkSettings::OnPreferenceTreeClick(
/* [in] */ IPreferenceScreen* preferenceScreen,
/* [in] */ IPreference* preference,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
*result = FALSE;
/** TODO: Refactor and get rid of the if's using subclasses */
String key;
preference->GetKey(&key);
Boolean res;
if (key.Equals(BUTTON_4G_LTE_KEY)) {
*result = TRUE;
return NOERROR;
}
else if (mGsmUmtsOptions != NULL &&
(mGsmUmtsOptions->PreferenceTreeClick(preference, &res), res)) {
*result = TRUE;
return NOERROR;
}
else if (mCdmaOptions != NULL &&
(mCdmaOptions->PreferenceTreeClick(preference, &res), res)) {
AutoPtr<ISystemProperties> helper;
CSystemProperties::AcquireSingleton((ISystemProperties**)&helper);
String obj;
helper->Get(ITelephonyProperties::PROPERTY_INECM_MODE, &obj);
if (StringUtils::ParseBoolean(obj)) {
mClickedPreference = preference;
// In ECM mode launch ECM app dialog
AutoPtr<IIntent> intent;
CIntent::New(ITelephonyIntents::ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, NULL,
(IIntent**)&intent);
StartActivityForResult(intent, REQUEST_CODE_EXIT_ECM);
}
*result = TRUE;
return NOERROR;
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButtonPreferredNetworkMode)) {
//displays the value taken from the Settings.System
AutoPtr<IContext> context;
mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
mButtonPreferredNetworkMode->SetValue(StringUtils::ToString(settingsNetworkMode));
*result = TRUE;
return NOERROR;
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mLteDataServicePref)) {
AutoPtr<IContentResolver> contentResolver;
GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
String tmpl;
helper->GetString(contentResolver, ISettingsGlobal::SETUP_PREPAID_DATA_SERVICE_URL,
&tmpl);
if (!TextUtils::IsEmpty(tmpl)) {
AutoPtr<IInterface> obj;
GetSystemService(IContext::TELEPHONY_SERVICE, (IInterface**)&obj);
AutoPtr<ITelephonyManager> tm = ITelephonyManager::Probe(obj);
String imsi;
tm->GetSubscriberId(&imsi);
if (imsi.IsNull()) {
imsi = String("");
}
String url;
if (!TextUtils::IsEmpty(tmpl)) {
AutoPtr<ICharSequence> tmplChar = CoreUtils::Convert(tmpl);
AutoPtr<ArrayOf<ICharSequence*> > array = ArrayOf<ICharSequence*>::Alloc(1);
AutoPtr<ICharSequence> imsiChar = CoreUtils::Convert(imsi);
array->Set(0, imsiChar);
AutoPtr<ICharSequence> cchar = TextUtils::ExpandTemplate(tmplChar, array);
cchar->ToString(&url);
}
AutoPtr<IUriHelper> helper;
CUriHelper::AcquireSingleton((IUriHelper**)&helper);
AutoPtr<IUri> _data;
helper->Parse(url, (IUri**)&_data);
AutoPtr<IIntent> intent;
CIntent::New(IIntent::ACTION_VIEW, _data, (IIntent**)&intent);
StartActivity(intent);
}
else {
Logger::E(TAG, "Missing SETUP_PREPAID_DATA_SERVICE_URL");
}
*result = TRUE;
return NOERROR;
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButtonEnabledNetworks)) {
AutoPtr<IContext> context;
mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
mButtonEnabledNetworks->SetValue(StringUtils::ToString(settingsNetworkMode));
*result = TRUE;
return NOERROR;
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButtonDataRoam)) {
// Do not disable the preference screen if the user clicks Data roaming.
*result = TRUE;
return NOERROR;
}
else {
// if the button is anything but the simple toggle preference,
// we'll need to disable all preferences to reject all click
// events until the sub-activity's UI comes up.
IPreference::Probe(preferenceScreen)->SetEnabled(FALSE);
// Let the intents be launched by the Preference manager
*result = FALSE;
return NOERROR;
}
return NOERROR;
}
void CMobileNetworkSettings::SetIMS(
/* [in] */ Boolean turnOn)
{
AutoPtr<ISharedPreferences> imsPref;
assert(0);
// GetSharedPreferences(IImsManager::IMS_SHARED_PREFERENCES, IContext::MODE_WORLD_READABLE,
// (ISharedPreferences**)&imsPref);
AutoPtr<ISharedPreferencesEditor> edit;
imsPref->Edit((ISharedPreferencesEditor**)&edit);
assert(0);
//edit->PutBoolean(IImsManager::KEY_IMS_ON, turnOn);
Boolean tmp;
edit->Commit(&tmp);
}
ECode CMobileNetworkSettings::OnCreate(
/* [in] */ IBundle* icicle)
{
SetTheme(Elastos::Droid::TeleService::R::style::Theme_Material_Settings);
PreferenceActivity::OnCreate(icicle);
mPhone = PhoneGlobals::GetPhone();
mHandler = new MyHandler(this);
AutoPtr<IInterface> obj;
GetSystemService(IContext::USER_SERVICE, (IInterface**)&obj);
mUm = IUserManager::Probe(obj);
Boolean res;
if (mUm->HasUserRestriction(IUserManager::DISALLOW_CONFIG_MOBILE_NETWORKS, &res), res) {
mUnavailable = TRUE;
SetContentView(Elastos::Droid::TeleService::R::layout::telephony_disallowed_preference_screen);
return NOERROR;
}
AddPreferencesFromResource(Elastos::Droid::TeleService::R::xml::network_setting);
AutoPtr<IPreference> preference;
FindPreference(BUTTON_4G_LTE_KEY, (IPreference**)&preference);
mButton4glte = ISwitchPreference::Probe(preference);
AutoPtr<InnerListener> listener = new InnerListener(this);
IPreference::Probe(mButton4glte)->SetOnPreferenceChangeListener(listener);
assert(0);
//mButton4glte->SetChecked(ImsManager::IsEnhanced4gLteModeSettingEnabledByUser(listener));
//try
ECode ec = NOERROR;
{
AutoPtr<IContext> con;
FAIL_GOTO(ec = CreatePackageContext(String("com.android.systemui"), 0, (IContext**)&con), ERROR)
AutoPtr<IResources> resources;
FAIL_GOTO(ec = con->GetResources((IResources**)&resources), ERROR)
Int32 id;
FAIL_GOTO(ec = resources->GetIdentifier(String("config_show4GForLTE"),
String("bool"), String("com.android.systemui"), &id), ERROR)
FAIL_GOTO(ec = resources->GetBoolean(id, &mShow4GForLTE), ERROR)
}
// catch (NameNotFoundException e) {
ERROR:
if (ec == (ECode)E_NAME_NOT_FOUND_EXCEPTION) {
Loge(String("NameNotFoundException for show4GFotLTE"));
mShow4GForLTE = FALSE;
}
//}
//get UI object references
AutoPtr<IPreferenceScreen> prefSet;
GetPreferenceScreen((IPreferenceScreen**)&prefSet);
AutoPtr<IPreference> preference2;
AutoPtr<ICharSequence> cchar2 = CoreUtils::Convert(BUTTON_ROAMING_KEY);
IPreferenceGroup::Probe(prefSet)->FindPreference(cchar2, (IPreference**)&preference2);
mButtonDataRoam = ISwitchPreference::Probe(preference2);
AutoPtr<IPreference> preference3;
AutoPtr<ICharSequence> cchar3 = CoreUtils::Convert(BUTTON_PREFERED_NETWORK_MODE);
IPreferenceGroup::Probe(prefSet)->FindPreference(cchar3, (IPreference**)&preference3);
mButtonPreferredNetworkMode = IListPreference::Probe(preference3);
AutoPtr<IPreference> preference4;
AutoPtr<ICharSequence> cchar4 = CoreUtils::Convert(BUTTON_ENABLED_NETWORKS_KEY);
IPreferenceGroup::Probe(prefSet)->FindPreference(cchar4, (IPreference**)&preference4);
mButtonEnabledNetworks = IListPreference::Probe(preference4);
IPreference::Probe(mButtonDataRoam)->SetOnPreferenceChangeListener(listener);
AutoPtr<ICharSequence> cchar5 = CoreUtils::Convert(BUTTON_CDMA_LTE_DATA_SERVICE_KEY);
IPreferenceGroup::Probe(prefSet)->FindPreference(cchar5, (IPreference**)&mLteDataServicePref);
Int32 mode;
mPhone->GetLteOnCdmaMode(&mode);
Boolean isLteOnCdma = mode == IPhoneConstants::LTE_ON_CDMA_TRUE;
Int32 phoneId;
mPhone->GetPhoneId(&phoneId);
if (isLteOnCdma) {
AutoPtr<IResources> resources;
GetResources((IResources**)&resources);
AutoPtr< ArrayOf<Int32> > ar;
resources->GetInt32Array(Elastos::Droid::TeleService::R::array::config_show_cdma, (ArrayOf<Int32>**)&ar);
mIsGlobalCdma = (*ar)[phoneId] != 0;
}
else {
mIsGlobalCdma = FALSE;
}
AutoPtr<IInterface> obj2;
GetSystemService(IContext::TELEPHONY_SERVICE, (IInterface**)&obj2);
AutoPtr<ITelephonyManager> tm = ITelephonyManager::Probe(obj2);
AutoPtr<IResources> resources;
GetResources((IResources**)&resources);
AutoPtr<ISubscriptionManager> helper;
CSubscriptionManager::AcquireSingleton((ISubscriptionManager**)&helper);
Int64 id;
helper->GetDefaultSubId(&id);
if (tm->GetSimplifiedNetworkSettingsEnabledForSubscriber(id, &res), res) {
Boolean tmp;
IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(mButtonPreferredNetworkMode), &tmp);
IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(mButtonEnabledNetworks), &tmp);
IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(mLteDataServicePref), &tmp);
}
else if (resources->GetBoolean(Elastos::Droid::TeleService::R::bool_::world_phone, &res), res) {
Boolean tmp;
IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(mButtonEnabledNetworks), &tmp);
// set the listener for the mButtonPreferredNetworkMode list preference so we can issue
// change Preferred Network Mode.
IPreference::Probe(mButtonPreferredNetworkMode)->SetOnPreferenceChangeListener(listener);
//Get the networkMode from Settings.System and displays it
AutoPtr<IContext> context;
mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
mButtonPreferredNetworkMode->SetValue(StringUtils::ToString(settingsNetworkMode));
CCdmaOptions::New(this, prefSet, mPhone, (ICdmaOptions**)&mCdmaOptions);
CGsmUmtsOptions::New(this, prefSet, (IGsmUmtsOptions**)&mGsmUmtsOptions);
}
else {
Boolean tmp;
IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(mButtonPreferredNetworkMode), &tmp);
Int32 phoneType;
mPhone->GetPhoneType(&phoneType);
if (phoneType == IPhoneConstants::PHONE_TYPE_CDMA) {
if (isLteOnCdma) {
mButtonEnabledNetworks->SetEntries(
Elastos::Droid::TeleService::R::array::enabled_networks_cdma_choices);
mButtonEnabledNetworks->SetEntryValues(
Elastos::Droid::TeleService::R::array::enabled_networks_cdma_values);
}
CCdmaOptions::New(this, prefSet, mPhone, (ICdmaOptions**)&mCdmaOptions);
}
else if (phoneType == IPhoneConstants::PHONE_TYPE_GSM) {
Boolean res1, res2;
if ((resources->GetBoolean(Elastos::Droid::TeleService::R::bool_::config_prefer_2g, &res1), !res1)
&& (resources->GetBoolean(Elastos::Droid::TeleService::R::bool_::config_enabled_lte, &res2), !res2)) {
mButtonEnabledNetworks->SetEntries(
Elastos::Droid::TeleService::R::array::enabled_networks_except_gsm_lte_choices);
mButtonEnabledNetworks->SetEntryValues(
Elastos::Droid::TeleService::R::array::enabled_networks_except_gsm_lte_values);
}
else if ((resources->GetBoolean(Elastos::Droid::TeleService::R::bool_::config_prefer_2g, &res1), !res1)) {
Int32 select = (mShow4GForLTE == TRUE) ?
Elastos::Droid::TeleService::R::array::enabled_networks_except_gsm_4g_choices
: Elastos::Droid::TeleService::R::array::enabled_networks_except_gsm_choices;
mButtonEnabledNetworks->SetEntries(select);
mButtonEnabledNetworks->SetEntryValues(
Elastos::Droid::TeleService::R::array::enabled_networks_except_gsm_values);
}
else if ((resources->GetBoolean(Elastos::Droid::TeleService::R::bool_::config_enabled_lte, &res1), !res1)) {
mButtonEnabledNetworks->SetEntries(
Elastos::Droid::TeleService::R::array::enabled_networks_except_lte_choices);
mButtonEnabledNetworks->SetEntryValues(
Elastos::Droid::TeleService::R::array::enabled_networks_except_lte_values);
}
else if (mIsGlobalCdma) {
mButtonEnabledNetworks->SetEntries(
Elastos::Droid::TeleService::R::array::enabled_networks_cdma_choices);
mButtonEnabledNetworks->SetEntryValues(
Elastos::Droid::TeleService::R::array::enabled_networks_cdma_values);
}
else {
Int32 select = (mShow4GForLTE == TRUE) ? Elastos::Droid::TeleService::R::array::enabled_networks_4g_choices
: Elastos::Droid::TeleService::R::array::enabled_networks_choices;
mButtonEnabledNetworks->SetEntries(select);
mButtonEnabledNetworks->SetEntryValues(
Elastos::Droid::TeleService::R::array::enabled_networks_values);
}
CGsmUmtsOptions::New(this, prefSet, (IGsmUmtsOptions**)&mGsmUmtsOptions);
}
else {
//throw new IllegalStateException("Unexpected phone type: " + phoneType);
Logger::E(TAG, "Unexpected phone type: %d", phoneType);
return E_ILLEGAL_STATE_EXCEPTION;
}
IPreference::Probe(mButtonEnabledNetworks)->IPreference::Probe((this));
AutoPtr<IContext> context;
mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
if (DBG) Log(String("settingsNetworkMode: ") + StringUtils::ToString(settingsNetworkMode));
mButtonEnabledNetworks->SetValue(StringUtils::ToString(settingsNetworkMode));
}
AutoPtr<IContentResolver> contentResolver;
GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper2;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper2);
String str;
helper2->GetString(contentResolver, ISettingsGlobal::SETUP_PREPAID_DATA_SERVICE_URL, &str);
Boolean missingDataServiceUrl = TextUtils::IsEmpty(str);
if (!isLteOnCdma || missingDataServiceUrl) {
Boolean tmp;
IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(mLteDataServicePref), &tmp);
}
else {
Logger::D(TAG, "keep ltePref");
}
// Enable enhanced 4G LTE mode settings depending on whether exists on platform
assert(0);
// if (!ImsManager::IsEnhanced4gLteModeSettingEnabledByPlatform(this)) {
// AutoPtr<IPreference> pref;
// IPreferenceGroup::Probe(prefSet)->FindPreference(BUTTON_4G_LTE_KEY, (IPreference**)&pref);
// if (pref != NULL) {
// Boolean tmp;
// IPreferenceGroup::Probe(prefSet)->RemovePreference(IPreference::Probe(pref), &tmp);
// }
// }
AutoPtr<IActionBar> actionBar;
GetActionBar((IActionBar**)&actionBar);
if (actionBar != NULL) {
// android.R.id.home will be triggered in onOptionsItemSelected()
actionBar->SetDisplayHomeAsUpEnabled(TRUE);
}
AutoPtr<IUserHandleHelper> helper3;
CUserHandleHelper::AcquireSingleton((IUserHandleHelper**)&helper3);
Int32 uid;
helper3->GetMyUserId(&uid);
Boolean isSecondaryUser = uid != IUserHandle::USER_OWNER;
// Enable link to CMAS app settings depending on the value in config.xml.
Boolean isCellBroadcastAppLinkEnabled;
resources->GetBoolean(
Elastos::Droid::R::bool_::config_cellBroadcastAppLinks, &isCellBroadcastAppLinkEnabled);
Boolean tmp;
if (isSecondaryUser || !isCellBroadcastAppLinkEnabled
|| (mUm->HasUserRestriction(IUserManager::DISALLOW_CONFIG_CELL_BROADCASTS, &tmp), tmp)) {
AutoPtr<IPreferenceScreen> root;
GetPreferenceScreen((IPreferenceScreen**)&root);
AutoPtr<IPreference> ps;
FindPreference(BUTTON_CELL_BROADCAST_SETTINGS, (IPreference**)&ps);
if (ps != NULL) {
Boolean tmp;
IPreferenceGroup::Probe(root)->RemovePreference(ps, &tmp);
}
}
return NOERROR;
}
ECode CMobileNetworkSettings::OnResume()
{
PreferenceActivity::OnResume();
if (mUnavailable) {
return NOERROR;
}
// upon resumption from the sub-activity, make sure we re-enable the
// preferences.
AutoPtr<IPreferenceScreen> preferenceScreen;
GetPreferenceScreen((IPreferenceScreen**)&preferenceScreen);
IPreference::Probe(preferenceScreen)->SetEnabled(TRUE);
// Set UI state in onResume because a user could go home, launch some
// app to change this setting's backend, and re-launch this settings app
// and the UI state would be inconsistent with actual state
Boolean res;
ITwoStatePreference::Probe(mButtonDataRoam)->SetChecked((mPhone->GetDataRoamingEnabled(&res), res));
AutoPtr<IPreference> preference;
AutoPtr<ICharSequence> cchar1 = CoreUtils::Convert(BUTTON_PREFERED_NETWORK_MODE);
IPreferenceGroup::Probe(preferenceScreen)->FindPreference(cchar1, (IPreference**)&preference);
if (preference != NULL) {
AutoPtr<IMessage> m;
mHandler->ObtainMessage(
MyHandler::MESSAGE_GET_PREFERRED_NETWORK_TYPE, (IMessage**)&m);
mPhone->GetPreferredNetworkType(m);
}
AutoPtr<IPreference> preference2;
AutoPtr<ICharSequence> cchar2 = CoreUtils::Convert(BUTTON_ENABLED_NETWORKS_KEY);
IPreferenceGroup::Probe(preferenceScreen)->FindPreference(cchar2, (IPreference**)&preference2);
if (preference2 != NULL) {
AutoPtr<IMessage> m;
mHandler->ObtainMessage(
MyHandler::MESSAGE_GET_PREFERRED_NETWORK_TYPE, (IMessage**)&m);
mPhone->GetPreferredNetworkType(m);
}
return NOERROR;
}
ECode CMobileNetworkSettings::OnPause()
{
return PreferenceActivity::OnPause();
}
ECode CMobileNetworkSettings::OnPreferenceChange(
/* [in] */ IPreference* preference,
/* [in] */ IInterface* objValue,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButtonPreferredNetworkMode)) {
//NOTE onPreferenceChange seems to be called even if there is no change
//Check if the button value is changed from the System.Setting
AutoPtr<ICharSequence> cchar = ICharSequence::Probe(objValue);
String str;
cchar->ToString(&str);
mButtonPreferredNetworkMode->SetValue(str);
Int32 buttonNetworkMode = StringUtils::ParseInt32(str);
AutoPtr<IContext> context;
mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
if (buttonNetworkMode != settingsNetworkMode) {
Int32 modemNetworkMode;
// if new mode is invalid ignore it
switch (buttonNetworkMode) {
case IPhone::NT_MODE_WCDMA_PREF:
case IPhone::NT_MODE_GSM_ONLY:
case IPhone::NT_MODE_WCDMA_ONLY:
case IPhone::NT_MODE_GSM_UMTS:
case IPhone::NT_MODE_CDMA:
case IPhone::NT_MODE_CDMA_NO_EVDO:
case IPhone::NT_MODE_EVDO_NO_CDMA:
case IPhone::NT_MODE_GLOBAL:
case IPhone::NT_MODE_LTE_CDMA_AND_EVDO:
case IPhone::NT_MODE_LTE_GSM_WCDMA:
case IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
case IPhone::NT_MODE_LTE_ONLY:
case IPhone::NT_MODE_LTE_WCDMA:
// This is one of the modes we recognize
modemNetworkMode = buttonNetworkMode;
break;
default:
StringBuilder sb;
sb += "Invalid Network Mode (";
sb += buttonNetworkMode;
sb += ") chosen. Ignore.";
Loge(sb.ToString());
*result = TRUE;
return NOERROR;
}
UpdatePreferredNetworkModeSummary(buttonNetworkMode);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Boolean res;
helper->PutInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
buttonNetworkMode, &res);
//Set the modem network mode
AutoPtr<IMessage> m;
mHandler->ObtainMessage(
MyHandler::MESSAGE_SET_PREFERRED_NETWORK_TYPE, (IMessage**)&m);
mPhone->SetPreferredNetworkType(modemNetworkMode, m);
}
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButtonEnabledNetworks)) {
AutoPtr<ICharSequence> cchar = ICharSequence::Probe(objValue);
String str;
cchar->ToString(&str);
mButtonEnabledNetworks->SetValue(str);
Int32 buttonNetworkMode = StringUtils::ParseInt32(str);
if (DBG) Log(String("buttonNetworkMode: ") + StringUtils::ToString(buttonNetworkMode));
AutoPtr<IContext> context;
mPhone->GetContext((IContext**)&context);
AutoPtr<IContentResolver> contentResolver;
context->GetContentResolver((IContentResolver**)&contentResolver);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Int32 settingsNetworkMode;
helper->GetInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
sPreferredNetworkMode, &settingsNetworkMode);
if (buttonNetworkMode != settingsNetworkMode) {
Int32 modemNetworkMode;
// if new mode is invalid ignore it
switch (buttonNetworkMode) {
case IPhone::NT_MODE_WCDMA_PREF:
case IPhone::NT_MODE_GSM_ONLY:
case IPhone::NT_MODE_LTE_GSM_WCDMA:
case IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
case IPhone::NT_MODE_CDMA:
case IPhone::NT_MODE_CDMA_NO_EVDO:
case IPhone::NT_MODE_LTE_CDMA_AND_EVDO:
// This is one of the modes we recognize
modemNetworkMode = buttonNetworkMode;
break;
default:
StringBuilder sb;
sb += "Invalid Network Mode (";
sb += buttonNetworkMode;
sb += ") chosen. Ignore.";
Loge(sb.ToString());
*result = TRUE;
return NOERROR;
}
UpdateEnabledNetworksValueAndSummary(buttonNetworkMode);
AutoPtr<ISettingsGlobal> helper;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&helper);
Boolean res;
helper->PutInt32(contentResolver, ISettingsGlobal::PREFERRED_NETWORK_MODE,
buttonNetworkMode, &res);
//Set the modem network mode
AutoPtr<IMessage> m;
mHandler->ObtainMessage(
MyHandler::MESSAGE_SET_PREFERRED_NETWORK_TYPE, (IMessage**)&m);
mPhone->SetPreferredNetworkType(modemNetworkMode, m);
}
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButton4glte)) {
AutoPtr<ISwitchPreference> ltePref = ISwitchPreference::Probe(preference);
Boolean res;
ITwoStatePreference::Probe(ltePref)->SetChecked((ITwoStatePreference::Probe(ltePref)->IsChecked(&res), !res));
SetIMS((ITwoStatePreference::Probe(ltePref)->IsChecked(&res), res));
assert(0);
// AutoPtr<IImsManager> imsMan = ImsManager::GetInstance(getBaseContext(),
// SubscriptionManager::GetDefaultVoiceSubId());
// if (imsMan != NULL) {
// //try {
// imsMan->SetAdvanced4GMode(ltePref->IsChecked(&res), res);
// //} catch (ImsException ie) {
// // do nothing
// //}
// }
}
else if (TO_IINTERFACE(preference) == TO_IINTERFACE(mButtonDataRoam)) {
if (DBG) Log(String("onPreferenceTreeClick: preference == mButtonDataRoam."));
//normally called on the toggle click
Boolean res;
if ((ITwoStatePreference::Probe(mButtonDataRoam)->IsChecked(&res), !res)) {
AutoPtr<InnerListener> listener = new InnerListener(this);
// First confirm with a warning dialog about charges
mOkClicked = FALSE;
AutoPtr<IAlertDialogBuilder> builder;
CAlertDialogBuilder::New(this, (IAlertDialogBuilder**)&builder);
AutoPtr<IResources> resources;
GetResources((IResources**)&resources);
String str;
resources->GetString(Elastos::Droid::TeleService::R::string::roaming_warning, &str);
AutoPtr<ICharSequence> cchar = CoreUtils::Convert(str);
builder->SetMessage(cchar);
builder->SetTitle(Elastos::Droid::R::string::dialog_alert_title);
builder->SetIconAttribute(Elastos::Droid::R::attr::alertDialogIcon);
builder->SetPositiveButton(Elastos::Droid::R::string::yes, listener);
builder->SetNegativeButton(Elastos::Droid::R::string::no, listener);
AutoPtr<IAlertDialog> dialog;
builder->Show((IAlertDialog**)&dialog);
builder->SetOnDismissListener(listener);
}
else {
mPhone->SetDataRoamingEnabled(FALSE);
}
*result = TRUE;
return NOERROR;
}
// always let the preference setting proceed.
*result = TRUE;
return NOERROR;
}
void CMobileNetworkSettings::UpdatePreferredNetworkModeSummary(
/* [in] */ Int32 NetworkMode)
{
switch(NetworkMode) {
case IPhone::NT_MODE_WCDMA_PREF:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_wcdma_perf_summary);
break;
case IPhone::NT_MODE_GSM_ONLY:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_gsm_only_summary);
break;
case IPhone::NT_MODE_WCDMA_ONLY:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_wcdma_only_summary);
break;
case IPhone::NT_MODE_GSM_UMTS:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_gsm_wcdma_summary);
break;
case IPhone::NT_MODE_CDMA:
Int32 mode;
mPhone->GetLteOnCdmaMode(&mode);
switch (mode) {
case IPhoneConstants::LTE_ON_CDMA_TRUE:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_cdma_summary);
break;
case IPhoneConstants::LTE_ON_CDMA_FALSE:
default:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_cdma_evdo_summary);
break;
}
break;
case IPhone::NT_MODE_CDMA_NO_EVDO:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_cdma_only_summary);
break;
case IPhone::NT_MODE_EVDO_NO_CDMA:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_evdo_only_summary);
break;
case IPhone::NT_MODE_LTE_ONLY:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_lte_summary);
break;
case IPhone::NT_MODE_LTE_GSM_WCDMA:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_lte_gsm_wcdma_summary);
break;
case IPhone::NT_MODE_LTE_CDMA_AND_EVDO:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_lte_cdma_evdo_summary);
break;
case IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_global_summary);
break;
case IPhone::NT_MODE_GLOBAL:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_cdma_evdo_gsm_wcdma_summary);
break;
case IPhone::NT_MODE_LTE_WCDMA:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_lte_wcdma_summary);
break;
default:
IPreference::Probe(mButtonPreferredNetworkMode)->SetSummary(
Elastos::Droid::TeleService::R::string::preferred_network_mode_global_summary);
}
}
void CMobileNetworkSettings::UpdateEnabledNetworksValueAndSummary(
/* [in] */ Int32 NetworkMode)
{
switch (NetworkMode) {
case IPhone::NT_MODE_WCDMA_ONLY:
case IPhone::NT_MODE_GSM_UMTS:
case IPhone::NT_MODE_WCDMA_PREF:
if (!mIsGlobalCdma) {
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_WCDMA_PREF));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_3G);
}
else {
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_global);
}
break;
case IPhone::NT_MODE_GSM_ONLY:
if (!mIsGlobalCdma) {
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_GSM_ONLY));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_2G);
}
else {
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_global);
}
break;
case IPhone::NT_MODE_LTE_GSM_WCDMA:
case IPhone::NT_MODE_LTE_ONLY:
case IPhone::NT_MODE_LTE_WCDMA:
if (!mIsGlobalCdma) {
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_LTE_GSM_WCDMA));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary((mShow4GForLTE == true)
? Elastos::Droid::TeleService::R::string::network_4G :
Elastos::Droid::TeleService::R::string::network_lte);
} else {
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_global);
}
break;
case IPhone::NT_MODE_LTE_CDMA_AND_EVDO:
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_LTE_CDMA_AND_EVDO));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_lte);
break;
case IPhone::NT_MODE_CDMA:
case IPhone::NT_MODE_EVDO_NO_CDMA:
case IPhone::NT_MODE_GLOBAL:
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_CDMA));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_3G);
break;
case IPhone::NT_MODE_CDMA_NO_EVDO:
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_CDMA_NO_EVDO));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_1x);
break;
case IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
mButtonEnabledNetworks->SetValue(
StringUtils::ToString(IPhone::NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(Elastos::Droid::TeleService::R::string::network_global);
break;
default:
{
StringBuilder sb;
sb += "Invalid Network Mode (";
sb += NetworkMode;
sb += "). Ignore.";
String errMsg = sb.ToString();
Loge(errMsg);
AutoPtr<ICharSequence> cchar = CoreUtils::Convert(errMsg);
IPreference::Probe(mButtonEnabledNetworks)->SetSummary(cchar);
}
}
}
ECode CMobileNetworkSettings::OnActivityResult(
/* [in] */ Int32 requestCode,
/* [in] */ Int32 resultCode,
/* [in] */ IIntent* data)
{
switch(requestCode) {
case REQUEST_CODE_EXIT_ECM:
Boolean isChoiceYes;
data->GetBooleanExtra(IEmergencyCallbackModeExitDialog::EXTRA_EXIT_ECM_RESULT,
FALSE, &isChoiceYes);
if (isChoiceYes) {
// If the phone exits from ECM mode, show the CDMA Options
mCdmaOptions->ShowDialog(mClickedPreference);
}
else {
// do nothing
}
break;
default:
break;
}
return NOERROR;
}
void CMobileNetworkSettings::Log(
/* [in] */ const String& msg)
{
Logger::D(TAG, msg);
}
void CMobileNetworkSettings::Loge(
/* [in] */ const String& msg)
{
Logger::E(TAG, msg);
}
ECode CMobileNetworkSettings::OnOptionsItemSelected(
/* [in] */ IMenuItem* item,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
Int32 itemId;
item->GetItemId(&itemId);
if (itemId == Elastos::Droid::R::id::home) { // See ActionBar#setDisplayHomeAsUpEnabled()
// Commenting out "logical up" capability. This is a workaround for issue 5278083.
//
// Settings app may not launch this activity via UP_ACTIVITY_CLASS but the other
// Activity that looks exactly same as UP_ACTIVITY_CLASS ("SubSettings" Activity).
// At that moment, this Activity launches UP_ACTIVITY_CLASS on top of the Activity.
// which confuses users.
// TODO: introduce better mechanism for "up" capability here.
/*Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName(UP_ACTIVITY_PACKAGE, UP_ACTIVITY_CLASS);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);*/
Finish();
*result = TRUE;
return NOERROR;
}
return PreferenceActivity::OnOptionsItemSelected(item, result);
}
} // namespace Phone
} // namespace TeleService
} // namespace Droid
} // namespace Elastos
| 43.49 | 128 | 0.644401 | [
"object"
] |
d36d51bac863eea0355ccb6b4db24d964d2b77dd | 19,128 | cpp | C++ | src/algorithms/unchop.cpp | Ellmen/vg | f9f5a815ef2db3481b23ff2533355aaf7f2f947b | [
"MIT"
] | 1 | 2021-11-16T21:23:49.000Z | 2021-11-16T21:23:49.000Z | src/algorithms/unchop.cpp | CominLab/VG-SNP-Aware | 6e28125879ad7b5b9b0d160d19406e69278a0e58 | [
"MIT"
] | null | null | null | src/algorithms/unchop.cpp | CominLab/VG-SNP-Aware | 6e28125879ad7b5b9b0d160d19406e69278a0e58 | [
"MIT"
] | null | null | null | /**
* \file unchop.cpp
*
* Defines an algorithm to join adjacent handles.
*/
#include "unchop.hpp"
#include <unordered_set>
#include <list>
#include <set>
#include <iostream>
#include <sstream>
namespace vg {
namespace algorithms {
using namespace std;
/// Return true if nodes share all paths and the mappings they share in these paths
/// are adjacent, in the specified relative order and orientation.
static bool nodes_are_perfect_path_neighbors(PathHandleGraph* graph, handle_t left_handle, handle_t right_handle) {
#ifdef debug
cerr << "Check if " << graph->get_id(left_handle) << (graph->get_is_reverse(left_handle) ? "-" : "+") << " and "
<< graph->get_id(right_handle) << (graph->get_is_reverse(right_handle) ? "-" : "+") << " are perfect path neighbors" << endl;
#endif
// Set this false if we find an impermissible step
bool ok = true;
// Count the number of permissible steps on the next node we find
size_t expected_next = 0;
graph->for_each_step_on_handle(left_handle, [&](const step_handle_t& here) {
// For each path step on the left
// We need to work out if the path traverses this handle backward.
bool step_is_to_reverse_of_handle = (graph->get_handle_of_step(here) != left_handle);
#ifdef debug
cerr << "Consider visit of path " << graph->get_path_name(graph->get_path_handle_of_step(here))
<< " to " << (step_is_to_reverse_of_handle ? "reverse" : "forward") << " orientation of handle" << endl;
#endif
if (!(step_is_to_reverse_of_handle ? graph->has_previous_step(here) : graph->has_next_step(here))) {
// If there's no visit to the right of this handle, it can't be to the right next place
#ifdef debug
cerr << "Path stops here so no subsequent handle is a perfect path neighbor" << endl;
#endif
ok = false;
return false;
}
// Walk along the path whatever direction is forward relative to our left handle.
step_handle_t step_to_right = step_is_to_reverse_of_handle ? graph->get_previous_step(here) : graph->get_next_step(here);
handle_t handle_to_right = graph->get_handle_of_step(step_to_right);
if (step_is_to_reverse_of_handle) {
// If we had to walk back along the reverse strand of the path, we have to flip where we ended up.
handle_to_right = graph->flip(handle_to_right);
}
if (handle_to_right != right_handle) {
// It goes to the wrong next place
#ifdef debug
cerr << "Path goes to the wrong place ("
<< graph->get_id(handle_to_right) << (graph->get_is_reverse(handle_to_right) ? "-" : "+")
<< ") and so these nodes are not perfect path neighbors" << endl;
#endif
ok = false;
return false;
}
// Otherwise, record a step that is allowed to exist on the next handle
expected_next++;
return true;
});
if (!ok) {
// We found a bad step, or the path stopped.
return false;
}
// Now count up the path steps on the right handle
size_t observed_next = 0;
graph->for_each_step_on_handle(right_handle, [&](const step_handle_t& ignored) {
#ifdef debug
cerr << "Next node has path " << graph->get_path_name(graph->get_path_handle_of_step(ignored)) << endl;
#endif
observed_next++;
});
#ifdef debug
if (observed_next != expected_next) {
cerr << "Next node has " << observed_next << " path visits but should have " << expected_next << endl;
}
#endif
// If there are any steps on the right node that weren't accounted for on
// the left node, fail. Otherwise, succeed.
return observed_next == expected_next;
}
/// Get the set of components that could be merged into single nodes without
/// changing the path space of the graph. Emits oriented traversals of
/// nodes, in the order and orientation in which they are to be merged.
static set<list<handle_t>> simple_components(PathHandleGraph* graph, int min_size = 1) {
// go around and establish groupings
unordered_set<id_t> seen;
set<list<handle_t>> components;
graph->for_each_handle([&](const handle_t& n) {
id_t n_id = graph->get_id(n);
if (seen.count(n_id)) {
// We already found this node in a previous component
return;
}
#ifdef debug
cerr << "Component based on " << n_id << endl;
#endif
seen.insert(n_id);
// go left and right through each as far as we have only single edges connecting us
// to nodes that have only single edges coming in or out
// that go to other nodes
list<handle_t> c;
// go left
{
handle_t l = n;
vector<handle_t> prev;
graph->follow_edges(l, true, [&](const handle_t& h) {
prev.push_back(h);
});
#ifdef debug
cerr << "\tLeft: ";
for (auto& x : prev) {
cerr << graph->get_id(x) << (graph->get_is_reverse(x) ? '-' : '+')
<< "(" << graph->get_degree(x, false) << " edges right) ";
graph->follow_edges(x, false, [&](const handle_t& other) {
cerr << "(to " << graph->get_id(other) << (graph->get_is_reverse(other) ? '-' : '+') << ") ";
});
}
cerr << endl;
#endif
while (prev.size() == 1
&& graph->get_degree(prev.front(), false) == 1) {
// While there's only one node left of here, and one node right of that node...
auto last = l;
// Move over left to that node
l = prev.front();
// avoid merging if it breaks stored paths
if (!nodes_are_perfect_path_neighbors(graph, l, last)) {
#ifdef debug
cerr << "\tNot perfect neighbors!" << endl;
#endif
break;
}
// avoid merging if it's already in this or any other component (catch self loops)
if (seen.count(graph->get_id(l))) {
#ifdef debug
cerr << "\tAlready seen!" << endl;
#endif
break;
}
prev.clear();
graph->follow_edges(l, true, [&](const handle_t& h) {
prev.push_back(h);
});
#ifdef debug
cerr << "\tLeft: ";
for (auto& x : prev) {
cerr << graph->get_id(x) << (graph->get_is_reverse(x) ? '-' : '+')
<< "(" << graph->get_degree(x, false) << " edges right) ";
graph->follow_edges(x, false, [&](const handle_t& other) {
cerr << "(to " << graph->get_id(other) << (graph->get_is_reverse(other) ? '-' : '+') << ") ";
});
}
cerr << endl;
#endif
c.push_front(l);
seen.insert(graph->get_id(l));
}
}
// add the node (in the middle)
c.push_back(n);
// go right
{
handle_t r = n;
vector<handle_t> next;
graph->follow_edges(r, false, [&](const handle_t& h) {
next.push_back(h);
});
#ifdef debug
cerr << "\tRight: ";
for (auto& x : next) {
cerr << graph->get_id(x) << (graph->get_is_reverse(x) ? '-' : '+')
<< "(" << graph->get_degree(x, true) << " edges left) ";
graph->follow_edges(x, true, [&](const handle_t& other) {
cerr << "(to " << graph->get_id(other) << (graph->get_is_reverse(other) ? '-' : '+') << ") ";
});
}
cerr << endl;
#endif
while (next.size() == 1
&& graph->get_degree(next.front(), true) == 1) {
// While there's only one node right of here, and one node left of that node...
auto last = r;
// Move over right to that node
r = next.front();
// avoid merging if it breaks stored paths
if (!nodes_are_perfect_path_neighbors(graph, last, r)) {
#ifdef debug
cerr << "\tNot perfect neighbors!" << endl;
#endif
break;
}
// avoid merging if it's already in this or any other component (catch self loops)
if (seen.count(graph->get_id(r))) {
#ifdef debug
cerr << "\tAlready seen!" << endl;
#endif
break;
}
next.clear();
graph->follow_edges(r, false, [&](const handle_t& h) {
next.push_back(h);
});
#ifdef debug
cerr << "\tRight: ";
for (auto& x : next) {
cerr << graph->get_id(x) << (graph->get_is_reverse(x) ? '-' : '+')
<< "(" << graph->get_degree(x, true) << " edges left) ";
graph->follow_edges(x, true, [&](const handle_t& other) {
cerr << "(to " << graph->get_id(other) << (graph->get_is_reverse(other) ? '-' : '+') << ") ";
});
}
cerr << endl;
#endif
c.push_back(r);
seen.insert(graph->get_id(r));
}
}
if (c.size() >= min_size) {
components.emplace(std::move(c));
}
});
#ifdef debug
cerr << "components " << endl;
for (auto& c : components) {
for (auto x : c) {
cerr << graph->get_id(x) << (graph->get_is_reverse(x) ? '-' : '+') << " ";
}
cerr << endl;
}
#endif
return components;
}
/// Concatenates the nodes into a new node with the same external linkage as
/// the provided component. All handles must be in left to right order and a
/// consistent orientation. All paths present must run all the way through the
/// run of nodes from start to end or end to start.
///
/// Returns the handle to the newly created node.
///
/// After calling this on a vg::VG, paths will be invalid until
/// Paths::compact_ranks() is called.
static handle_t concat_nodes(handlegraph::MutablePathDeletableHandleGraph* graph, const list<handle_t>& nodes) {
// Make sure we have at least 2 nodes
assert(!nodes.empty() && nodes.front() != nodes.back());
#ifdef debug
cerr << "Paths before concat: " << endl;
graph->for_each_path_handle([&](const path_handle_t p) {
cerr << graph->get_path_name(p) << ": ";
for (auto h : graph->scan_path(p)) {
cerr << graph->get_id(h) << (graph->get_is_reverse(h) ? '-' : '+') << " ";
}
cerr << endl;
});
#endif
// We also require no edges enter or leave the run of nodes, but we can't check that now.
// Make the new node
handle_t new_node;
{
stringstream ss;
for (auto& n : nodes) {
ss << graph->get_sequence(n);
}
new_node = graph->create_handle(ss.str());
}
#ifdef debug
cerr << "Concatenating ";
for (auto& n : nodes) {
cerr << graph->get_id(n) << (graph->get_is_reverse(n) ? "-" : "+") << " ";
}
cerr << "into " << graph->get_id(new_node) << "+" << endl;
#endif
// We should be able to rely on our handle graph to deduplicate edges, but see https://github.com/vgteam/libbdsg/issues/39
// So we deduplicate ourselves.
// Find all the neighbors. Make sure to translate edges to the other end of
// the run, or self loops.
unordered_set<handle_t> left_neighbors;
graph->follow_edges(nodes.front(), true, [&](const handle_t& left_neighbor) {
if (left_neighbor == nodes.back()) {
// Loop back to the end
left_neighbors.insert(new_node);
} else if (left_neighbor == graph->flip(nodes.front())) {
// Loop back to the front
left_neighbors.insert(graph->flip(new_node));
} else {
// Normal edge
left_neighbors.insert(left_neighbor);
}
});
unordered_set<handle_t> right_neighbors;
graph->follow_edges(nodes.back(), false, [&](const handle_t& right_neighbor) {
if (right_neighbor == nodes.front()) {
// Loop back to the front.
// We will have seen it from the other side, so ignore it here.
} else if (right_neighbor == graph->flip(nodes.back())) {
// Loop back to the end
right_neighbors.insert(graph->flip(new_node));
} else {
// Normal edge
right_neighbors.insert(right_neighbor);
}
});
// Make all the edges, now that we can't interfere with edge listing
for (auto& n : left_neighbors) {
#ifdef debug
cerr << "Creating edge " << graph->get_id(n) << (graph->get_is_reverse(n) ? "-" : "+") << " -> "
<< graph->get_id(new_node) << (graph->get_is_reverse(new_node) ? "-" : "+") << endl;
#endif
graph->create_edge(n, new_node);
}
for (auto& n : right_neighbors) {
#ifdef debug
cerr << "Creating edge " << graph->get_id(new_node) << (graph->get_is_reverse(new_node) ? "-" : "+") << " -> "
<< graph->get_id(n) << (graph->get_is_reverse(n) ? "-" : "+") << endl;
#endif
graph->create_edge(new_node, n);
}
{
// Collect the first and last visits along paths. TODO: this requires
// walking each path all the way through.
//
// This contains the first and last handles in path orientation, and a flag
// for if the path runs along the reverse strand of our run of nodes.
vector<tuple<step_handle_t, step_handle_t, bool>> ranges_to_rewrite;
graph->for_each_step_on_handle(nodes.front(), [&](const step_handle_t& front_step) {
auto path = graph->get_path_handle_of_step(front_step);
#ifdef debug
cerr << "Consider path " << graph->get_path_name(path) << endl;
#endif
// If we don't get the same oriented node as where this step is
// stepping, we must be stepping on the other orientation.
bool runs_reverse = (graph->get_handle_of_step(front_step) != nodes.front());
step_handle_t back_step = front_step;
while(graph->get_handle_of_step(back_step) != (runs_reverse ? graph->flip(nodes.back()) : nodes.back())) {
// Until we find the step on the path that visits the last node in our run.
// Go along the path towards where our last node should be, in our forward orientation.
back_step = runs_reverse ? graph->get_previous_step(back_step) : graph->get_next_step(back_step);
}
// Now we can record the range to rewrite
// Make sure to put it into path-forward order
if (runs_reverse) {
#ifdef debug
cerr << "\tGoing to rewrite between " << graph->get_id(graph->get_handle_of_step(front_step)) << " and " << graph->get_id(graph->get_handle_of_step(back_step)) << " backward" << endl;
#endif
ranges_to_rewrite.emplace_back(back_step, front_step, true);
} else {
#ifdef debug
cerr << "\tGoing to rewrite between " << graph->get_id(graph->get_handle_of_step(front_step)) << " and " << graph->get_id(graph->get_handle_of_step(back_step)) << endl;
#endif
ranges_to_rewrite.emplace_back(front_step, back_step, false);
}
});
for (auto& range : ranges_to_rewrite) {
// Rewrite each range to visit the new node in the appropriate orientation instead of whatever it did before
// Make sure to advance the end of the range because rewrite is end-exclusive (to allow insert).
graph->rewrite_segment(get<0>(range), graph->get_next_step(get<1>(range)), {get<2>(range) ? graph->flip(new_node) : new_node});
}
}
// Destroy all the old edges
// We know they only exist to the left and right neighbors, and along the run
for (auto& n : left_neighbors) {
graph->destroy_edge(n, nodes.front());
}
for (auto& n : right_neighbors) {
graph->destroy_edge(nodes.back(), n);
}
auto it = nodes.begin();
auto next_it = it;
++next_it;
while (next_it != nodes.end()) {
graph->destroy_edge(*it, *next_it);
it = next_it;
++next_it;
}
for (auto& n : nodes) {
// Destroy all the old nodes
#ifdef debug
cerr << "Destroying node " << graph->get_id(n) << endl;
#endif
graph->destroy_handle(n);
}
#ifdef debug
cerr << "Paths after concat: " << endl;
graph->for_each_path_handle([&](const path_handle_t p) {
cerr << graph->get_path_name(p) << ": ";
for (auto h : graph->scan_path(p)) {
cerr << graph->get_id(h) << (graph->get_is_reverse(h) ? '-' : '+') << " ";
}
cerr << endl;
});
#endif
// Return the new handle we merged to.
return new_node;
}
void unchop(handlegraph::MutablePathDeletableHandleGraph* graph) {
#ifdef debug
cerr << "Running unchop" << endl;
#endif
for (auto& comp : simple_components(graph, 2)) {
#ifdef debug
cerr << "Unchop " << comp.size() << " nodes together" << endl;
#endif
concat_nodes(graph, comp);
}
}
void chop(handlegraph::MutableHandleGraph* graph, size_t max_node_length) {
// borrowed from https://github.com/vgteam/odgi/blob/master/src/subcommand/chop_main.cpp
std::vector<handle_t> to_chop;
graph->for_each_handle([&](const handle_t& handle) {
if (graph->get_length(handle) > max_node_length) {
to_chop.push_back(handle);
}
});
for (auto& handle : to_chop) {
// get divide points
uint64_t length = graph->get_length(handle);
std::vector<size_t> offsets;
for (uint64_t i = max_node_length; i < length; i+=max_node_length) {
offsets.push_back(i);
}
graph->divide_handle(handle, offsets);
}
}
}
}
| 38.256 | 199 | 0.533668 | [
"vector"
] |
d36e1d54d7723432c10d3fb96890ca256c69c730 | 1,488 | hpp | C++ | include/3d_line_detection/HoughTransform.hpp | xmba15/3d_line_detection | a287339caa88b257427dc5ec7c292d7e4695cf67 | [
"MIT"
] | 1 | 2021-09-15T12:04:00.000Z | 2021-09-15T12:04:00.000Z | include/3d_line_detection/HoughTransform.hpp | TANHAIYU/3d_line_detection | c62d9252b1e379b295e619a26afea88e03d556be | [
"MIT"
] | null | null | null | include/3d_line_detection/HoughTransform.hpp | TANHAIYU/3d_line_detection | c62d9252b1e379b295e619a26afea88e03d556be | [
"MIT"
] | 2 | 2021-09-15T12:07:49.000Z | 2022-02-24T06:09:10.000Z | /**
* @file HoughTransform.hpp
*
* @author btran
*
*/
#pragma once
#include <vector>
#include <pcl/ModelCoefficients.h>
#include <pcl/common/common.h>
#include "LineSegment3D.hpp"
#include "Sphere.hpp"
namespace perception
{
template <typename POINT_CLOUD_TYPE> class HoughTransform
{
public:
using PointCloudType = POINT_CLOUD_TYPE;
using PointCloud = pcl::PointCloud<PointCloudType>;
using PointCloudPtr = typename PointCloud::Ptr;
using Sphere = geometry::Sphere;
using LineSegment3D = geometry::LineSegment3D<PointCloudType>;
using LineSegment3Ds = std::vector<LineSegment3D>;
struct Param {
std::size_t numRangeBin = 64;
std::size_t sphereGranularity = 5; // value from 0 to geometry::Sphere::MAX_SUBDIVISION-1
std::size_t minNumVote = 10;
float distanceToLineThresh = 0.2;
};
explicit HoughTransform(const Param& param);
LineSegment3Ds run(const PointCloudPtr& cloud);
private:
int getLine(pcl::ModelCoefficients& coeffs, const float minRange, const float deltaRange,
const std::vector<std::size_t>& accumulatorCellIndices) const;
float calcNorm(const PointCloudType& point) const;
void votePoint(const PointCloudType& point, const float minRange, const float deltaRange, const bool toAdd);
private:
Param m_param;
std::vector<std::size_t> m_accumulator;
const Sphere& m_sphere;
};
} // namespace perception
#include "impl/HoughTransform.ipp"
| 26.105263 | 112 | 0.713038 | [
"geometry",
"vector"
] |
d3764702a5a9920d1137308987b326831a209e80 | 1,988 | cpp | C++ | SerialHMD/source/driver_serialhmd.cpp | Seneral/SerialHMD | d01fa216fd9290c4d2ee5e664bbd54edf8a9e747 | [
"MIT"
] | 4 | 2019-03-14T11:51:57.000Z | 2020-09-21T15:47:12.000Z | SerialHMD/source/driver_serialhmd.cpp | Seneral/SerialHMD | d01fa216fd9290c4d2ee5e664bbd54edf8a9e747 | [
"MIT"
] | null | null | null | SerialHMD/source/driver_serialhmd.cpp | Seneral/SerialHMD | d01fa216fd9290c4d2ee5e664bbd54edf8a9e747 | [
"MIT"
] | 1 | 2021-04-12T21:14:09.000Z | 2021-04-12T21:14:09.000Z | // ON WINDOWS, compile with MSVC (e.g. Visual Studio) - gcc or g++ won't work since they produce libraries which Steam can't interact with properly!!
// ON LINUX - no tested. I did start off with Linux though, so atleast the base should throw no errors, and I might try again once there are VR games on Linux!
#include <openvr_driver.h>
#include <SerialHMDShared.h>
#include <SerialHMDDriver.h>
#include <SerialHMDServer.h>
#include <SerialHMDWatchdog.h>
#include <vector>
using namespace vr;
// *******************************************************
// Platform Dependencies
// *******************************************************
#if defined(_WIN32)
// Windows
#include <windows.h>
#define HMD_DLL_EXPORT extern "C" __declspec(dllexport)
#define HMD_DLL_IMPORT extern "C" __declspec(dllimport)
#elif defined(__GNUC__) || defined(COMPILER_GCC) || defined(__APPLE__)
// UNIX
#define HMD_DLL_EXPORT extern "C" __attribute__((visibility("default")))
#define HMD_DLL_IMPORT extern "C"
#define __stdcall
#define __out
#define __in
#define BYTE unsigned char
#define WORD unsigned short
#define SHORT short
#define DWORD unsigned int
#define HMODULE void *
#define strcmp strcasecmp
#else
#error "Unsupported Platform."
#endif
// *******************************************************
// Creates instances of the other driver parts on request
// First watchdog, and once watchdog recognizes an HMD, the server
// *******************************************************
SerialHMDServer g_hmdServer;
SerialHMDWatchdog g_hmdWatchdog;
HMD_DLL_EXPORT void *HmdDriverFactory(const char *pInterfaceName, int *pReturnCode)
{
if (strcmp(IServerTrackedDeviceProvider_Version, pInterfaceName) == 0)
{
return &g_hmdServer;
}
if (strcmp(IVRWatchdogProvider_Version, pInterfaceName) == 0)
{
return &g_hmdWatchdog;
}
if (pReturnCode)
*pReturnCode = VRInitError_Init_InterfaceNotFound;
return NULL;
}
| 27.611111 | 160 | 0.651408 | [
"vector"
] |
c96548aa24f28c92899440999c6033a522bf83a3 | 1,434 | hpp | C++ | include/fea/rendering/renderentity.hpp | CptAsgard/featherkit | 84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5 | [
"Zlib"
] | 22 | 2015-01-13T10:49:38.000Z | 2020-12-23T15:25:59.000Z | include/fea/rendering/renderentity.hpp | CptAsgard/featherkit | 84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5 | [
"Zlib"
] | 27 | 2015-01-11T03:47:27.000Z | 2015-12-10T17:52:17.000Z | include/fea/rendering/renderentity.hpp | CptAsgard/featherkit | 84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5 | [
"Zlib"
] | 7 | 2015-09-18T15:06:45.000Z | 2020-02-19T15:12:34.000Z | #pragma once
#include <fea/config.hpp>
#include <fea/rendering/opengl.hpp>
#include <fea/rendering/uniform.hpp>
#include <fea/rendering/vertexattribute.hpp>
#include <vector>
namespace fea
{
enum BlendMode { NONE = 0, ALPHA, ADD, MULTIPLY, MULTIPLY2X };
struct FEA_API RenderEntity
{
std::vector<Uniform> mUniforms;
std::vector<VertexAttribute> mVertexAttributes;
BlendMode mBlendMode;
GLenum mDrawMode;
uint32_t mElementAmount;
};
/** @addtogroup Render2D
*@{
* @enum BlendMode
* @class RenderEntity
*@}
***
* @enum BlendMode
* @brief Mode the renderer uses for blending colors.
***
* @class RenderEntity
* @brief Contains the data needed for rendering a drawable.
***
* @var RenderEntity::mUniforms
* @brief List of uniforms to use in the rendering process.
***
* @var RenderEntity::mVertexAttributes
* @brief List of vertex attributes to use in the rendering process. The first one describes the vertex positions.
***
* @var RenderEntity::mBlendMode
* @brief Describes which blending mode the drawable should use.
***
* @var RenderEntity::mDrawMode
* @brief Describes which GL draw mode should be used to render the drawable.
***
* @var RenderEntity::mElementAmount
* @brief Describes the amount of render elements
***/
}
| 29.875 | 119 | 0.645049 | [
"render",
"vector"
] |
c96bb7d30fa6541293dcb565ec03aee21813969b | 369 | hpp | C++ | resources/factories/factories.hpp | hyper1423/SomeFPS | dcd353124d58e2696be7eaf44cddec17d6259629 | [
"BSD-3-Clause"
] | null | null | null | resources/factories/factories.hpp | hyper1423/SomeFPS | dcd353124d58e2696be7eaf44cddec17d6259629 | [
"BSD-3-Clause"
] | null | null | null | resources/factories/factories.hpp | hyper1423/SomeFPS | dcd353124d58e2696be7eaf44cddec17d6259629 | [
"BSD-3-Clause"
] | null | null | null | #ifndef FACTORIES_HPP
#define FACTORIES_HPP
#include "../resource_list.hpp"
#include <string>
#include <memory>
#include <cstddef>
namespace factories {
class TextLoader {
public:
resourceTypes::Resource* operator()(std::vector<std::byte> bytes);
};
class ModelLoader {
public:
resourceTypes::Resource* operator()(std::vector<std::byte> bytes);
};
}
#endif | 16.772727 | 70 | 0.723577 | [
"vector"
] |
c978d6f2d51611f114daa211071c8bc4b6cdda3d | 5,543 | cpp | C++ | X-Editor/src/Layers/EditorLayer.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 4 | 2020-02-17T07:08:26.000Z | 2020-08-07T21:35:12.000Z | X-Editor/src/Layers/EditorLayer.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 25 | 2020-03-08T05:35:25.000Z | 2020-07-08T01:59:52.000Z | X-Editor/src/Layers/EditorLayer.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 1 | 2020-10-15T12:39:29.000Z | 2020-10-15T12:39:29.000Z | // Editor Layer Source file
#include <chrono>
#include <ImGui/imgui.h>
#include <glm/gtc/type_ptr.hpp>
#include "Layers/EditorLayer.h"
#include "XEngine/Scene/Serializer.h"
#include <glm/gtc/matrix_transform.hpp>
#include "XEngine/Debug/Instrumentor.h"
namespace XEngine
{
EditorLayer::EditorLayer() : Layer("Editor Layer"), m_Camera(1920.0f / 1080.0f) {}
void EditorLayer::OnAttach()
{
XPROFILE_FUNCTION();
// Framebuffer
FramebufferSpecificaion fbSpec;
fbSpec.Width = 1280;
fbSpec.Height = 720;
m_Framebuffer = Framebuffer::Create(fbSpec);
m_ActiveScene = CreateRef<Scene>();
m_CameraEntity = m_ActiveScene->CreateEntity("Camera");
m_CameraEntity.AddComponent<CameraComponent>();
class Controller : public ScriptableEntity
{
public:
void OnCreate() {}
void OnDestroy() {}
void OnUpdate(Timestep timestep)
{
auto& transform = GetComponent<TransformComponent>().Position;
float speed = 5.0f;
if (Input::IsKeyPressed(Key::A))
transform.x -= speed * timestep;
if (Input::IsKeyPressed(Key::D))
transform.x += speed * timestep;
if (Input::IsKeyPressed(Key::W))
transform.y += speed * timestep;
if (Input::IsKeyPressed(Key::S))
transform.y -= speed * timestep;
}
};
m_CameraEntity.AddComponent<NativeScriptComponent>().Bind<Controller>();
m_Hierarchy.SetContext(m_ActiveScene);
//Serializer serializer(m_ActiveScene);
//serializer.Serialize("Assets/Scenes/Example.XEngine");
}
void EditorLayer::OnDetach()
{ XPROFILE_FUNCTION(); }
void EditorLayer::OnUpdate(Timestep timestep)
{
XPROFILE_FUNCTION();
// Framebuffer
if (FramebufferSpecificaion spec = m_Framebuffer->GetSpecificaion(); m_ViewportSize.x > 0.0f && m_ViewportSize.y > 0.0f && (spec.Width != m_ViewportSize.x || spec.Height != m_ViewportSize.y))
{
m_Framebuffer->Resize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
m_Camera.OnResize(m_ViewportSize.x, m_ViewportSize.y);
m_ActiveScene->OnViewportResize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
}
if(m_ViewportFocused)
m_Camera.OnUpdate(timestep);
// Profiler
Renderer2D::ResetStats();
// Background and clear
m_Framebuffer->Bind();
RenderCommand::SetClearColor({ .1f, .1f, .1f, 1 });
RenderCommand::Clear();
// Begin Scene and Draw
m_ActiveScene->OnUpdate(timestep);
m_Framebuffer->Unbind();
}
void EditorLayer::OnImGuiRender()
{
XPROFILE_FUNCTION();
// Dockspace
{
static bool dockspaceOpen = true;
static bool opt_fullscreen_persistant = true;
bool opt_fullscreen = opt_fullscreen_persistant;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
if (opt_fullscreen)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->GetWorkPos());
ImGui::SetNextWindowSize(viewport->GetWorkSize());
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
}
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace", &dockspaceOpen, window_flags);
ImGui::PopStyleVar();
if (opt_fullscreen)
ImGui::PopStyleVar(2);
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
float minWinSizeX = style.WindowMinSize.x;
style.WindowMinSize.x = 370.0f;
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("DockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
}
style.WindowMinSize.x = minWinSizeX;
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Exit")) Application::Get().Close();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
auto stats = Renderer2D::GetStats();
// Scene
{
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{ 0, 0 });
ImGui::Begin("Scene");
m_ViewportFocused = ImGui::IsWindowFocused();
m_ViewportHovered = ImGui::IsWindowHovered();
Application::Get().GetImGuiLayer()->SetBlockEvents(!m_ViewportFocused || !m_ViewportHovered);
ImVec2 viewportPanelSize = ImGui::GetContentRegionAvail();
m_ViewportSize = { viewportPanelSize.x, viewportPanelSize.y };
uint64_t textureID = m_Framebuffer->GetColorAttachmentRendererID();
ImGui::Image(reinterpret_cast<void*>(textureID), ImVec2{ m_ViewportSize.x, m_ViewportSize.y }, ImVec2{ 0, 1 }, ImVec2{ 1, 0 });
ImGui::End();
ImGui::PopStyleVar();
}
// Profiler
{
ImGui::Begin("Profiler");
ImGui::Text("Renderer2D Stats: ");
ImGui::Text("Draw Calls: %d", stats.DrawCalls);
ImGui::Text("Quads: %d", stats.QuadCount);
ImGui::Text("Vertices: %d", stats.GetTotalVertexCount());
ImGui::Text("Indices: %d", stats.GetTotalIndexCount());
ImGui::End();
}
// Hierarchy
{ m_Hierarchy.OnImGuiRender(); }
// Details
{ m_Details.OnImGuiRender(m_Hierarchy.m_SelectionContext); }
ImGui::End();
}
}
void EditorLayer::OnEvent(Event& e)
{ m_Camera.OnEvent(e); }
} | 36.467105 | 193 | 0.713152 | [
"transform"
] |
c97a35a05e57b528e7d50e3ee60abf368f114f4e | 3,652 | cpp | C++ | src/main.cpp | bergentroll/otus-cpp-14 | 7f9c429c94ca97f6213a52f9a34aed43bff406d4 | [
"CC0-1.0"
] | null | null | null | src/main.cpp | bergentroll/otus-cpp-14 | 7f9c429c94ca97f6213a52f9a34aed43bff406d4 | [
"CC0-1.0"
] | null | null | null | src/main.cpp | bergentroll/otus-cpp-14 | 7f9c429c94ca97f6213a52f9a34aed43bff406d4 | [
"CC0-1.0"
] | null | null | null | #include <boost/program_options.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
#include "file_marker.hpp"
#include "mapper.hpp"
#include "reducer.hpp"
#include "shuffler.hpp"
#include "thread_keeper.hpp"
using namespace std;
using namespace otus;
namespace po = boost::program_options;
using
boost::any,
boost::any_cast,
boost::lexical_cast,
boost::bad_lexical_cast;
BOOST_STRONG_TYPEDEF(int, ThreadsNum);
void validate(any& v, const vector<string>& values, ThreadsNum*, int) {
po::validators::check_first_occurrence(v);
const string &str { po::validators::get_single_string(values) };
try {
v = lexical_cast<ThreadsNum>(str);
} catch (bad_lexical_cast const &e) {
throw po::error("unexpected threads amount " + str);
}
auto port { any_cast<ThreadsNum>(v) };
if (port < 1) throw po::error("threads amount must be greater than 0");
}
int main(int argc, char **argv) {
string filename;
size_t mapThreadsNum;
size_t reduceThreadsNum;
try {
po::positional_options_description positional_description { };
positional_description.add("src", 1);
positional_description.add("mnum", 1);
positional_description.add("rnum", 1);
po::options_description description { "Hidden options" };
description.add_options()
("src", po::value<string>()->composing()->required(),
"input file")
("mnum", po::value<ThreadsNum>()->composing()->required(),
"numer of mapping threads")
("rnum", po::value<ThreadsNum>()->composing()->required(),
"number of reduce threads");
po::variables_map options;
po::store(
po::command_line_parser(argc, argv)
.positional(positional_description)
.options(description)
.run(),
options);
po::notify(options);
filename = options["src"].as<string>();
mapThreadsNum = options["mnum"].as<ThreadsNum>();
reduceThreadsNum = options["rnum"].as<ThreadsNum>();
} catch (po::error const &e) {
cerr << "Options error: " << e.what() << endl;
return EXIT_FAILURE;
}
FileMarker::OutputType marks { };
try {
FileMarker marker { filename };
marks = marker.mark(mapThreadsNum);
}
catch (FailedToReadFile const &e) {
std::cerr << "Error: " << e.what() << endl;
return EXIT_FAILURE;
}
ThreadKeeper<decltype(&Mapper::operator()), Mapper*> mapThreads { mapThreadsNum };
vector<Mapper> mappers { };
mappers.reserve(mapThreadsNum);
PosType begin { 0 };
for (auto const & endPair: marks) {
auto [end, size] { endPair };
try {
mappers.emplace_back(filename, begin, end, size);
}
catch (FailedToReadFile const &e) {
std::cerr << "Error: " << e.what() << endl;
return EXIT_FAILURE;
}
Mapper &mapper { mappers.back() };
mapThreads.run(&Mapper::operator(), &mapper);
begin = end + PosType(1);
}
mapThreads.join();
Shuffler::InputType containers { };
containers.reserve(mapThreadsNum);
for (auto &i: mappers) {
containers.push_back(&i.getResult());
}
Shuffler shuffler { containers, reduceThreadsNum };
shuffler();
auto const &shuffledData { shuffler.getResult() };
ThreadKeeper<decltype(&Reducer::operator()), Reducer*>
reduceThreads {reduceThreadsNum };
vector<Reducer> reducers { };
reducers.reserve(reduceThreadsNum);
for (auto const &container: shuffledData) {
reducers.emplace_back(container);
Reducer &reducer { reducers.back() };
reduceThreads.run(&Reducer::operator(), &reducer);
}
reduceThreads.join();
return EXIT_SUCCESS;
}
| 26.852941 | 84 | 0.665663 | [
"vector"
] |
c97b37e460d5873cb7a621a6794e1a6b720b480e | 14,469 | cpp | C++ | rnn++/app/ygpdb_etl.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | rnn++/app/ygpdb_etl.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | rnn++/app/ygpdb_etl.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | #include <vector>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <set>
#include <pqxx/pqxx>
#include <fmt/printf.h>
#include "similarity/query_engine.h"
#include "similarity/config.h"
#include "data_source/rss.h"
#include "data_source/ygp_db.h"
#include "data_source/ygp_etl.h"
#include "data_source/corenlp_helper.h"
#include "data_source/corenlp_utils.h"
#include "utils/hdf5.h"
#include "utils/profiling.h"
#include "utils/string.h"
#include "utils/type_param.h"
#include "utils/persistent_vector.h"
#include "utils/versioned_name.h"
#include "utils/optional.h"
#include "utils/math.h"
using namespace util::io;
using namespace wordrep;
using namespace engine;
using util::get_str;
void write_WordUIDs(std::string uid_dump, std::string filename, std::string voca_name, std::string uids_name){
H5file file{H5name{filename}, hdf5::FileMode::rw_exist};
auto raw = file.getRawData<char>(H5name{voca_name});
auto words = util::string::unpack_word_views(raw);
WordUIDindex wordUIDs{uid_dump};
std::vector<WordUID::val_t> uids;
for(auto word : words) uids.push_back(wordUIDs[word].val);
file.writeRawData(H5name{uids_name}, uids);
}
int list_columns(){
try
{
pqxx::connection C{"dbname=C291145_gbi_test host=bill.uphere.he"};
std::cout << "Connected to " << C.dbname() << std::endl;
pqxx::work W(C);
pqxx::result R = W.exec("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';");
std::cout << "Found " << R.size() << "Tables:" << std::endl;
for (auto row: R) {
for(auto elm : row) fmt::print("{} ", elm);
fmt::print("\n");
auto table = row[0];
auto query=fmt::format("select column_name from information_schema.columns where table_name='{}';", table);
pqxx::result R = W.exec(query);
for (auto column: R) fmt::print("{} ", column[0]);
}
W.commit();
std::cout << "ok." << std::endl;
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
namespace test {
void unicode_conversion(){
auto row_str = u8"This is 테스트 of unicode-UTF8 conversion.";
auto substr = util::string::substring_unicode_offset(row_str, 8, 11);
assert(substr==u8"테스트");
assert(substr!=u8"테스트 ");
assert(substr!=u8" 테스트");
fmt::print("{}\n", substr);
}
void word_importance(util::json_t const &config){
engine::SubmoduleFactory factory{{config}};
WordUIDindex wordUIDs = factory.word_uid_index();
POSUIDindex posUIDs = factory.pos_uid_index();
ArcLabelUIDindex arclabelUIDs = factory.arclabel_uid_index();
WordImportance word_importance = factory.word_importance();
auto ask = util::load_json("../rnn++/tests/data/query.unittest.inf_cutoff.corenlp");
DepParsedTokens query_tokens{};
query_tokens.append_corenlp_output(ask);
query_tokens.build_sent_uid(SentUID{SentUID::val_t{0x80000000}});
auto sents = query_tokens.IndexSentences();
for(auto sent : sents){
for(auto idx :sent){
auto wuid = sent.dict->word_uid(idx);
auto word = wordUIDs[wuid];
auto cutoff = word_importance.score(wuid);
assert(cutoff == 0.0);
}
}
}
using util::PersistentVector;
using util::TypedPersistentVector;
void persistent_vector_float(){
std::vector<float> vals = {1.1, 1.2, 1.3, 1.4, 1.5, 1.6};
PersistentVector<float,float> vec{vals, "reals"};
{
H5file h5store{H5name{"tmp.1849ya98fy2qhrqr6y198r1yr.h5"}, hdf5::FileMode::replace};
vec.write(h5store);
}
{
H5file h5store{H5name{"tmp.1849ya98fy2qhrqr6y198r1yr.h5"}, hdf5::FileMode::read_exist};
PersistentVector<float,float> vec2{h5store, "reals"};
for(auto x : util::zip(vec, vec2)) assert(x.first ==x.second);
}
}
void persistent_vector_WordUID(){
std::vector<WordUID::val_t> vals = {932,4,1,3,10};
TypedPersistentVector<WordUID> vec{vals, "wuid"};
{
H5file h5store{H5name{"tmp.1849ya98fy2qhrqr6y198r1yr.h5"}, hdf5::FileMode::replace};
vec.write(h5store);
}
{
H5file h5store{H5name{"tmp.1849ya98fy2qhrqr6y198r1yr.h5"}, hdf5::FileMode::read_exist};
TypedPersistentVector<WordUID> vec2{h5store, "wuid"};
for(auto x : util::zip(vec, vec2)) assert(x.first ==x.second);
}
//test copy
auto vec3 = vec;
for(auto x : util::zip(vec, vec3)) assert(x.first ==x.second);
vec3.front() = WordUID{1};
assert(vec3.front()!=vec.front());
}
void filesystem(util::json_t const &config){
auto data_path = util::get_str(config, "dep_parsed_store");
{
std::vector <std::string> files = {"foo.h5.1.0", "foo.h5.1.1", "foo.h5.1.2", "foo.h5.1.10", "foo.h5.1.3"};
auto ver = util::get_latest_version(files);
assert(ver.minor == 10);
assert(ver.major == 1);
assert(ver.name == "foo.h5");
}
{
std::vector<std::string> files = {"/bar/foo.h5.1.0", "/bar/foo.h5.2.1"};
auto ver = util::get_latest_version(files);
assert(ver.minor == 1);
assert(ver.major == 2);
assert(ver.name == "/bar/foo.h5");
assert(ver.fullname == "/bar/foo.h5.2.1");
}
std::cerr<< util::get_latest_version(data_path).fullname << std::endl;
}
void test_all(int argc, char** argv){
assert(argc > 1);
auto config = util::load_json(argv[1]);
word_importance(config);
unicode_conversion();
persistent_vector_float();
persistent_vector_WordUID();
filesystem(config);
}
}//namespace test
namespace data {
namespace ygp {
namespace test {
void ygpdb_indexing(util::json_t const &config){
using util::string::split;
auto path = "corenlp/autchklist2.guidenote.autchkid.12668";
RowDumpFilePath row{path};
assert(row.table =="autchklist2");
assert(row.column =="guidenote");
assert(row.index_col=="autchkid");
assert(row.index == 12668);
assert(row.full_column_name() == "autchklist2.guidenote.autchkid");
auto cols_to_exports = util::get_str(config,"column_uids_dump");
YGPdb db{cols_to_exports};
assert(db.col_uid("regulation.regtitle.regid")==ColumnUID{3});
assert(db.col_uid("reach_reports.content.report_id")==ColumnUID{0});
assert(db.is_in("reach_reports.content.report_id"));
assert(!db.is_in("dsafasfafsafa.content.asfasdf"));
}
void chunks() {
}
void country_annotator(util::json_t const &config) {
Factory factory{{config}};
CountryCodeAnnotator country_tagger = factory.country_code_annotator();
{
auto tags = country_tagger.tag("Seoul is a capital city of South Korea.\n");
assert(!util::isin(tags, "Japan"));
assert(util::isin(tags, "South Korea"));
}
{
//Test a special logic that treats "Korea" as "South Korea"
auto tags = country_tagger.tag("Seoul is a capital city of Korea.\n");
assert(!util::isin(tags, "Japan"));
assert(util::isin(tags, "South Korea"));
}
{
//"China" should also includes "Hong Kong"
auto tags = country_tagger.tag("China is in Asia.\n");
assert(!util::isin(tags, "Japan"));
assert(util::isin(tags, "China"));
assert(util::isin(tags, "Hong Kong"));
}
}
void test_all(int argc, char** argv) {
assert(argc > 1);
auto config = util::load_json(argv[1]);
ygpdb_indexing(config);
country_annotator(config);
}
}//namespace data::ygp::test
}//namespace data::ygp
}//namespace data
namespace data {
namespace corenlp {
namespace test {
struct Word{
Word(){};
Word(std::string substr) {
auto dep_word_end = substr.find_last_of("-");
word = substr.substr(0, dep_word_end);
idx = std::stoi(substr.substr(dep_word_end+1))-1;
}
std::string word;
int64_t idx;
};
struct Offset{
int64_t beg;
int64_t end;
};
struct WordToken{
WordToken(std::string line, int64_t idx){
auto elms = util::string::split(line.substr(1, line.size()-2), " ");
auto get = [](auto elm){return elm.substr(elm.find("=")+1);};
self.word = get(elms[0]);
self.idx = idx;
offset.beg = std::stoi(get(elms[1]));
offset.end = std::stoi(get(elms[2]));
pos = get(elms[3]);
}
std::string pos;
Word self;
Offset offset;
};
struct DepToken{
DepToken(std::string line){
auto label_end = line.find("(");
auto dep_end = line.find(", ");
auto gov_end = line.find(")");
arclabel = line.substr(0, label_end);
dependent = Word{line.substr(1+label_end, dep_end - (1+label_end))};
governor = Word{line.substr(2+dep_end, gov_end- (2+dep_end))};
}
std::string arclabel;
Word dependent;
Word governor;
};
bool isSentBeg(std::string const &sentence){
std::string tag = "Sentence #";
return tag == sentence.substr(0,tag.size());
}
bool isSentEnd(std::string const &sentence){
std::string tag = "";
return tag == sentence;
}
struct DepChunk{
using lines_t = std::vector<std::string>::const_iterator;
static std::optional<DepChunk> get(lines_t beg, lines_t end){
DepChunk chunk{};
auto it=beg;
for(;!isSentBeg(*it);++it) if(it==end) return {};
assert(isSentBeg(*it));
chunk.beg=it;
for(;!isSentEnd(*it);++it) if(it==end) return {};
assert(isSentEnd(*it));
chunk.end=it;
return chunk;
}
lines_t beg;
lines_t end;
};
struct DepChunkParser{
DepChunkParser(std::string filename)
: lines{util::string::readlines(filename)}
{}
template<typename OP>
void iter(OP const &op) const {
auto beg = lines.cbegin();
auto end = lines.cend();
while(auto maybe_chunk = DepChunk::get(beg, end)){
auto chunk = maybe_chunk.value();
op(chunk);
beg = chunk.end;
}
}
std::vector<std::string> const lines;
};
void parse_batch_output_line(){
{
assert(isSentBeg("Sentence #1 (9 tokens):"));
assert(!isSentBeg(""));
assert(!isSentEnd("Sentence #1 (9 tokens):"));
assert(isSentEnd(""));
}
{
std::string line = "[Text=Dave CharacterOffsetBegin=0 CharacterOffsetEnd=4 PartOfSpeech=NNP]";
WordToken test{line,0};
assert(test.pos=="NNP");
assert(test.self.word=="Dave");
assert(test.self.idx==0);
assert(test.offset.beg==0);
assert(test.offset.end==4);
}
{
std::string line = "[Text== CharacterOffsetBegin=0 CharacterOffsetEnd=4 PartOfSpeech=NNP]";
WordToken test{line,0};
assert(test.pos=="NNP");
assert(test.self.word=="=");
assert(test.self.idx==0);
assert(test.offset.beg==0);
assert(test.offset.end==4);
}
{
std::string line = "appos(Aneckstein-2, Research-5)";
DepToken test{line};
assert(test.arclabel == "appos");
assert(test.dependent.word == "Aneckstein");
assert(test.dependent.idx == 1);
assert(test.governor.word == "Research");
assert(test.governor.idx == 4);
}
{
std::string line = u8"dobj(A-B-2, ROOT-0)";
DepToken test{line};
assert(test.arclabel == "dobj");
assert(test.dependent.word == "A-B");
assert(test.dependent.idx == 1);
assert(test.governor.word == "ROOT");
assert(test.governor.idx == -1);
}
{
std::string line = u8"punct(가나다-2, ,-6)";
DepToken test{line};
assert(test.arclabel == "punct");
assert(test.dependent.word == "가나다");
assert(test.dependent.idx == 1);
assert(test.governor.word == ",");
assert(test.governor.idx == 5);
}
std::string line = "appos(Aneckstein-2, Research-5)";
gsl::cstring_span<> aa = gsl::ensure_z(line.data());
auto it_label_end = std::find(aa.cbegin(), aa.cend(), '(');
fmt::print(std::cerr, "{} \n",gsl::to_string(aa.subspan(0, it_label_end-aa.cbegin())));
}
void parse_batch_output(){
DepChunkParser parse{"../rnn++/tests/data/batch.corenlp"};
parse.iter([](auto const &chunk){
for(auto it=chunk.beg; it!=chunk.end; ++it) fmt::print("{}\n", *it);
});
}
void test_all(int argc, char** argv){
assert(argc > 1);
auto config = util::load_json(argv[1]);
parse_batch_output_line();
parse_batch_output();
}
}//namespace data::corenlp::test
}//namespace data::corenlp
}//namespace data
int process_ygp_dump(int argc, char** argv){
assert(argc>3);
auto config = util::load_json(argv[1]);
util::Timer timer;
auto json_dump_path = argv[2];
auto dataset_prefix = argv[3];
engine::SubmoduleFactory factory{{config}};
auto voca = factory.voca_info();
timer.here_then_reset("Load data.");
data::CoreNLPoutputParser dump_parser;
auto json_dumps = util::string::readlines(json_dump_path);
timer.here_then_reset(fmt::format("Begin to process {} JSON dump files. ",json_dumps.size()));
data::parallel_load_jsons(json_dumps, dump_parser);
timer.here_then_reset(fmt::format("Parsed {} files. ",dump_parser.chunks.size()));
auto tokens = dump_parser.get();
auto non_null_idxs = dump_parser.get_nonnull_idx();
timer.here_then_reset("Parsing is finished. ");
tokens.build_voca_index(voca.indexmap);
timer.here_then_reset("Built voca index.");
tokens.to_file({dataset_prefix});
timer.here_then_reset("Write to files.");
std::vector<std::string> non_null_dumps;
for(auto i : non_null_idxs) non_null_dumps.push_back(json_dumps[i]);
data::ygp::write_column_indexes(dataset_prefix,
util::get_str(config,"column_uids_dump"),
non_null_dumps);
timer.here_then_reset("Write indexes.");
return 0;
}
void test_common(int argc, char** argv){
assert(argc > 1);
auto config = util::load_json(argv[1]);
data::corenlp::test::parse_batch_output_line();
data::corenlp::test::parse_batch_output();
}
int main(int argc, char** argv){
assert(argc>1);
auto config = util::load_json(argv[1]);
// data::ygp::test::test_all(argc, argv);
// test::test_all(argc,argv);
// data::corenlp::test::test_all(argc,argv);
// return 0;
process_ygp_dump(argc,argv);
return 0;
}
| 31.18319 | 119 | 0.621467 | [
"vector"
] |
c97ceeb91fc8eb2c3d7e9713de898685156c3b71 | 11,100 | cc | C++ | FGUI/controls/listbox.cc | zanzo420/fgui | cb6c657ea01b8ea0c18a6ac29aa46e7cc9d1b53e | [
"MIT"
] | 1 | 2019-10-05T20:25:54.000Z | 2019-10-05T20:25:54.000Z | FGUI/controls/listbox.cc | Qazwar/fgui | cb6c657ea01b8ea0c18a6ac29aa46e7cc9d1b53e | [
"MIT"
] | null | null | null | FGUI/controls/listbox.cc | Qazwar/fgui | cb6c657ea01b8ea0c18a6ac29aa46e7cc9d1b53e | [
"MIT"
] | null | null | null | /* *
* fgui - an extensive oop gui framework *
* */
// includes
#include "listbox.hh"
#include "../handler/handler.hh"
#include "../dependencies/color.hh"
#include "../dependencies/aliases.hh"
fgui::listbox::listbox() {
fgui::listbox::m_index = 0;
fgui::listbox::m_title = "listbox";
fgui::listbox::m_slider_top = 0;
fgui::listbox::m_item_height = 20;
fgui::listbox::m_font = fgui::element::m_font;
fgui::listbox::m_family = fgui::element_family::LISTBOX_FAMILY;
fgui::element::m_flags = fgui::element_flag::DRAWABLE | fgui::element_flag::CLICKABLE | fgui::element_flag::SAVABLE;
}
//---------------------------------------------------------
void fgui::listbox::draw() {
// get the current position of the window
fgui::point a = fgui::element::get_absolute_position();
// get the window style
auto style = handler::get_style();
// get the control area
fgui::rect area = { a.x, a.y, m_width, m_height };
// get the number of displayed items
unsigned int item_displayed = 0;
// calculate the quantity of entries that will be drawned on the listbox
int calculated_items = m_height / m_item_height;
// listbox body
fgui::render.outline(area.left, area.top, area.right, area.bottom, fgui::color(style.listbox.at(0)));
if (fgui::input.is_mouse_in_region(area) || m_dragging)
fgui::render.outline(area.left + 2, area.top + 2, (area.right - 14) - 4, area.bottom - 4, fgui::color(style.listbox.at(3)));
else
fgui::render.outline(area.left + 1, area.top + 1, area.right - 2, area.bottom - 2, fgui::color(style.listbox.at(1)));
fgui::render.rect(area.left + 3, area.top + 3, (area.right - 14) - 6, area.bottom - 6, fgui::color(style.listbox.at(2)));
// listbox label
fgui::render.text(area.left, area.top - 15, fgui::color(style.text.at(0)), fgui::listbox::get_font(), m_title);
if (m_items.empty())
return;
for (std::size_t i = m_slider_top; (i < m_items.size() && item_displayed < calculated_items); i++) {
// get the item region
fgui::rect item_area = { a.x, a.y + (m_item_height * item_displayed), (m_width - 15), m_item_height };
int item_text_width, item_text_height;
fgui::render.get_text_size(fgui::listbox::get_font(), m_items[i].first, item_text_width, item_text_height);
// if the user is hovering an item on the list
if (fgui::input.is_mouse_in_region(item_area) || m_index == i) {
fgui::render.rect(item_area.left + 2, item_area.top + 2, item_area.right - 4, item_area.bottom - 4, fgui::color(style.listbox.at(3)));
if (fgui::listbox::m_items[i].first.length() > 20)
fgui::render.text(item_area.left + 5, item_area.top + (item_area.bottom / 2) - (item_text_height / 2), fgui::color(style.text.at(0)), fgui::listbox::get_font(), m_items[i].first.replace(m_items[i].first.begin() + 20, m_items[i].first.end(), "..."));
else
fgui::render.text(item_area.left + 5, item_area.top + (item_area.bottom / 2) - (item_text_height / 2), fgui::color(style.text.at(0)), fgui::listbox::get_font(), m_items[i].first);
}
else if (!fgui::input.is_mouse_in_region(item_area)) {
if (fgui::listbox::m_items[i].first.length() > 20)
fgui::render.text(item_area.left + 5, item_area.top + (item_area.bottom / 2) - (item_text_height / 2), fgui::color(style.text.at(0)), fgui::listbox::get_font(), m_items[i].first.replace(m_items[i].first.begin() + 20, m_items[i].first.end(), "..."));
else
fgui::render.text(item_area.left + 5, item_area.top + (item_area.bottom / 2) - (item_text_height / 2), fgui::color(style.text.at(0)), fgui::listbox::get_font(), m_items[i].first);
}
item_displayed++;
}
// calculate the slider position
float calculated_position = static_cast<float>(m_slider_top) / static_cast<float>(m_items.size());
if (calculated_position >= 1.f)
calculated_position = 1.f;
calculated_position *= m_height;
// calculate the slider size
float calculated_size = static_cast<float>(calculated_items) / static_cast<float>(m_items.size());
if (calculated_size > 1.f)
calculated_size = 1.f;
calculated_size *= m_height;
// scrollbar area
fgui::rect scrollbar_area = { (area.left + 2) + (area.right - 15), area.top + 2, 15 - 4, area.bottom - 4 };
// scrollbar body
fgui::render.outline(scrollbar_area.left + 1, scrollbar_area.top + 1, scrollbar_area.right - 2, scrollbar_area.bottom - 2, fgui::color(style.listbox.at(0)));
fgui::render.rect(scrollbar_area.left, scrollbar_area.top, scrollbar_area.right, scrollbar_area.bottom, fgui::color(style.listbox.at(1)));
fgui::render.outline(scrollbar_area.left + 1, (scrollbar_area.top + calculated_position) + 1, scrollbar_area.right - 2, (calculated_size - 2) - 4, fgui::color(style.listbox.at(3)));
if (m_items.size() > 100)
fgui::render.colored_gradient(scrollbar_area.left + 2, (scrollbar_area.top + calculated_position) + 2, scrollbar_area.right - 4, (calculated_size - 4) - 4, fgui::color(style.listbox.at(1)), fgui::color(style.listbox.at(2)), fgui::gradient_type::VERTICAL);
else
fgui::render.colored_gradient(scrollbar_area.left + 2, (scrollbar_area.top + calculated_position) + 2, scrollbar_area.right - 4, (calculated_size - 4) - 4, fgui::color(style.listbox.at(1)), fgui::color(style.listbox.at(2)), fgui::gradient_type::VERTICAL);
// dots
if (m_dragging) {
fgui::render.rect(scrollbar_area.left + 5, (scrollbar_area.top + calculated_position) + 2 + (calculated_size / 2) - 1, 1, 1, fgui::color(style.listbox.at(3)));
fgui::render.rect(scrollbar_area.left + 5, (scrollbar_area.top + calculated_position) + 2 + (calculated_size / 2) - 3, 1, 1, fgui::color(style.listbox.at(3)));
fgui::render.rect(scrollbar_area.left + 5, (scrollbar_area.top + calculated_position) + 2 + (calculated_size / 2) - 5, 1, 1, fgui::color(style.listbox.at(3)));
}
else if (!m_dragging) {
fgui::render.rect(scrollbar_area.left + 5, (scrollbar_area.top + calculated_position) + 2 + (calculated_size / 2) - 1, 1, 1, fgui::color(style.text.at(0)));
fgui::render.rect(scrollbar_area.left + 5, (scrollbar_area.top + calculated_position) + 2 + (calculated_size / 2) - 3, 1, 1, fgui::color(style.text.at(0)));
fgui::render.rect(scrollbar_area.left + 5, (scrollbar_area.top + calculated_position) + 2 + (calculated_size / 2) - 5, 1, 1, fgui::color(style.text.at(0)));
}
}
//---------------------------------------------------------
void fgui::listbox::add_item(std::string item, int value) {
m_items.emplace_back(item, value);
}
//---------------------------------------------------------
std::string fgui::listbox::get_item() {
return m_items[m_index].first;
}
//---------------------------------------------------------
int fgui::listbox::get_index() {
return m_index;
}
//---------------------------------------------------------
int fgui::listbox::get_value() {
return m_items[m_index].second;
}
//---------------------------------------------------------
void fgui::listbox::set_index(int index) {
m_index = index;
}
//---------------------------------------------------------
void fgui::listbox::handle_input() {
// get the current position of the window
fgui::point a = fgui::element::get_absolute_position();
if (m_items.size() > 0) {
// get the control area
fgui::rect area = { a.x, a.y, m_width , m_height };
// scrollbar area
fgui::rect scrollbar_area = { (area.left + 2) + (area.right - 15), area.top + 2, 15 - 4, area.bottom - 4 };
if (fgui::input.is_mouse_in_region(scrollbar_area)) {
if (fgui::input.get_key_state(MOUSE_LEFT))
m_dragging = true;
}
// calculate the amount of items to be drawned
int calculated_items = m_height / m_item_height;
// get the number of displayed items
unsigned int item_displayed = 0;
for (std::size_t i = m_slider_top; (i < m_items.size() && item_displayed < calculated_items); i++) {
// get the item area of the list box
fgui::rect item_region = { a.x, a.y + (item_displayed * m_item_height), m_width - 15, m_item_height };
if (fgui::input.is_mouse_in_region(item_region)) {
// select a item
m_index = i;
}
item_displayed++;
}
}
}
//---------------------------------------------------------
void fgui::listbox::update() {
// get the current position of the window
fgui::point a = fgui::element::get_absolute_position();
// calculate the amount of items to be drawned
int calculated_items = m_height / m_item_height;
if (m_dragging) {
if (fgui::input.get_key_state(MOUSE_LEFT)) {
// get the cursor position
fgui::point cursor;
fgui::input.get_mouse_position(cursor.x, cursor.y);
// move the slider vertically
cursor.y -= a.y + 2;
// ratio of how many visible to how many are hidden
float calculated_size = static_cast<float>(calculated_items) / static_cast<float>(m_items.size());
calculated_size *= m_height;
// height delta
float height_delta = (cursor.y + calculated_size) - m_height;
if (height_delta >= 0)
cursor.y -= height_delta;
float new_position_ratio = static_cast<float>(cursor.y) / static_cast<float>(m_height);
m_slider_top = new_position_ratio * m_items.size();
if (m_slider_top <= 0)
m_slider_top = 0;
}
else
m_dragging = false;
}
}
//---------------------------------------------------------
void fgui::listbox::tooltip() {
// get the current position of the window
fgui::point a = fgui::element::get_absolute_position();
// get the control area
fgui::rect area = { a.x, a.y, m_width, m_height };
if (m_tooltip.length() > 0) {
// tooltip text size
int tooltip_text_width, tooltip_text_height;
fgui::render.get_text_size(fgui::element::get_font(), m_tooltip, tooltip_text_width, tooltip_text_height);
if (fgui::input.is_mouse_in_region(area)) {
fgui::point cursor = { 0, 0 };
fgui::input.get_mouse_position(cursor.x, cursor.y);
fgui::render.rect(cursor.x + 10, cursor.y + 20, tooltip_text_width + 10, 20, fgui::color(225, 100, 85));
fgui::render.text(cursor.x + 10 + ((tooltip_text_width + 10) / 2) - (tooltip_text_width / 2), cursor.y + 20 + (20 / 2) - (tooltip_text_height / 2), fgui::color(255, 255, 255), fgui::element::get_font(), m_tooltip);
}
}
}
//---------------------------------------------------------
void fgui::listbox::save(const std::string& file_name, nlohmann::json& json_module) {
json_module[m_identificator] = m_index;
}
//---------------------------------------------------------
void fgui::listbox::load(const std::string& file_name) {
nlohmann::json json_module;
// open the file
std::ifstream file_to_load(file_name, std::ifstream::binary);
if (!file_to_load.good())
return;
// read config file
json_module = nlohmann::json::parse(file_to_load);
// change the element state to match the one stored on file
m_index = json_module[m_identificator];
} | 37.883959 | 258 | 0.627117 | [
"render"
] |
c97dde9e4c62cb17153c4701ac231a86cd5bc95c | 63 | hh | C++ | RAVL2/MSVC/include/Ravl/Crack.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/Crack.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/Crack.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null |
#include "../.././Math/Geometry/Euclidean/Boundary/Crack.hh"
| 15.75 | 60 | 0.68254 | [
"geometry"
] |
c97e9c6f28288e9e6d1d8815286360ed4f9fbf63 | 34,902 | cpp | C++ | tests/narrowphasetest.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | 6 | 2015-12-08T05:38:03.000Z | 2021-04-09T13:45:59.000Z | tests/narrowphasetest.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | tests/narrowphasetest.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (C) 2007 by the members of PG 510, University of Dortmund: *
* d-collide-users@lists.sourceforge.net *
* Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, *
* Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, *
* Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz *
* *
* 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 PG510 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 directives
#include "narrowphasetest.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <math.h>
#include <list>
#include "world.h"
#include "worldcollisions.h"
#include "broadphase/broadphasecollisions.h"
#include "shapes/shapes.h"
#include "narrowphase/narrowphase.h"
#include "narrowphase/narrowphasestrategy.h"
#include "math/matrix.h"
#include "math/vector.h"
#include "real.h"
#include "proxy.h"
#include "dcollide-defines.h"
#include "narrowphase/triangleintersector.h"
#include <iomanip>
//-------------------------------------
//-------using directives--------------
using namespace std;
using namespace dcollide;
/*
add the class test to a global list of tests
if this line is forgotten - nothing will happen
the test methods will never get called
IMPORTANT:
This registration MUST happen in the .cpp file
If it is done in the header, which is also possible,
the registration gets run every time the header is
included. The Unit Test may be registered several times.
*/
CPPUNIT_TEST_SUITE_REGISTRATION (NarrowPhaseTest);
const float epsilon = 0.0001f;
namespace dcollide {
/*!
* \brief resource allocation for unit test
*/
void NarrowPhaseTest::setUp(void) {
//Constructor for Unit Tests
//not needed here
//use this to allocate resources as memory, files etc.
}
/*!
* \brief resource deallocation for unit test
*/
void NarrowPhaseTest::tearDown(void) {
//Destructor for Unit Tests
//not needed here
//use this to free the resources allocated in setUp()
}
void NarrowPhaseTest::sphereSphereTest() {
World world(Vector3(1000, 1000, 1000));
world.setNarrowPhaseStrategySphereSphere(NP_STRATEGY_SLOWEST_EXTENSIVE);
Proxy* sphere1 = world.createProxy(new Sphere(1));
Proxy* sphere2 = world.createProxy(new Sphere(1));
world.addProxy(sphere1);
world.addProxy(sphere2);
world.prepareSimulation();
//Convenience matrices for fast resets
Matrix origin;
Matrix o500;
o500.translate(5,0,0);
/*
BoundingVolumeCollision mpc;
mpc.node1 = sphere1->getBvHierarchyNode();
mpc.node2 = sphere2->getBvHierarchyNode();
NarrowPhaseShapeStrategies strategies;
strategies.mStrategySphereSphere = NP_STRATEGY_SLOWEST_EXTENSIVE;
NarrowPhase np(strategies);
*/
//--- Test 1: no collision , 2 fixed spheres ---//
//Two spheres of radius 1, sphere 1 at (1.9, 1.9, 1.9) so that the BVs
//overlap
// sphere2 is placed fixed at the origin
sphere1->translate((real)(1.9), (real)(1.9), (real)(1.9));
std::list<CollisionInfo> result =
world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL(true, result.empty());
//examine result
//--- Test 2: basic collision---//
//Two spheres of radius 1, sphere 1 was at (5,0,0) moving to (1.5, 0, 0)
// sphere2 is placed fixed at the origin
sphere1->setTransformation(o500);
world.startNextStep();
sphere1->translate(Vector3(-3.5f, 0, 0));
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t) 1, result.size());
//examine result
CollisionInfo coll = *result.begin();
CPPUNIT_ASSERT_EQUAL(Vector3(1, 0, 0), coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(0.5f, coll.penetrationDepth);
CPPUNIT_ASSERT_EQUAL(Vector3(1, 0, 0), coll.normal);
//--- Test 3: no collision (stops before coll)---//
//Two spheres of radius 1, sphere 1 at (5,0,0) moving to (4, 0, 0)
// sphere2 is placed fixed at the origin
//first reset the sphere1
sphere1->setTransformation(o500);
world.startNextStep();
sphere1->translate(-1, 0, 0);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(result.empty());
//--- Test 4: no collision (parallel movement)---//
//reset to a coordinates with colliding BVs, but no sphere-collision
sphere2->setTransformation(origin);
sphere1->setTransformation(origin);
sphere1->translate(2, 2, 0);
world.startNextStep();
//move the spheres up in y-direction
sphere1->translate(0, 5, 0);
sphere2->translate(0, 5, 0);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(result.empty());
//--- Test 5: one collision, touching at t=1---//
//sphere1 starts at 5,0,0 and moves to 3,0,0
//sphere2 moves to 1,0,0 so that the collision is at 2,0,0
//reset
sphere2->setTransformation(origin);
sphere1->setTransformation(o500);
world.startNextStep();
sphere1->translate(-2, 0, 0);
sphere2->translate(1, 0, 0);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
//examine result
coll = *result.begin();
CPPUNIT_ASSERT_EQUAL(Vector3(2, 0, 0), coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(1, 0, 0), coll.normal);
CPPUNIT_ASSERT_EQUAL(0.0f, coll.penetrationDepth);
//--- Test 7: all axis test---//
//sphere1 going from 2,2,2 to 0,0,0
//sphere2 going from 0,0,0 to 2,2,2
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
sphere1->translate(2, 2, 2);
world.startNextStep();
sphere1->translate(-2, -2, -2);
sphere2->translate(2, 2, 2);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
//this is a collision we cannot find without doing backtracking
CPPUNIT_ASSERT(result.size()==1);
//examine result
coll = *result.begin();
Vector3 expNormal(1, 1, 1);
expNormal.normalize();
real expDepth = Vector3(1, 1, 1).length()+1;
CPPUNIT_ASSERT_EQUAL(Vector3(1, 1, 1), coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(expNormal, coll.normal);
CPPUNIT_ASSERT_DOUBLES_EQUAL(expDepth, coll.penetrationDepth, epsilon);
//------- Test 8: Collision in the previous state, no collision now---//
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
world.startNextStep();
sphere1->translate(2, 2, 2);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(result.empty());
//--- Test 9: Collision in the previous state and the current state---//
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
world.startNextStep();
sphere1->translate(0.5, 0, 0);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t) 1, result.size());
//examine result
coll = *result.begin();
//GJ: Note that the simple algorithm is used here
CPPUNIT_ASSERT_EQUAL(Vector3(0.25, 0, 0), coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(1, 0, 0), coll.normal);
CPPUNIT_ASSERT_EQUAL(1.5f, coll.penetrationDepth);
//---------Test 10:: touching while passing by---------------//
//sphere1 is fixed, sphere2 moves from (2, -2, 0) to (2, 2, 0)
//to touch sphere1 at (1, 0, 0)
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
sphere2->translate(Vector3(2, -2, 0));
world.startNextStep();
//std::cout << "Touching while passing by test" <<std::endl;
sphere2->translate(Vector3(0, 2, 0));
result = world.calculateAllCollisions(World::COLLISIONFLAG_NONE).getNarrowPhaseCollisions();
//another case whithout collision at current state
CPPUNIT_ASSERT_EQUAL((size_t) 1, result.size());
//examine result
coll = *result.begin();
CPPUNIT_ASSERT_EQUAL(Vector3(1,0,0), coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(1,0,0), coll.normal);
CPPUNIT_ASSERT_EQUAL(0.0f, coll.penetrationDepth);
//---------Test 11:: collision while passing by---------------//
//sphere1 is fixed, sphere2 moves from (1, -5, 0) to (1, 2, 0)
//to get a full collision with sphere 1 on the way
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
sphere2->translate(Vector3(1, -5, 0));
world.startNextStep();
sphere2->translate(Vector3(0, 7, 0));
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
//another case whithout collision at current state
CPPUNIT_ASSERT_EQUAL((size_t) 1, result.size());
//examine result
coll = *result.begin();
Vector3 expectedCollPoint (0.5, (real)(- sqrt(3.0)/2.0), 0);
CPPUNIT_ASSERT_EQUAL(expectedCollPoint, coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(expectedCollPoint, coll.normal);
CPPUNIT_ASSERT(coll.penetrationDepth>2.5);
//---------Test 12a:: starting at a collision and not moving--------//
//This is kind of difficult. We cannot be sure where the collision was
//GJ: i propose following interpretation:
//just return the center of the overlap region as collision point
sphere1->setTransformation(origin);
sphere1->translate(Vector3(1, 0, 0));
sphere2->setTransformation(origin);
world.startNextStep();
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(result.size()==1);
//examine result
coll = *result.begin();
CPPUNIT_ASSERT_EQUAL(Vector3(0.5, 0, 0), coll.collisionPoint);
//we don't care about the direction of the normal
CPPUNIT_ASSERT( coll.normal == Vector3(1, 0, 0) ||
coll.normal == Vector3(-1, 0, 0));
CPPUNIT_ASSERT_EQUAL(1.0f, coll.penetrationDepth);
//---------Test 12b:: starting at a collision moving parallel--------//
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
sphere2->translate(Vector3(1, 0, 0));
world.startNextStep();
sphere1->translate(Vector3(0, 1, 0));
sphere2->translate(Vector3(0, 1, 0));
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(result.size()==1);
//examine result
coll = *result.begin();
CPPUNIT_ASSERT_EQUAL(Vector3(0.5, 1, 0), coll.collisionPoint);
//we don't care about the direction of the normal
CPPUNIT_ASSERT( coll.normal == Vector3(1, 0, 0) ||
coll.normal == Vector3(-1, 0, 0));
CPPUNIT_ASSERT_EQUAL(1.0f, coll.penetrationDepth);
//---------Test 12c:: starting and staying at one point--------//
sphere1->setTransformation(origin);
sphere2->setTransformation(origin);
world.startNextStep();
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(result.size()==1);
//examine result
coll = *result.begin();
//collisionpoint should be centerpoint of both spheres
//collision normal is some random normalized vector
CPPUNIT_ASSERT_EQUAL(Vector3(0,0,0), coll.collisionPoint);
CPPUNIT_ASSERT_EQUAL(1.0f, coll.normal.length());
CPPUNIT_ASSERT_EQUAL(2.0f, coll.penetrationDepth);
}
void NarrowPhaseTest::sphereMeshTest() {
World world(Vector3(1000, 1000, 1000));
// The Mesh will have only one triangle,
// the sphere will have a radius of 2 and will be moved around
// to test area collisions, edge collisions and vertex collisions
std::stringstream ss; // <- error message
std::vector<Vertex*> vertices;
std::vector<Triangle*> triangles;
vertices.push_back(new Vertex(Vector3( 0.0, 0.0, 0.0)));
vertices.push_back(new Vertex(Vector3( 5.0, 0.0, 0.0)));
vertices.push_back(new Vertex(Vector3( 0.0, 5.0, 0.0)));
Triangle* t = new Triangle(vertices[0], vertices[1], vertices[2]);
triangles.push_back(t);
Mesh* myMesh = new Mesh(vertices, triangles);
Sphere* mySphere = new Sphere(2.0);
Proxy* meshProxy = world.createProxy(myMesh);
Proxy* sphereProxy = world.createProxy(mySphere);
world.addProxy(meshProxy);
world.addProxy(sphereProxy);
world.prepareSimulation();
//First: area collision from "above"
sphereProxy->setPosition(1.0, 1.0, 1.0);
std::list<CollisionInfo> result = world.calculateAllCollisions().getNarrowPhaseCollisions();
CollisionInfo collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(1.0, 1.0, 0.0), collision.collisionPoint);
CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, collision.penetrationDepth, epsilon);
CPPUNIT_ASSERT_EQUAL(Vector3(0.0, 0.0, 1.0), collision.normal);
//second test: area collision from "below"
sphereProxy->setPosition(2.0, 1.0, -1.5);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(2.0, 1.0, 0.0), collision.collisionPoint);
//the penetration normal always point "out"
//so the sphere gets pushed back outside the triangle
CPPUNIT_ASSERT_DOUBLES_EQUAL(3.5, collision.penetrationDepth, epsilon);
CPPUNIT_ASSERT_EQUAL(Vector3(0.0, 0.0, 1.0), collision.normal);
//third test: edge collisions
//with edge01
Vector3 spherePosition (2.5, -1.5, 0.5);
sphereProxy->setPosition(spherePosition);
result = world.calculateAllCollisions(World::COLLISIONFLAG_NONE).getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
collision = result.front();
CPPUNIT_ASSERT_EQUAL(Vector3(2.5, 0.0, 0.0), collision.collisionPoint);
Vector3 connection (0, -1.5, 0.5); //sphere to collision connection
CPPUNIT_ASSERT_DOUBLES_EQUAL(2 - connection.length(), collision.penetrationDepth, epsilon);
connection.normalize();
CPPUNIT_ASSERT_EQUAL(connection, collision.normal);
//with edge02 (slightly below)
sphereProxy->setPosition(Vector3(-1, 3, -0.5));
result = world.calculateAllCollisions(World::COLLISIONFLAG_NONE).getNarrowPhaseCollisions();
collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(0.0, 3.0, 0.0), collision.collisionPoint);
connection = Vector3(-1.0, 0.0, -0.5); //sphere to collision connection
CPPUNIT_ASSERT_DOUBLES_EQUAL(2 - connection.length(), collision.penetrationDepth, epsilon);
connection.normalize();
CPPUNIT_ASSERT_EQUAL(connection, collision.normal);
//with edge12 (same plane)
sphereProxy->setPosition(Vector3(3.0, 3.0, 0.0));
result = world.calculateAllCollisions(World::COLLISIONFLAG_NONE).getNarrowPhaseCollisions();
collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(2.5, 2.5, 0.0), collision.collisionPoint);
connection = Vector3(0.5, 0.5, 0.0); //sphere to collision connection
CPPUNIT_ASSERT_DOUBLES_EQUAL(2 - connection.length(), collision.penetrationDepth, epsilon);
connection.normalize();
CPPUNIT_ASSERT_EQUAL(connection, collision.normal);
//fourth test: collision with vertices
//with (0,0,0)
spherePosition.set(-1,-1, 1);
sphereProxy->setPosition(spherePosition);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(0.0, 0.0, 0.0), collision.collisionPoint);
connection.set(-1.0, -1.0, 1); //sphere to collision connection
CPPUNIT_ASSERT_DOUBLES_EQUAL(2 - connection.length(), collision.penetrationDepth, epsilon);
connection.normalize();
CPPUNIT_ASSERT_EQUAL(connection, collision.normal);
//with vertex 5,0,0
spherePosition.set(6,0, 1);
sphereProxy->setPosition(spherePosition);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(5.0, 0.0, 0.0), collision.collisionPoint);
connection.set(1.0, 0.0, 1.0); //collpoint to spherecenter connection
CPPUNIT_ASSERT_DOUBLES_EQUAL(2 - connection.length(), collision.penetrationDepth, epsilon);
connection.normalize();
CPPUNIT_ASSERT_EQUAL(connection, collision.normal);
//with vertex 0,5,0
spherePosition.set(1, 6, 1);
sphereProxy->setPosition(spherePosition);
result = world.calculateAllCollisions().getNarrowPhaseCollisions();
collision = result.front();
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(Vector3(0.0, 5.0, 0.0), collision.collisionPoint);
connection.set(1.0, 1.0, 1.0); //collpoint to spherecenter connection
CPPUNIT_ASSERT_DOUBLES_EQUAL(2 - connection.length(), collision.penetrationDepth, epsilon);
connection.normalize();
CPPUNIT_ASSERT_EQUAL(connection, collision.normal);
}
void NarrowPhaseTest::boxBoxTest() {
#define DUMP_VERTICES(box) { \
cout << #box << " = [" << endl; \
Box* shape = (Box*) box->getShape(); \
const Vector3* verts = shape->getVertices(box->getWorldTransformation()); \
for (int i=0; i<8; i++) { \
cout << " " << fixed << verts[i] << "," << endl; \
} \
cout << "]" << endl << endl; \
}
#define DUMP_RESULTS(results) { \
int i = 0; \
for (it = results.begin(); it != results.end(); ++it) { \
CollisionInfo info = *it; \
cout << "CP" << i << " = " << info.collisionPoint << ", depth = " \
<< info.penetrationDepth << endl; \
i++; \
} \
}
World world(Vector3(1000, 1000, 1000));
Proxy* box1;
Proxy* box2;
Proxy* box3;
const Matrix identity;
list<CollisionInfo> results;
list<CollisionInfo>::iterator it;
/* --- Test 1: no collision , 2 fixed boxes ---
*
* Two boxes, each one 1x1x1 each, first one at (5, 0, 0) the second
* one is placed fixed at the origin. No collision.
*/
box1 = world.createProxy(new Box(Vector3(1, 1, 1)));
box2 = world.createProxy(new Box(Vector3(1, 1, 1)));
world.addProxy(box1);
world.addProxy(box2);
world.prepareSimulation();
box1->translate(5, 0, 0);
results = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(results.empty());
/* --- Test 2: basic collision ---
*
* Two 1x1x1-boxes, first one, moving from (5, 0, 0) to (0.5, 0.5, 0.0)
* into the other one, which is fixed at the origin. Should give us 4
* collision points.
*/
world.startNextStep();
box1->setTransformation(identity);
box2->setTransformation(identity);
box1->translate(5, 0, 0);
results = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT(results.empty());
world.startNextStep();
// move to (0.5, 0.5, 0.0)
box1->translate(-4.5, 0.5, 0.0);
results = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t) 4, results.size());
// Collision points should be (0.5, 0.5, 0), (0.5, 1.5, 0),
// (0.5, 0.5, 1) and (0.5, 1.5, 1), with a penetration depth of 0.5.
{
int a = 0; // (0.5, 0.5, 0)
int b = 0; // (0.5, 1.5, 0)
int c = 0; // (0.5, 0.5, 1)
int d = 0; // (0.5, 1.5, 1)
for (it = results.begin(); it != results.end(); ++it) {
CollisionInfo info = *it;
CPPUNIT_ASSERT_DOUBLES_EQUAL(info.penetrationDepth, (real)0.5, 0.1e-5);
// epsilon is 0.001 by default (see Vector3 class)
if (info.collisionPoint.isEqual(Vector3(0.5, 0.5, 0))) {
a++;
}
if (info.collisionPoint.isEqual(Vector3(0.5, 1.5, 0))) {
b++;
}
if (info.collisionPoint.isEqual(Vector3(0.5, 0.5, 1))) {
c++;
}
if (info.collisionPoint.isEqual(Vector3(0.5, 1.5, 1))) {
d++;
}
}
// Assert each collision point is returned exactly once.
CPPUNIT_ASSERT_EQUAL(1, a);
CPPUNIT_ASSERT_EQUAL(1, b);
CPPUNIT_ASSERT_EQUAL(1, c);
CPPUNIT_ASSERT_EQUAL(1, d);
}
/* --- Test 3: a more complicated setup ---
*
* Starting with a collision, then box2 moves 0.5 upwards (y-axis),
* still colliding with box1.
*/
world.startNextStep();
box1->setTransformation(identity);
box2->setTransformation(identity);
box2->translate(1.4, 0.0, 0.5);
box2->rotate(45.0, 1, 0, 0);
box2->rotate(45.0, 0, 0, 1);
results = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t) 2, results.size());
// expected: (1.400000, 0.000000, 0.500000)
// and (0.692893, 0.500000, 1.000000)
{
int a = 0; // (1.400000, 0.000000, 0.500000)
int b = 0; // (0.692893, 0.500000, 1.000000)
for (it = results.begin(); it != results.end(); ++it) {
CollisionInfo info = *it;
CPPUNIT_ASSERT_DOUBLES_EQUAL(info.penetrationDepth, (real)0.177308, 0.1e-5);
if (info.collisionPoint.isEqual(Vector3(1.4, 0, 0.5))) {
a++;
}
if (info.collisionPoint.isEqual(Vector3(0.692893, 0.50, 1.0))) {
b++;
}
}
// Assert each collision point is returned exactly once.
CPPUNIT_ASSERT_EQUAL(1, a);
CPPUNIT_ASSERT_EQUAL(1, b);
}
world.startNextStep();
box2->translate(0.0, 0.0, -0.5);
results = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t) 2, results.size());
// expected: (0.692893, 0.853553, 0.646447)
// and (0.692893, 0.146447, 1.353553)
{
int a = 0; // (0.692893, 0.853553, 0.646447)
int b = 0; // (0.692893, 0.146447, 1.353553)
for (it = results.begin(); it != results.end(); ++it) {
CollisionInfo info = *it;
CPPUNIT_ASSERT_DOUBLES_EQUAL(info.penetrationDepth, (real)0.307107, 0.1e-5);
if (info.collisionPoint.isEqual(Vector3(0.692893, 0.853553, 0.646447))) {
a++;
}
if (info.collisionPoint.isEqual(Vector3(0.692893, 0.146447, 1.353553))) {
b++;
}
}
// Assert each collision point is returned exactly once.
CPPUNIT_ASSERT_EQUAL(1, a);
CPPUNIT_ASSERT_EQUAL(1, b);
}
/* --- Test 4: Box on box ---
*
* Put a 1x1x1 box on top of a 2x1x1-box, should yield four collision
* points in the 'y=1'-plane.
*/
world.startNextStep();
world.removeProxy(box2);
box3 = world.createProxy(new Box(Vector3(2, 1, 1)));
box1->setTransformation(identity);
box3->setTransformation(identity);
world.addProxy(box3);
box1->translate(0.0, (real) 1.0, 0.0);
results = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL(results.size(), (size_t) 4);
for (it = results.begin(); it != results.end(); ++it) {
CollisionInfo info = *it;
Vector3 p = info.collisionPoint;
CPPUNIT_ASSERT_DOUBLES_EQUAL((real) 1.0, p.getY(), 0.1e-5);
CPPUNIT_ASSERT_DOUBLES_EQUAL((real) 0.0, info.penetrationDepth, 0.1e-5);
}
#undef DUMP_RESULTS
#undef DUMP_VERTICES
}
void NarrowPhaseTest::boxSphereTest() {
//---------Setup----------------//
World world(Vector3(2000, 2000, 2000));
Proxy* sphere = world.createProxy(new Sphere(2));
Proxy* box = world.createProxy(new Box(10, 10, 10));
//put box into a container to simplify translations with rotated box
Proxy* boxContainer = world.createProxy();
boxContainer->addChild(box);
world.addProxy(sphere);
world.addProxy(boxContainer);
world.prepareSimulation();
//Basic setup: Sphere of radius 2 around (0,0,0)
// Cube of size 10 moving around
//--------Test 1: No Collision, but overlapping BVs-------//
boxContainer->translate(0, 2, 2);
std::list<CollisionInfo> npc1 = world.calculateAllCollisions().getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL(true, npc1.empty());
//--------Test 2: unrotated full collision with box-face ABCD-----//
boxContainer->translate(-1, -3, -1);
WorldCollisions coll2 = world.calculateAllCollisions();
std::list<CollisionInfo> npc2 = coll2.getNarrowPhaseCollisions();
//we should now have a collision
CPPUNIT_ASSERT_EQUAL((size_t)1, npc2.size());
CollisionInfo ci2 = *(npc2.begin());
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci2.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci2.normal);
CPPUNIT_ASSERT_EQUAL((real) 1.0, ci2.penetrationDepth);
CPPUNIT_ASSERT_EQUAL(box, ci2.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(sphere, ci2.penetratedProxy);
//--------Test 3: rotated full collision with box-edge AB-----//
//move box in y-dir so that the edge AB holds the closest point
boxContainer->translate(0, 1, 0);
box->rotate(45, 1, 0, 0);
WorldCollisions coll3 = world.calculateAllCollisions();
std::list<CollisionInfo> npc3 = coll3.getNarrowPhaseCollisions();
//This ensures that broadphase and rigid middlephase are working correctly
CPPUNIT_ASSERT_EQUAL((size_t)1,
(size_t)coll3.getBroadPhaseCollisions()->getResults().size());
CPPUNIT_ASSERT_EQUAL((size_t)1, (size_t)coll3.getRigidBoundingVolumeCollisions().size());
//Collision should be the same
CPPUNIT_ASSERT_EQUAL((size_t)1, npc3.size());
CollisionInfo ci3 = *(npc3.begin());
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci3.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci3.normal);
CPPUNIT_ASSERT_EQUAL((real) 1.0, ci3.penetrationDepth);
CPPUNIT_ASSERT_EQUAL(box, ci3.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(sphere, ci3.penetratedProxy);
//--------Test 4: rotated full collision with vertex A-------//
//move box in y-dir so that the vertex A is the closest point
boxContainer->translate(1, 0, 0);
box->rotate(45, 0, 0, 1); //i am not sure if this is correct- vertexA
//should now be the single lowest point from the box
WorldCollisions coll4 = world.calculateAllCollisions();
std::list<CollisionInfo> npc4 = coll4.getNarrowPhaseCollisions();
//Collision should be the same
CPPUNIT_ASSERT_EQUAL((size_t)1, npc4.size());
CollisionInfo ci4 = *(npc4.begin());
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci4.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci4.normal);
CPPUNIT_ASSERT_EQUAL((real) 1.0, ci4.penetrationDepth);
CPPUNIT_ASSERT_EQUAL(box, ci4.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(sphere, ci4.penetratedProxy);
//--------Test 5: rotated touching-------//
//move box up 1 unit in z-dir so that vertexA touches the sphere
boxContainer->translate(0, 0, 1);
//should now be the single lowest point from the box
WorldCollisions coll5 = world.calculateAllCollisions();
std::list<CollisionInfo> npc5 = coll5.getNarrowPhaseCollisions();
//Collision should be the same
CPPUNIT_ASSERT_EQUAL((size_t)1, npc5.size());
CollisionInfo ci5 = *(npc5.begin());
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 2), ci5.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 1), ci5.normal);
CPPUNIT_ASSERT_EQUAL((real) 0.0, ci5.penetrationDepth);
CPPUNIT_ASSERT_EQUAL(box, ci5.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(sphere, ci5.penetratedProxy);
//--------Test 6: box hits center of sphere-------//
boxContainer->translate(0, 0, -2);
//should now be the single lowest point from the box
WorldCollisions coll6 = world.calculateAllCollisions();
std::list<CollisionInfo> npc6 = coll6.getNarrowPhaseCollisions();
//Collision should be the same
CPPUNIT_ASSERT_EQUAL((size_t)1, npc6.size());
CollisionInfo ci6 = *(npc6.begin());
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 0), ci6.collisionPoint);
//We should have an arbitrary normal vector of lenght 1
CPPUNIT_ASSERT_DOUBLES_EQUAL(1 , ci6.normal.length(), 0.01);
CPPUNIT_ASSERT_EQUAL((real) 2.0, ci6.penetrationDepth);
CPPUNIT_ASSERT_EQUAL(box, ci6.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(sphere, ci6.penetratedProxy);
//-------Test 7: unrotated collision with vertexE---//
//reset the box-orientation, move it down so that vertexG is at (0,0,0)
//now we will move the sphere around the faces, edges and vertices
Matrix m;
box->setTransformation(m); //unrotated
boxContainer->setTransformation(m);
boxContainer->translate(-10, -10, -10);
world.calculateAllCollisions(); //make sure the box has MOVEFLAG_UNMOVED
sphere->translate(1, 1, 1);
WorldCollisions coll7 = world.calculateAllCollisions();
std::list<CollisionInfo> npc7 = coll7.getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t)1, npc7.size());
CollisionInfo ci7 = *(npc7.begin());
//we have moved the sphere - it should be the penetrating proxy
CPPUNIT_ASSERT_EQUAL(sphere, ci7.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(box, ci7.penetratedProxy);
CPPUNIT_ASSERT_EQUAL(Vector3(0, 0, 0), ci7.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(1, 1, 1).normalize(), ci7.normal);
//high tolerance, we are calculating with babylonian length
CPPUNIT_ASSERT_DOUBLES_EQUAL((real) 2.0 - Vector3(1,1,1).length(), ci7.penetrationDepth, 0.1);
//---------Test 8: Collision with Face CDHG-----------//
sphere->translate(-3, 0, -3);
WorldCollisions coll8 = world.calculateAllCollisions();
std::list<CollisionInfo> npc8 = coll8.getNarrowPhaseCollisions();
CPPUNIT_ASSERT_EQUAL((size_t)1, npc8.size());
CollisionInfo ci8 = *(npc8.begin());
CPPUNIT_ASSERT_EQUAL(sphere, ci8.penetratingProxy);
CPPUNIT_ASSERT_EQUAL(box, ci8.penetratedProxy);
CPPUNIT_ASSERT_EQUAL(Vector3(-2, 0, -2), ci8.collisionPoint);
CPPUNIT_ASSERT_EQUAL(Vector3(0, 1, 0), ci8.normal);
//high tolerance, we are calculating with babylonian length
CPPUNIT_ASSERT_EQUAL((real) 1.0, ci8.penetrationDepth);
}
}
/*
* vim: et sw=4 ts=4
*/
| 39.526614 | 102 | 0.607902 | [
"mesh",
"shape",
"vector"
] |
c9805e66f04f7e6f4bda126dba4b865e76a02718 | 10,097 | cc | C++ | RecoBTag/ONNXRuntime/plugins/DeepVertexONNXJetTagsProducer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoBTag/ONNXRuntime/plugins/DeepVertexONNXJetTagsProducer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoBTag/ONNXRuntime/plugins/DeepVertexONNXJetTagsProducer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/makeRefToBaseProdFrom.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include "DataFormats/BTauReco/interface/JetTag.h"
#include "DataFormats/BTauReco/interface/DeepFlavourTagInfo.h"
#include "PhysicsTools/ONNXRuntime/interface/ONNXRuntime.h"
#include "RecoBTag/ONNXRuntime/interface/tensor_fillers.h"
#include "RecoBTag/ONNXRuntime/interface/tensor_configs.h"
using namespace cms::Ort;
class DeepVertexONNXJetTagsProducer : public edm::stream::EDProducer<edm::GlobalCache<ONNXRuntime>> {
public:
explicit DeepVertexONNXJetTagsProducer(const edm::ParameterSet&, const ONNXRuntime*);
~DeepVertexONNXJetTagsProducer() override;
static void fillDescriptions(edm::ConfigurationDescriptions&);
static std::unique_ptr<ONNXRuntime> initializeGlobalCache(const edm::ParameterSet&);
static void globalEndJob(const ONNXRuntime*);
private:
typedef std::vector<reco::DeepFlavourTagInfo> TagInfoCollection;
typedef reco::JetTagCollection JetTagCollection;
void produce(edm::Event&, const edm::EventSetup&) override;
void make_inputs(unsigned i_jet, const reco::DeepFlavourTagInfo& taginfo);
const edm::EDGetTokenT<TagInfoCollection> src_;
std::vector<std::string> flav_names_;
std::vector<std::string> input_names_;
std::vector<std::string> output_names_;
const double min_jet_pt_;
const double max_jet_eta_;
enum InputIndexes { kGlobal = 0, kSeedingTracks = 1, kNeighbourTracks = 2 };
const static unsigned n_features_global_ = deepvertex::n_features_global;
const static unsigned n_seed_ = deepvertex::n_seed;
const static unsigned n_features_seed_ = deepvertex::n_features_seed;
const static unsigned n_neighbor_ = deepvertex::n_neighbor;
const static unsigned n_features_neighbor_ = deepvertex::n_features_neighbor;
const static std::vector<unsigned> input_sizes_;
// hold the input data
FloatArrays data_;
};
const std::vector<unsigned> DeepVertexONNXJetTagsProducer::input_sizes_{n_features_global_,
n_seed_* n_features_seed_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_,
n_neighbor_* n_features_neighbor_};
DeepVertexONNXJetTagsProducer::DeepVertexONNXJetTagsProducer(const edm::ParameterSet& iConfig, const ONNXRuntime* cache)
: src_(consumes<TagInfoCollection>(iConfig.getParameter<edm::InputTag>("src"))),
flav_names_(iConfig.getParameter<std::vector<std::string>>("flav_names")),
input_names_(iConfig.getParameter<std::vector<std::string>>("input_names")),
output_names_(iConfig.getParameter<std::vector<std::string>>("output_names")),
min_jet_pt_(iConfig.getParameter<double>("min_jet_pt")),
max_jet_eta_(iConfig.getParameter<double>("max_jet_eta")) {
// get output names from flav_names
for (const auto& flav_name : flav_names_) {
produces<JetTagCollection>(flav_name);
}
assert(input_names_.size() == input_sizes_.size());
}
DeepVertexONNXJetTagsProducer::~DeepVertexONNXJetTagsProducer() {}
void DeepVertexONNXJetTagsProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
// pfDeepFlavourJetTags
edm::ParameterSetDescription desc;
desc.add<edm::InputTag>("src", edm::InputTag("pfDeepFlavourTagInfos"));
desc.add<std::vector<std::string>>("input_names",
{"input_1",
"input_2",
"input_3",
"input_4",
"input_5",
"input_6",
"input_7",
"input_8",
"input_9",
"input_10",
"input_11",
"input_12"});
desc.add<edm::FileInPath>("model_path", edm::FileInPath("RecoBTag/Combined/data/DeepVertex/phase1_deepvertex.onnx"));
desc.add<std::vector<std::string>>("output_names", {"dense_6"});
desc.add<std::vector<std::string>>("flav_names", std::vector<std::string>{"probb", "probc", "probuds", "probg"});
desc.add<double>("min_jet_pt", 15.0);
desc.add<double>("max_jet_eta", 2.5);
descriptions.add("pfDeepVertexJetTags", desc);
}
std::unique_ptr<ONNXRuntime> DeepVertexONNXJetTagsProducer::initializeGlobalCache(const edm::ParameterSet& iConfig) {
return std::make_unique<ONNXRuntime>(iConfig.getParameter<edm::FileInPath>("model_path").fullPath());
}
void DeepVertexONNXJetTagsProducer::globalEndJob(const ONNXRuntime* cache) {}
void DeepVertexONNXJetTagsProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) {
edm::Handle<TagInfoCollection> tag_infos;
iEvent.getByToken(src_, tag_infos);
data_.clear();
std::vector<std::unique_ptr<JetTagCollection>> output_tags;
if (!tag_infos->empty()) {
unsigned good_taginfo_count = 0;
std::vector<bool> good_taginfo_jets(tag_infos->size(), false);
for (unsigned jet_n = 0; jet_n < tag_infos->size(); ++jet_n) {
const auto& jet_ref = (*tag_infos)[jet_n].jet();
if (jet_ref->pt() > min_jet_pt_ && std::fabs(jet_ref->eta()) < max_jet_eta_) {
good_taginfo_count++;
good_taginfo_jets[jet_n] = true;
}
}
// init data storage w correct size
for (const auto& len : input_sizes_) {
data_.emplace_back(good_taginfo_count * len, 0);
}
// initialize output collection
auto jet_ref = tag_infos->begin()->jet();
auto ref2prod = edm::makeRefToBaseProdFrom(jet_ref, iEvent);
for (std::size_t i = 0; i < flav_names_.size(); i++) {
output_tags.emplace_back(std::make_unique<JetTagCollection>(ref2prod));
}
// convert inputs
unsigned inputs_done_count = 0;
for (unsigned jet_n = 0; jet_n < tag_infos->size(); ++jet_n) {
if (good_taginfo_jets[jet_n]) {
const auto& taginfo = (*tag_infos)[jet_n];
make_inputs(inputs_done_count, taginfo);
inputs_done_count++;
}
}
// run prediction
assert(inputs_done_count == good_taginfo_count);
const auto outputs = globalCache()->run(input_names_, data_, {}, output_names_, good_taginfo_count)[0];
assert(outputs.size() == flav_names_.size() * good_taginfo_count);
// get the outputs
unsigned i_output = 0;
for (unsigned jet_n = 0; jet_n < tag_infos->size(); ++jet_n) {
const auto& jet_ref = (*tag_infos)[jet_n].jet();
for (std::size_t flav_n = 0; flav_n < flav_names_.size(); flav_n++) {
if (good_taginfo_jets[jet_n]) {
(*(output_tags[flav_n]))[jet_ref] = outputs[i_output];
++i_output;
} else {
(*(output_tags[flav_n]))[jet_ref] = -2;
}
}
}
} else {
// create empty output collection
for (std::size_t i = 0; i < flav_names_.size(); i++) {
output_tags.emplace_back(std::make_unique<JetTagCollection>());
}
}
// put into the event
for (std::size_t flav_n = 0; flav_n < flav_names_.size(); ++flav_n) {
iEvent.put(std::move(output_tags[flav_n]), flav_names_[flav_n]);
}
}
void DeepVertexONNXJetTagsProducer::make_inputs(unsigned i_jet, const reco::DeepFlavourTagInfo& taginfo) {
const auto& features = taginfo.features();
float* ptr = nullptr;
const float* start = nullptr;
unsigned offset = 0;
// jet variables
offset = i_jet * input_sizes_[kGlobal];
const auto& jet_features = features.jet_features;
ptr = &data_[kGlobal][offset];
start = ptr;
jet4vec_tensor_filler(ptr, jet_features);
assert(start + n_features_global_ - 1 == ptr);
// seeds
auto max_seed_n = std::min(features.seed_features.size(), (std::size_t)n_seed_);
offset = i_jet * input_sizes_[kSeedingTracks];
for (std::size_t seed_n = 0; seed_n < max_seed_n; seed_n++) {
const auto& seed_features = features.seed_features[seed_n];
ptr = &data_[kSeedingTracks][offset + seed_n * n_features_seed_];
start = ptr;
seedTrack_tensor_filler(ptr, seed_features);
assert(start + n_features_seed_ - 1 == ptr);
}
// neighbours
offset = i_jet * input_sizes_[kNeighbourTracks];
for (std::size_t seed_n = 0; seed_n < max_seed_n; seed_n++) {
const auto& neighbourTracks_features = features.seed_features[seed_n].nearTracks;
auto max_neighbour_n = std::min(neighbourTracks_features.size(), (std::size_t)n_neighbor_);
for (std::size_t neighbour_n = 0; neighbour_n < max_neighbour_n; neighbour_n++) {
ptr = &data_[kNeighbourTracks + seed_n][offset + neighbour_n * n_features_neighbor_];
start = ptr;
neighbourTrack_tensor_filler(ptr, neighbourTracks_features[neighbour_n]);
assert(start + n_features_neighbor_ - 1 == ptr);
}
}
}
//define this as a plug-in
DEFINE_FWK_MODULE(DeepVertexONNXJetTagsProducer);
| 42.783898 | 120 | 0.639299 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.