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
4a785038a5940dbaa9e1f47ffb23398eee8308a9
9,277
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/navigation/SoScXMLNavigationInvoke.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/navigation/SoScXMLNavigationInvoke.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/navigation/SoScXMLNavigationInvoke.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ #include "navigation/SoScXMLNavigationInvoke.h" #include <assert.h> #include <math.h> #include <float.h> #include <Inventor/SbViewVolume.h> #include <Inventor/SbRotation.h> #include <Inventor/SbPlane.h> #include <Inventor/SbLine.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/nodes/SoOrthographicCamera.h> #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/fields/SoSFVec3d.h> #include <Inventor/scxml/SoScXMLStateMachine.h> #include <Inventor/scxml/SoScXMLEvent.h> SCXML_OBJECT_ABSTRACT_SOURCE(SoScXMLNavigationInvoke); void SoScXMLNavigationInvoke::initClass(void) { SCXML_OBJECT_INIT_ABSTRACT_CLASS(SoScXMLNavigationInvoke, ScXMLInvoke); } // Rotate camera around its focal point. void SoScXMLNavigationInvoke::reorientCamera(SoCamera * camera, const SbRotation & rot) { if (camera == NULL) return; // Find global coordinates of focal point. SbVec3f direction; camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), direction); SbVec3f focalpoint = camera->position.getValue() + camera->focalDistance.getValue() * direction; // Set new orientation value by accumulating the new rotation. camera->orientation = rot * camera->orientation.getValue(); // Reposition camera so we are still pointing at the same old focal point. camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), direction); camera->position = focalpoint - camera->focalDistance.getValue() * direction; // some custom code to support UTMCamera cameras static const SoType utmcamtype(SoType::fromName("UTMCamera")); if (utmcamtype != SoType::badType() && camera->isOfType(utmcamtype)) { SbVec3d offset; offset.setValue(camera->position.getValue()); SoSFVec3d * utmpositionfield = (SoSFVec3d *) camera->getField("utmposition"); assert(utmpositionfield); utmpositionfield->setValue(utmpositionfield->getValue()+offset); camera->position.setValue(0.0f, 0.0f, 0.0f); } } // Move camera parallel with the plane orthogonal to the camera // direction vector. void SoScXMLNavigationInvoke::panCamera(SoCamera * camera, float vpaspect, const SbPlane & panplane, const SbVec2f & previous, const SbVec2f & current) { if (camera == NULL) return; // can happen for empty scenegraph if (current == previous) return; // useless invocation // Find projection points for the last and current mouse coordinates. SbViewVolume vv = camera->getViewVolume(vpaspect); SbLine line; vv.projectPointToLine(current, line); SbVec3f current_planept; panplane.intersect(line, current_planept); vv.projectPointToLine(previous, line); SbVec3f old_planept; panplane.intersect(line, old_planept); // Reposition camera according to the vector difference between the // projected points. camera->position = camera->position.getValue() - (current_planept - old_planept); } // ************************************************************************* // Dependent on the camera type this will either shrink or expand the // height of the viewport (orthogonal camera) or move the camera // closer or further away from the focal point in the scene. void SoScXMLNavigationInvoke::zoom(SoCamera * camera, float diffvalue) { if (camera == NULL) return; // can happen for empty scenegraph SoType cameratype = camera->getTypeId(); // This will be in the range of <0, ->>. float multiplicator = float(exp(diffvalue)); if (cameratype.isDerivedFrom(SoOrthographicCamera::getClassTypeId())) { // Since there's no perspective, "zooming" in the original sense // of the word won't have any visible effect. So we just increase // or decrease the field-of-view values of the camera instead, to // "shrink" the projection size of the model / scene. SoOrthographicCamera * oc = (SoOrthographicCamera *) camera; oc->height = oc->height.getValue() * multiplicator; } else { // FrustumCamera can be found in the SmallChange CVS module (it's // a camera that lets you specify (for instance) an off-center // frustum (similar to glFrustum()) static const SbName frustumtypename("FrustumCamera"); if (!cameratype.isDerivedFrom(SoPerspectiveCamera::getClassTypeId()) && cameratype.getName() != frustumtypename) { static SbBool first = TRUE; if (first) { SoDebugError::postWarning("SoGuiFullViewerP::zoom", "Unknown camera type, " "will zoom by moving position, but this might not be correct."); first = FALSE; } } const float oldfocaldist = camera->focalDistance.getValue(); const float newfocaldist = oldfocaldist * multiplicator; SbVec3f direction; camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), direction); const SbVec3f oldpos = camera->position.getValue(); const SbVec3f newpos = oldpos + (newfocaldist - oldfocaldist) * -direction; // This catches a rather common user interface "buglet": if the // user zooms the camera out to a distance from origo larger than // what we still can safely do floating point calculations on // (i.e. without getting NaN or Inf values), the faulty floating // point values will propagate until we start to get debug error // messages and eventually an assert failure from core Coin code. // // With the below bounds check, this problem is avoided. // // (But note that we depend on the input argument ''diffvalue'' to // be small enough that zooming happens gradually. Ideally, we // should also check distorigo with isinf() and isnan() (or // inversely; isinfite()), but those only became standardized with // C99.) const float distorigo = newpos.length(); // sqrt(FLT_MAX) == ~ 1e+19, which should be both safe for further // calculations and ok for the end-user and app-programmer. if (distorigo > float(sqrt(FLT_MAX))) { //SoDebugError::postWarning("SoGuiFullViewerP::zoom", // "zoomed too far (distance to origo==%f (%e))", // distorigo, distorigo); } else { camera->position = newpos; camera->focalDistance = newfocaldist; } } } SoScXMLStateMachine * SoScXMLNavigationInvoke::castToSo(ScXMLStateMachine * statemachine) const { if (!statemachine) { SbString id; id.sprintf("%s::invoke", this->getTypeId().getName().getString()); SoDebugError::post(id.getString(), "Statemachine argument was NULL."); return NULL; } if (!statemachine->isOfType(SoScXMLStateMachine::getClassTypeId())) { SbString id; id.sprintf("%s::invoke", this->getTypeId().getName().getString()); SoDebugError::post(id.getString(), "SoScXMLNavigationInvoke-derived objects require " "SoScXMLStateMachine-derived state machines."); return NULL; } return static_cast<SoScXMLStateMachine *>(statemachine); } const SoEvent * SoScXMLNavigationInvoke::getSoEvent(SoScXMLStateMachine * statemachine) const { const ScXMLEvent * ev = statemachine->getCurrentEvent(); if (!ev) { SbString id; id.sprintf("%s::invoke", this->getTypeId().getName().getString()); SoDebugError::post(id.getString(), "SoScXMLStateMachine has no current event."); return NULL; } if (!ev->isOfType(SoScXMLEvent::getClassTypeId())) { SbString id; id.sprintf("%s::invoke", this->getTypeId().getName().getString()); SoDebugError::post(id.getString(), "SoScXMLStateMachine current event is not " "of SoScXMLStateMachine type."); return NULL; } const SoEvent * soev = static_cast<const SoScXMLEvent *>(ev)->getSoEvent(); if (!soev) { SbString id; id.sprintf("%s::invoke", this->getTypeId().getName().getString()); SoDebugError::post(id.getString(), "SoScXMLStateMachine current event does not carry " "an SoEvent-derived event."); return NULL; } return soev; }
38.334711
98
0.664547
[ "vector", "model", "3d" ]
4a89450d2ff3103b66cbe3cba1bb5391c302d31c
1,557
cpp
C++
sem1/hw11/hw11.2/hw11.2/KMP_algorithm.cpp
Daria-Donina/Homework
8853fb65c7a0ad62556a49d12908098af9caf7ed
[ "Apache-2.0" ]
1
2018-11-29T11:12:51.000Z
2018-11-29T11:12:51.000Z
sem1/hw11/hw11.2/hw11.2/KMP_algorithm.cpp
Daria-Donina/Homework
8853fb65c7a0ad62556a49d12908098af9caf7ed
[ "Apache-2.0" ]
null
null
null
sem1/hw11/hw11.2/hw11.2/KMP_algorithm.cpp
Daria-Donina/Homework
8853fb65c7a0ad62556a49d12908098af9caf7ed
[ "Apache-2.0" ]
null
null
null
#include "KMP_algorithm.h" #include <string> #include <fstream> #include <vector> #include <iostream> using namespace std; vector<int> prefixFunction(const string &str) { vector<int> prefix(str.length()); prefix[0] = 0; for (int i = 1; i < str.length(); ++i) { int index = i - 1; while (index != -1) { if (str[i] == str[prefix[index]]) { prefix[i] = prefix[index] + 1; break; } else { index = prefix[index] - 1; } } } return prefix; } int countFirstOccurenceOfAPattern(const string &str, const string &pattern) { vector<int> prefixPattern(pattern.length()); prefixPattern = prefixFunction(pattern); int counter = 0; for (int i = 0; i < str.length(); ++i) { if (str[i] == pattern[counter]) { ++counter; if (counter == pattern.length()) { return i - pattern.length() + 2; } } else if (counter > 0) { counter = prefixPattern[counter - 1]; i += counter; } } return -1; } bool programTest() { ifstream inputData("test.txt"); string str1 = ""; getline(inputData, str1); string pattern1 = "all"; string str2 = ""; getline(inputData, str2); string pattern2 = "goodbye"; string str3 = ""; getline(inputData, str3); string pattern3 = "alive"; inputData.close(); return countFirstOccurenceOfAPattern(str1, pattern1) == 1 && countFirstOccurenceOfAPattern(str2, pattern2) == 9 && countFirstOccurenceOfAPattern(str3, pattern3) == 14; } void test() { if (programTest()) { cout << "Tests passed :)" << endl; } else { cout << "Tests failed :(" << endl; } }
17.896552
115
0.619782
[ "vector" ]
4a8f1db655dac069155e787f23bd590c1c1be40b
4,193
cc
C++
tensorstore/driver/zarr/zlib_compressor_test.cc
google/tensorstore
8df16a67553debaec098698ceaa5404eaf79634a
[ "BSD-2-Clause" ]
106
2020-04-02T20:00:18.000Z
2022-03-23T20:27:31.000Z
tensorstore/driver/zarr/zlib_compressor_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
28
2020-04-12T02:04:47.000Z
2022-03-23T20:27:03.000Z
tensorstore/driver/zarr/zlib_compressor_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
18
2020-04-08T06:41:30.000Z
2022-02-18T03:05:49.000Z
// Copyright 2020 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorstore/driver/zarr/compressor.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" namespace { using tensorstore::MatchesStatus; using tensorstore::internal_zarr::Compressor; class ZlibCompressorTest : public ::testing::TestWithParam<const char*> {}; INSTANTIATE_TEST_SUITE_P(ZlibCompressorTestCases, ZlibCompressorTest, ::testing::Values("zlib", "gzip")); // Tests that a small input round trips. TEST_P(ZlibCompressorTest, SmallRoundtrip) { auto compressor = Compressor::FromJson({{"id", GetParam()}, {"level", 6}}).value(); const absl::Cord input("The quick brown fox jumped over the lazy dog."); absl::Cord encode_result, decode_result; TENSORSTORE_ASSERT_OK(compressor->Encode(input, &encode_result, 1)); TENSORSTORE_ASSERT_OK(compressor->Decode(encode_result, &decode_result, 1)); EXPECT_EQ(input, decode_result); } // Tests that specifying a level of 1 gives the same result as not specifying a // level. TEST_P(ZlibCompressorTest, DefaultLevel) { auto compressor1 = Compressor::FromJson({{"id", GetParam()}}).value(); auto compressor2 = Compressor::FromJson({{"id", GetParam()}, {"level", 1}}).value(); const absl::Cord input("The quick brown fox jumped over the lazy dog."); absl::Cord encode_result1, encode_result2; TENSORSTORE_ASSERT_OK(compressor1->Encode(input, &encode_result1, 1)); TENSORSTORE_ASSERT_OK(compressor2->Encode(input, &encode_result2, 1)); EXPECT_EQ(encode_result1, encode_result2); } // Tests that specifying a level of 9 gives a result that is different from not // specifying a level. TEST_P(ZlibCompressorTest, NonDefaultLevel) { auto compressor1 = Compressor::FromJson({{"id", GetParam()}}).value(); auto compressor2 = Compressor::FromJson({{"id", GetParam()}, {"level", 9}}).value(); const absl::Cord input("The quick brown fox jumped over the lazy dog."); absl::Cord encode_result1, encode_result2; TENSORSTORE_ASSERT_OK(compressor1->Encode(input, &encode_result1, 1)); TENSORSTORE_ASSERT_OK(compressor2->Encode(input, &encode_result2, 1)); EXPECT_NE(encode_result1, encode_result2); absl::Cord decode_result; TENSORSTORE_ASSERT_OK(compressor2->Decode(encode_result2, &decode_result, 1)); EXPECT_EQ(input, decode_result); } // Tests that an invalid parameter gives an error. TEST_P(ZlibCompressorTest, InvalidParameter) { EXPECT_THAT(Compressor::FromJson({{"id", GetParam()}, {"level", "6"}}), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"level\": .*")); EXPECT_THAT(Compressor::FromJson({{"id", GetParam()}, {"level", -1}}), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"level\": .*")); EXPECT_THAT(Compressor::FromJson({{"id", GetParam()}, {"level", 10}}), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"level\": .*")); EXPECT_THAT(Compressor::FromJson({{"id", GetParam()}, {"foo", 10}}), MatchesStatus(absl::StatusCode::kInvalidArgument, "Object includes extra members: \"foo\"")); } TEST_P(ZlibCompressorTest, ToJson) { auto compressor = Compressor::FromJson({{"id", GetParam()}, {"level", 5}}).value(); EXPECT_EQ(nlohmann::json({{"id", GetParam()}, {"level", 5}}), compressor.ToJson()); } } // namespace
43.677083
80
0.696876
[ "object" ]
4a918758160eaa94e3bfbc906e0b2bec677f3395
11,416
cpp
C++
test_package/tests/unit/geom/PointTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
test_package/tests/unit/geom/PointTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
test_package/tests/unit/geom/PointTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
// // Test Suite for geos::geom::Point class. #include <tut/tut.hpp> // geos #include <geos/geom/Point.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateArraySequence.h> #include <geos/geom/Dimension.h> #include <geos/geom/Geometry.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/PrecisionModel.h> #include <geos/io/WKTReader.h> #include <geos/util/IllegalArgumentException.h> // std #include <memory> #include <string> namespace tut { // // Test Group // // Common data used by tests struct test_point_data { typedef geos::geom::Coordinate* CoordinatePtr; typedef geos::geom::Coordinate const* CoordinateCPtr; typedef geos::geom::Geometry* GeometryPtr; typedef std::unique_ptr<geos::geom::Geometry> GeometryAutoPtr; typedef geos::geom::Geometry const* GeometryCPtr; typedef geos::geom::Point* PointPtr; typedef std::unique_ptr<geos::geom::Point> PointAutoPtr; typedef geos::geom::Point const* PointCPtr; typedef geos::geom::GeometryFactory GeometryFactory; geos::geom::PrecisionModel pm_; GeometryFactory::Ptr factory_; geos::io::WKTReader reader_; PointAutoPtr empty_point_; PointPtr point_; test_point_data() : pm_(1000), factory_(GeometryFactory::create(&pm_, 0)) , reader_(factory_.get()), empty_point_(factory_->createPoint()) { // Create non-empty Point auto geo = reader_.read("POINT(1.234 5.678)"); point_ = dynamic_cast<PointPtr>(geo.release()); } ~test_point_data() { factory_->destroyGeometry(point_); } }; typedef test_group<test_point_data> group; typedef group::object object; group test_point_group("geos::geom::Point"); // // Test Cases // // Test of user's constructor to build empty Point template<> template<> void object::test<1> () { PointAutoPtr point(factory_->createPoint()); ensure(point->isEmpty()); } // Test of user's constructor to build non-empty Point template<> template<> void object::test<2> () { using geos::geom::Coordinate; using geos::geom::CoordinateArraySequence; CoordinateArraySequence* coords = new CoordinateArraySequence(); ensure(coords != nullptr); coords->add(Coordinate(1.234, 5.678)); PointAutoPtr point(factory_->createPoint(coords)); ensure(!point->isEmpty()); // currently the empty CoordinateArraySequence constructor // produces a dimension 0 sequence. The dimension is then // autodetected when the first point is inserted. ensure(point->getCoordinateDimension() == 2); } // Test of user's constructor throwing IllegalArgumentException template<> template<> void object::test<3> () { using geos::geom::Coordinate; using geos::geom::CoordinateArraySequence; // TODO - mloskot - temporary solution of Bug #89 CoordinateArraySequence* coords = nullptr; try { coords = new CoordinateArraySequence(); ensure(coords != nullptr); coords->add(Coordinate(1.234, 5.678)); coords->add(Coordinate(4.321, 8.765)); PointAutoPtr point(factory_->createPoint(coords)); fail("IllegalArgumentException expected."); } catch(geos::util::IllegalArgumentException const& e) { // TODO - mloskot - Bug #89: Possible memory leaks caused by Point constructor //delete coords; const char* msg = e.what(); // ok ensure(msg != nullptr); } } // Test of copy constructor template<> template<> void object::test<4> () { GeometryAutoPtr copy(empty_point_->clone()); ensure(copy->isEmpty()); } // Test of isEmpty() for empty Point template<> template<> void object::test<5> () { ensure(empty_point_->isEmpty()); } // Test of isSimple() for empty Point template<> template<> void object::test<6> () { ensure(empty_point_->isSimple()); } // Test of isValid() for empty Point template<> template<> void object::test<7> () { ensure(empty_point_->isValid()); } // Test of getEnvelope() for empty Point template<> template<> void object::test<8> () { auto envelope = empty_point_->getEnvelope(); ensure(envelope != nullptr); ensure(envelope->isEmpty()); } // Test of getBoundary() for empty Point template<> template<> void object::test<9> () { auto boundary = empty_point_->getBoundary(); ensure(boundary != nullptr); ensure(boundary->isEmpty()); } // Test of convexHull() for empty Point template<> template<> void object::test<10> () { auto hull = empty_point_->convexHull(); ensure(hull != nullptr); ensure(hull->isEmpty()); } // Test of getGeometryTypeId() for empty Point template<> template<> void object::test<11> () { ensure_equals(empty_point_->getGeometryTypeId(), geos::geom::GEOS_POINT); } // Test of getGeometryType() for empty Polygon template<> template<> void object::test<12> () { const std::string type("Point"); ensure_equals(empty_point_->getGeometryType(), type); } // Test of getDimension() for empty Point template<> template<> void object::test<13> () { ensure_equals(empty_point_->getDimension(), geos::geom::Dimension::P); } // Test of getBoundaryDimension() for empty Point template<> template<> void object::test<14> () { ensure_equals(empty_point_->getBoundaryDimension(), geos::geom::Dimension::False); } // Test of getNumPoints() for empty Point template<> template<> void object::test<15> () { ensure_equals(empty_point_->getNumPoints(), (size_t)0); } // Test of getLength() for empty Point template<> template<> void object::test<16> () { ensure_equals(empty_point_->getLength(), 0); } // Test of getArea() for empty Point template<> template<> void object::test<17> () { ensure_equals(empty_point_->getArea(), 0); } // Test of isEmpty() for non-empty Point template<> template<> void object::test<18> () { ensure(!point_->isEmpty()); } // Test of isSimple() for non-empty Point template<> template<> void object::test<19> () { ensure(point_->isSimple()); } // Test of isValid() for non-empty Point template<> template<> void object::test<20> () { ensure(point_->isValid()); } // Test of getEnvelope() for non-empty Point template<> template<> void object::test<21> () { auto envelope = point_->getEnvelope(); ensure(envelope != nullptr); ensure(!envelope->isEmpty()); } // Test of getBoundary() for non-empty Point template<> template<> void object::test<22> () { auto boundary = point_->getBoundary(); ensure(boundary != nullptr); ensure(boundary->isEmpty()); } // Test of convexHull() for non-empty Point template<> template<> void object::test<23> () { auto hull = point_->convexHull(); ensure(hull != nullptr); ensure(!hull->isEmpty()); } // Test of getGeometryTypeId() for non-empty Point template<> template<> void object::test<24> () { ensure_equals(point_->getGeometryTypeId(), geos::geom::GEOS_POINT); } // Test of getGeometryType() for non-empty Polygon template<> template<> void object::test<25> () { const std::string type("Point"); ensure_equals(point_->getGeometryType(), type); } // Test of getDimension() for non-empty Point template<> template<> void object::test<26> () { ensure_equals(point_->getDimension(), geos::geom::Dimension::P); } // Test of getBoundaryDimension() for non-empty Point template<> template<> void object::test<27> () { ensure_equals(empty_point_->getBoundaryDimension(), geos::geom::Dimension::False); } // Test of getNumPoints() for non-empty Point template<> template<> void object::test<28> () { ensure_equals(point_->getNumPoints(), (size_t)1); } // Test of getLength() for non-empty Point template<> template<> void object::test<29> () { ensure_equals(point_->getLength(), 0); } // Test of getArea() for non-empty Point template<> template<> void object::test<30> () { ensure_equals(point_->getArea(), 0); } // Test of equals() for empty Point template<> template<> void object::test<31> () { GeometryAutoPtr geo(empty_point_->clone()); ensure(empty_point_->equals(geo.get())); } // Test of equals() for non-empty Point (1.234,5.678) template<> template<> void object::test<32> () { auto p1 = reader_.read("POINT(1.234 5.678)"); auto p2 = reader_.read("POINT(1.234 5.678)"); ensure(p1->equals(p2.get())); } // Test of equals() for non-empty Point (1.23 5.67) template<> template<> void object::test<33> () { auto p1 = reader_.read("POINT(1.23 5.67)"); auto p2 = reader_.read("POINT(1.23 5.67)"); ensure(p1->equals(p2.get())); } // Test of equals() for non-empty Points (1.235 5.678) and (1.234 5.678) template<> template<> void object::test<34> () { auto p1 = reader_.read("POINT(1.235 5.678)"); auto p2 = reader_.read("POINT(1.234 5.678)"); ensure(!p1->equals(p2.get())); } // Test of equals() for non-empty Points (1.2334 5.678) and (1.2333 5.678) template<> template<> void object::test<35> () { auto p1 = reader_.read("POINT(1.2334 5.678)"); auto p2 = reader_.read("POINT(1.2333 5.678)"); ensure(p1->equals(p2.get())); } // Test of equals() for non-empty Points (1.2334 5.678) and (1.2335 5.678) template<> template<> void object::test<36> () { auto p1 = reader_.read("POINT(1.2334 5.678)"); auto p2 = reader_.read("POINT(1.2335 5.678)"); ensure(!p1->equals(p2.get())); } // Test of equals() for non-empty Points (1.2324 5.678) and (1.2325 5.678) template<> template<> void object::test<37> () { auto p1 = reader_.read("POINT(1.2324 5.678)"); auto p2 = reader_.read("POINT(1.2325 5.678)"); ensure(!p1->equals(p2.get())); } // Test of equals() for non-empty Points (1.2324 5.678) and (EMPTY) template<> template<> void object::test<38> () { auto p1 = reader_.read("POINT(1.2324 5.678)"); auto p2 = reader_.read("POINT EMPTY"); ensure(!p1->equals(p2.get())); } // Test of equals() for non-empty Points with negative coordiantes template<> template<> void object::test<39> () { auto pLo = reader_.read("POINT(-1.233 5.678)"); auto pHi = reader_.read("POINT(-1.232 5.678)"); auto p1 = reader_.read("POINT(-1.2326 5.678)"); auto p2 = reader_.read("POINT(-1.2325 5.678)"); auto p3 = reader_.read("POINT(-1.2324 5.678)"); ensure(!p1->equals(p2.get())); ensure(p3->equals(p2.get())); ensure(p1->equals(pLo.get())); ensure(p2->equals(pHi.get())); ensure(p3->equals(pHi.get())); } // Test of getCoordinateDimension() for 2d/3d. template<> template<> void object::test<40> () { auto p = reader_.read("POINT(-1.233 5.678 1.0)"); ensure(p->getCoordinateDimension() == 3); p = reader_.read("POINT(-1.233 5.678)"); ensure(p->getCoordinateDimension() == 2); } template<> template<> void object::test<41> () { // getCoordinate() returns nullptr for empty geometry auto gf = geos::geom::GeometryFactory::create(); std::unique_ptr<geos::geom::Geometry> g(gf->createPoint()); ensure(g->getCoordinate() == nullptr); } // test isDimensionStrict for empty Point template<> template<> void object::test<42> () { ensure(empty_point_->isDimensionStrict(geos::geom::Dimension::P)); ensure(!empty_point_->isDimensionStrict(geos::geom::Dimension::A)); } // test isDimensionStrict for non-empty Point template<> template<> void object::test<43> () { ensure(point_->isDimensionStrict(geos::geom::Dimension::P)); ensure(!point_->isDimensionStrict(geos::geom::Dimension::A)); } } // namespace tut
20.606498
86
0.666083
[ "geometry", "object", "3d" ]
4a932fbdccac52a779bceec24f1599be959c8181
5,218
cpp
C++
src/NBoard.cpp
louism33/Mudpuppy
27ec402aaaed0020078a331e4be645a44d728de5
[ "MIT" ]
null
null
null
src/NBoard.cpp
louism33/Mudpuppy
27ec402aaaed0020078a331e4be645a44d728de5
[ "MIT" ]
null
null
null
src/NBoard.cpp
louism33/Mudpuppy
27ec402aaaed0020078a331e4be645a44d728de5
[ "MIT" ]
null
null
null
// // Created by louis on 6/26/19. // #include <iostream> #include <cstring> #include <string> #include <boost/tokenizer.hpp> #include <ncurses.h> #include <regex> #include <bitset> #include <sstream> #include <iostream> #include <assert.h> #include <math.h> #include <jmorecfg.h> #include "Art.h" #include "BitBoardUtils.h" #include "NBoard.h" #include "MoveUtils.h" #include "Move.h" #include "main.h" #include "Board.h" #include <cstdint> using namespace boost; using namespace std; int madeMoveNumber = 0; void parseBoardCommand(string token, Board *board); static void send_move(uint64_t move, int score, TimePoint time); vector<string> split(const string &str, const string &delim) { vector<string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == string::npos) pos = str.length(); string token = str.substr(prev, pos - prev); if (!token.empty()) tokens.push_back(token); prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } void mainLoopNBoard(EngineBase *engine) { cout << "starting main nBoard loop " << endl; string cmd, c, setGameHelper; Board board; while (true) { std::getline(cin, cmd); if (cmd == "\n" || cmd.empty()) { continue; } const vector<string> &tokens = split(cmd, " "); c = tokens[0]; if (c == "nboard") { madeMoveNumber = 0; } else if (c == "d") { printBoardWithIndexAndLegalMoves(board); } else if (c == "hint") { cout << "not implemented yet " << endl; } else if (c == "learn") { cout << "not implemented yet " << endl; } else if (c == "analyse") { cout << "not implemented yet " << endl; } else if (c == "go") { cout << "status mudpuppy is thinking" << endl; TimePoint s = now(); uint64_t move = engine->getBestMove(board); TimePoint e = now(); send_move(move, engine->getDisplayScoreOfMove(board), e - s); cout << "status mudpuppy is waiting" << endl; } else if (c == "ping") { cout << "pong " << tokens[1] << endl; } else if (c == "move") { cout << "not implemented yet " << endl; } else if (c == "set") { if (tokens[1] == "game") { setGameHelper = ""; for (int i = 2; i < tokens.size(); i++) { setGameHelper += tokens[i]; } parseBoardCommand(setGameHelper, &board); } else if (tokens[1] == "contempt") { cout << "not implemented yet " << endl; } else if (tokens[1] == "depth") { engine->setDepthLimit(stoi(tokens[2])); } } else if (c == "quit") { cout << "received quit command, quitting" << endl; return; } } } string *moves = new string[128]; int getMovesFromToken(string token) { int index = 0; std::regex e(R"([ABCDEFHGP][12345678A])"); std::sregex_iterator iter(token.begin(), token.end(), e); std::sregex_iterator end; while (iter != end) { moves[index++] = ((*iter)[0]); ++iter; } moves[index] = "X"; if (madeMoveNumber > index) { // protocol does not make it clear when a new game starts... cout << "status assuming there is a new game!"<<endl; madeMoveNumber = -1; } return madeMoveNumber; } static void send_move(uint64_t move, int score, TimePoint time) { const string &s = getMoveStringFromMoveCAP(move); cout << "=== " << s << "/" << 1.0 * score << "/" << 0.001 * time << endl; } void parseBoardCommand(string token, Board *board) { if (getMovesFromToken(token) == -1) { madeMoveNumber = 0; cout << "status resetting board etc" << endl; board->reset(); printBoardWithIndexAndLegalMoves(*board); } for (int i = madeMoveNumber; i < 128; i++) { string &mv = moves[i]; if (mv == "X") { break; } board->makeMoveSB(&mv); madeMoveNumber++; } } /* * /home/louis/CLionProjects/mudpuppy/bin set game (;GM[Othello]PC[NBoard]DT[2019-06-27 15:34:50 GMT]PB[Ntest4]PW[louis]RE[?]TI[5:00]TY[8]BO[8 ---------------------------O*------*O--------------------------- *]B[D3/-1.34]W[C5//2.029]B[E6/-1.30]W[F5//5.09]B[F6/-0.51]W[D7//14.009]B[F4/1.68]W[E3//0.75]B[F3/3.11]W[E2//1.177]B[C4/4.08]W[G6//2.2]B[B6/4.79]W[A7//2.104]B[F1/12.66]W[C3//2.207]B[D6/15.17]W[G3//4.644]B[C6/19.94]W[D1//1.127]B[E7/24.15]W[D8//7.094]B[F7/26.12]W[G8//2.797]B[F2/28.44]W[C7//2.949]B[H3/30.83]W[G4//2.528]B[G5/29.58]W[H5//2.6550000000000002]B[H6/34.26]W[H7//1.151]B[E1/33.43]W[G1//1.608]B[H4/31.11]W[H2//2.125]B[C2/33.32]W[C1//2.235]B[D2/51.85]W[G7//3.251]B[F8/57.82]W[E8//1.7910000000000001]B[H8/59.42]W[PA//3.142]B[H1/61.54]W[PA//1.162]B[B1/59.85]W[B2//1.611]B[A1/64.00]W[B3//1.879]B[G2/62.00/0.01]W[PA//1.61]B[A3/62.00]W[A2//1.387]B[B4/62.00]W[A4//3.108]B[B5/62.00]W[PA//0.886]B[A6/62.00]W[A5//0.405]B[B7/62.00]W[C8//1.089]B[A8/62.00]W[PA//0.417];) */
32.01227
929
0.543887
[ "vector" ]
4aa1082aa218fd89ebdd1b871d827c7f201f388e
11,119
cpp
C++
src/entry_node.cpp
ryanloney/model_server
23889884dcdbd214c80b7fed096b4f70e935c62e
[ "Apache-2.0" ]
null
null
null
src/entry_node.cpp
ryanloney/model_server
23889884dcdbd214c80b7fed096b4f70e935c62e
[ "Apache-2.0" ]
null
null
null
src/entry_node.cpp
ryanloney/model_server
23889884dcdbd214c80b7fed096b4f70e935c62e
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "entry_node.hpp" #include <functional> #include <memory> #include <string> #include <utility> #include <inference_engine.hpp> #include "binaryutils.hpp" #include "logging.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wall" #include "tensorflow/core/framework/tensor.h" #pragma GCC diagnostic pop namespace ovms { Status EntryNode::execute(session_key_t sessionId, PipelineEventQueue& notifyEndQueue) { // this should be created in EntryNode::SetInputs, or special method for entry node called // in event loop can be done in future release while implementing dynamic demultiplexing at // entry node NodeSessionMetadata metadata; auto nodeSession = getNodeSession(metadata); // call to create session if (!nodeSession) { notifyEndQueue.push(NodeSessionKeyPair(*this, nodeSession->getSessionKey())); return StatusCode::INTERNAL_ERROR; } notifyEndQueue.push(NodeSessionKeyPair(*this, nodeSession->getSessionKey())); return StatusCode::OK; } Status EntryNode::fetchResults(NodeSession& nodeSession, SessionResults& nodeSessionOutputs) { BlobMap outputs; auto status = fetchResults(outputs); if (!status.ok()) { return status; } SessionResult metaOutputsPair{nodeSession.getNodeSessionMetadata(), std::move(outputs)}; auto it = nodeSessionOutputs.emplace(nodeSession.getSessionKey(), std::move(metaOutputsPair)); if (!it.second) { SPDLOG_LOGGER_DEBUG(dag_executor_logger, "Failed to set entry node session results."); return StatusCode::UNKNOWN_ERROR; } return StatusCode::OK; } Status EntryNode::fetchResults(BlobMap& outputs) { // Fill outputs map with tensorflow predict request inputs. Fetch only those that are required in following nodes for (const auto& node : this->next) { for (const auto& pair : node.get().getMappingByDependency(*this)) { const auto& outputName = pair.first; if (outputs.find(outputName) != outputs.end()) { continue; } auto it = request->inputs().find(outputName); if (it == request->inputs().end()) { std::stringstream ss; ss << "Required input: " << outputName; const std::string details = ss.str(); SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}] Missing input with specific name: {}", getName(), details); return Status(StatusCode::INVALID_MISSING_INPUT, details); } const auto& tensorProto = it->second; InferenceEngine::Blob::Ptr blob; SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}] Deserializing input: {}", getName(), outputName); auto status = deserialize(tensorProto, blob, inputsInfo.at(outputName)); if (!status.ok()) { return status; } outputs[outputName] = blob; SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}]: blob with name: {} description: {} has been prepared", getName(), outputName, TensorInfo::tensorDescToString(blob->getTensorDesc())); } } return StatusCode::OK; } Status EntryNode::deserialize(const tensorflow::TensorProto& proto, InferenceEngine::Blob::Ptr& blob, const std::shared_ptr<TensorInfo>& tensorInfo) { if (proto.dtype() == tensorflow::DataType::DT_STRING) { SPDLOG_LOGGER_DEBUG(dag_executor_logger, "Request contains binary input: {}", tensorInfo->getName()); return deserializeBinaryInput(proto, blob, tensorInfo); } else { return deserializeNumericalInput(proto, blob); } } Status EntryNode::deserializeBinaryInput(const tensorflow::TensorProto& proto, InferenceEngine::Blob::Ptr& blob, const std::shared_ptr<TensorInfo>& tensorInfo) { return convertStringValToBlob(proto, blob, tensorInfo, true); } Status EntryNode::deserializeNumericalInput(const tensorflow::TensorProto& proto, InferenceEngine::Blob::Ptr& blob) { InferenceEngine::TensorDesc description; if (proto.tensor_content().size() == 0) { const std::string details = "Tensor content size can't be 0"; SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}] {}", getName(), details); return Status(StatusCode::INVALID_CONTENT_SIZE, details); } // Assuming content is in proto.tensor_content InferenceEngine::SizeVector shape; for (int i = 0; i < proto.tensor_shape().dim_size(); i++) { shape.emplace_back(proto.tensor_shape().dim(i).size()); } description.setDims(shape); size_t tensor_count = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>()); if (proto.tensor_content().size() != tensor_count * tensorflow::DataTypeSize(proto.dtype())) { std::stringstream ss; ss << "Expected: " << tensor_count * tensorflow::DataTypeSize(proto.dtype()) << "; Actual: " << proto.tensor_content().size(); const std::string details = ss.str(); SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node {}] Invalid size of tensor proto - {}", getName(), details); return Status(StatusCode::INVALID_CONTENT_SIZE, details); } // description.setLayout(); // Layout info is stored in model instance. If we find out it is required, then need to be set right before inference. try { switch (proto.dtype()) { case tensorflow::DataType::DT_FLOAT: description.setPrecision(InferenceEngine::Precision::FP32); blob = InferenceEngine::make_shared_blob<float>(description, (float*)proto.tensor_content().data()); break; case tensorflow::DataType::DT_INT32: description.setPrecision(InferenceEngine::Precision::I32); blob = InferenceEngine::make_shared_blob<int32_t>(description, (int32_t*)proto.tensor_content().data()); break; case tensorflow::DataType::DT_INT8: description.setPrecision(InferenceEngine::Precision::I8); blob = InferenceEngine::make_shared_blob<int8_t>(description, (int8_t*)proto.tensor_content().data()); break; case tensorflow::DataType::DT_UINT8: description.setPrecision(InferenceEngine::Precision::U8); blob = InferenceEngine::make_shared_blob<uint8_t>(description, (uint8_t*)proto.tensor_content().data()); break; case tensorflow::DataType::DT_INT16: description.setPrecision(InferenceEngine::Precision::I16); blob = InferenceEngine::make_shared_blob<int16_t>(description, (int16_t*)proto.tensor_content().data()); break; case tensorflow::DataType::DT_HALF: case tensorflow::DataType::DT_UINT16: case tensorflow::DataType::DT_INT64: default: { std::stringstream ss; ss << "Actual: " << TensorInfo::getDataTypeAsString(proto.dtype()); const std::string details = ss.str(); SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}] Unsupported deserialization precision - {}", getName(), details); return Status(StatusCode::OV_UNSUPPORTED_DESERIALIZATION_PRECISION, details); } } } catch (const InferenceEngine::Exception& e) { Status status = StatusCode::OV_INTERNAL_DESERIALIZATION_ERROR; SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}] Exception thrown during deserialization from make_shared_blob; {}; exception message: {}", getName(), status.string(), e.what()); return status; } catch (std::logic_error& e) { Status status = StatusCode::OV_INTERNAL_DESERIALIZATION_ERROR; SPDLOG_LOGGER_DEBUG(dag_executor_logger, "[Node: {}] Exception thrown during deserialization from make_shared_blob; {}; exception message: {}", getName(), status.string(), e.what()); return status; } return StatusCode::OK; } Status EntryNode::isInputBinary(const std::string& name, bool& isBinary) const { auto it = request->inputs().find(name); if (it == request->inputs().end()) { SPDLOG_LOGGER_ERROR(dag_executor_logger, "Error during checking binary input; input: {} does not exist", name); return StatusCode::INTERNAL_ERROR; } isBinary = it->second.string_val_size() > 0; return StatusCode::OK; } Status EntryNode::createShardedBlob(InferenceEngine::Blob::Ptr& dividedBlob, const InferenceEngine::TensorDesc& dividedBlobDesc, InferenceEngine::Blob::Ptr blob, size_t i, size_t step, const NodeSessionMetadata& metadata, const std::string blobName) { bool isBinary = false; auto status = this->isInputBinary(blobName, isBinary); if (!status.ok()) { return status; } if (isBinary) { return Node::createShardedBlob(dividedBlob, dividedBlobDesc, blob, i, step, metadata, blobName); } // if condition is perf optimization // when demultiplying from entry node from tensor content we can skip allocation for sharded blobs // and reuse memory from original blob since its memory is kept for whole duration of predict request if (dividedBlobDesc.getPrecision() == InferenceEngine::Precision::FP32) { dividedBlob = InferenceEngine::make_shared_blob<float>(dividedBlobDesc, (float*)blob->buffer() + i * step / sizeof(float)); } else if (dividedBlobDesc.getPrecision() == InferenceEngine::Precision::I32) { dividedBlob = InferenceEngine::make_shared_blob<int32_t>(dividedBlobDesc, (int32_t*)blob->buffer() + i * step / sizeof(int32_t)); } else if (dividedBlobDesc.getPrecision() == InferenceEngine::Precision::I8) { dividedBlob = InferenceEngine::make_shared_blob<int8_t>(dividedBlobDesc, (int8_t*)blob->buffer() + i * step / sizeof(int8_t)); } else if (dividedBlobDesc.getPrecision() == InferenceEngine::Precision::U8) { dividedBlob = InferenceEngine::make_shared_blob<uint8_t>(dividedBlobDesc, (uint8_t*)blob->buffer() + i * step / sizeof(uint8_t)); } else if (dividedBlobDesc.getPrecision() == InferenceEngine::Precision::I16) { dividedBlob = InferenceEngine::make_shared_blob<int16_t>(dividedBlobDesc, (int16_t*)blob->buffer() + i * step / sizeof(int16_t)); } else { return Node::createShardedBlob(dividedBlob, dividedBlobDesc, blob, i, step, metadata, blobName); } return StatusCode::OK; } } // namespace ovms
49.860987
251
0.673082
[ "shape", "model" ]
4aa8bdcb68eb70deb087fce86a3e8fbe3d6645d8
807
cpp
C++
ds-algo/sort/src/sort/BoubleSort.cpp
hebostary/Notes
32e0537ba6f2cb257cd2a202ba2504a7cf70a7ed
[ "Unlicense" ]
null
null
null
ds-algo/sort/src/sort/BoubleSort.cpp
hebostary/Notes
32e0537ba6f2cb257cd2a202ba2504a7cf70a7ed
[ "Unlicense" ]
null
null
null
ds-algo/sort/src/sort/BoubleSort.cpp
hebostary/Notes
32e0537ba6f2cb257cd2a202ba2504a7cf70a7ed
[ "Unlicense" ]
null
null
null
#include "Sort.hpp" #include "../common/common.hpp" int boublesort(vector<int> &nums) { cout<<"***********[Begin]Bouble sort**********"<<endl; printVec(nums); int size = nums.size(); if (size < 2) return 0; for (int i = size - 1; i >= 0; --i) { bool flag = false; for (int j = 0; j < i; ++j) { if (nums[j] > nums[j+1]) { swap(nums[j], nums[j+1]); flag = true; } } //没有数据交换,说明数据已经是有序的,提前退出 if (!flag) break; } printVec(nums); cout<<"***********[End]Bouble sort**********"<<endl; return 0; } void boublesortTest() { vector<int> vec = createRandomVec(RANDOM_VECTOR_SIZE, RANDOM_INT_MAX); recordRunTime(); boublesort(vec); recordRunTime(true); }
22.416667
74
0.48575
[ "vector" ]
4ab42822196b0bf9ea14bedc2fd4fcb47e2e4d8b
324
hpp
C++
src/Intersect.hpp
vadosnaprimer/desktop-m3g
fa04787e8609cd0f4e63defc7f2c669c8cc78d1f
[ "MIT" ]
2
2019-05-14T08:14:15.000Z
2021-01-19T13:28:38.000Z
src/Intersect.hpp
vadosnaprimer/desktop-m3g
fa04787e8609cd0f4e63defc7f2c669c8cc78d1f
[ "MIT" ]
null
null
null
src/Intersect.hpp
vadosnaprimer/desktop-m3g
fa04787e8609cd0f4e63defc7f2c669c8cc78d1f
[ "MIT" ]
null
null
null
#ifndef __M3G_INTERSECT_HPP__ #define __M3G_INTERSECT_HPP__ namespace m3g { class Vector; bool triangle_intersect (const Vector& org, const Vector& dir, const Vector& v0, const Vector& v1, const Vector& v2, float* u, float* v, float* d); } #endif
16.2
82
0.583333
[ "vector" ]
3862a772622b3250cc952e4d24af2f05effeb5e2
57,221
cxx
C++
ds/adsi/msext/cuar.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/msext/cuar.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/msext/cuar.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1995 // // File: cuar.cxx // // Contents: Account Restrictions Propset for the User object // // History: 11-1-95 krishnag Created. // // PROPERTY_RW(AccountDisabled, boolean, 1) I // PROPERTY_RW(AccountExpirationDate, DATE, 2) I // PROPERTY_RO(AccountCanExpire, boolean, 3) I // PROPERTY_RO(PasswordCanExpire, boolean, 4) I // PROPERTY_RW(GraceLoginsAllowed, long, 5) NI // PROPERTY_RW(GraceLoginsRemaining, long, 6) NI // PROPERTY_RW(IsAccountLocked, boolean, 7) I // PROPERTY_RW(IsAdmin, boolean, 8) I // PROPERTY_RW(LoginHours, VARIANT, 9) I // PROPERTY_RW(LoginWorkstations, VARIANT, 10) I // PROPERTY_RW(MaxLogins, long, 11) I // PROPERTY_RW(MaxStorage, long, 12) I // PROPERTY_RW(PasswordExpirationDate, DATE, 13) I // PROPERTY_RW(PasswordRequired, boolean, 14) I // PROPERTY_RW(RequireUniquePassword,boolean, 15) I // // //---------------------------------------------------------------------------- #include "ldap.hxx" #pragma hdrstop #include <lm.h> #include <winldap.h> #include "..\ldapc\ldpcache.hxx" #include "..\ldapc\ldaputil.hxx" #include "..\ldapc\parse.hxx" #include <dsgetdc.h> #include <sspi.h> HRESULT BuildLDAPPathFromADsPath2( LPWSTR szADsPathName, LPWSTR *pszLDAPServer, LPWSTR *pszLDAPDn, DWORD * pdwPort ); DWORD GetDefaultServer( DWORD dwPort, BOOL fVerify, LPWSTR szDomainDnsName, LPWSTR szServerName, BOOL fWriteable ); HRESULT GetDomainDNSNameFromHost( LPWSTR szHostName, SEC_WINNT_AUTH_IDENTITY& AuthI, CCredentials &Credentials, DWORD dwPort, LPWSTR * ppszHostName ); // // The list of server entries - detailing SSL support // PSERVSSLENTRY gpServerSSLList = NULL; // // Critical Section and support routines to protect list // CRITICAL_SECTION g_ServerListCritSect; // // Flag that indicates if kerberos is being used. // const unsigned long KERB_SUPPORT_FLAGS = ISC_RET_MUTUAL_AUTH ; // // Routines that support cacheing server SSL info for perf // #define STRING_LENGTH(p) ( p ? wcslen(p) : 0) // // Get the status of SSL support on the server pszServerName // 0 indicates that the server was not in our list. // DWORD ReadServerSupportsSSL( LPWSTR pszServerName) { ENTER_SERVERLIST_CRITICAL_SECTION(); PSERVSSLENTRY pServerList = gpServerSSLList; DWORD dwRetVal = 0; // // Keep going through the list until we hit the end or // we find an entry that matches. // while ((pServerList != NULL) && (dwRetVal == 0)) { #ifdef WIN95 if (!(_wcsicmp(pszServerName, pServerList->pszServerName))) { #else if (CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, pszServerName, -1, pServerList->pszServerName, -1 ) == CSTR_EQUAL ) { #endif dwRetVal = pServerList->dwFlags; } pServerList = pServerList->pNext; } LEAVE_SERVERLIST_CRITICAL_SECTION(); return dwRetVal; } HRESULT UpdateServerSSLSupportStatus( PWSTR pszServerName, DWORD dwFlags ) { HRESULT hr = S_OK; PSERVSSLENTRY pServEntry = NULL; ENTER_SERVERLIST_CRITICAL_SECTION() PSERVSSLENTRY pServerList = gpServerSSLList; DWORD dwRetVal = 0; ADsAssert(pszServerName && *pszServerName); // // Keep going through the list until we hit the end or // we find an entry that matches. // while ((pServerList != NULL) && (dwRetVal == 0)) { #ifdef WIN95 if (!(_wcsicmp(pszServerName, pServerList->pszServerName))) { #else if (CompareStringW( LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, pszServerName, -1, pServerList->pszServerName, -1 ) == CSTR_EQUAL ) { #endif pServerList->dwFlags = dwFlags; LEAVE_SERVERLIST_CRITICAL_SECTION() RRETURN(S_OK); } pServerList = pServerList->pNext; } pServEntry = (PSERVSSLENTRY) AllocADsMem(sizeof(SERVSSLENTRY)); if (!pServEntry) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } pServEntry->pszServerName = AllocADsStr(pszServerName); if (!pServEntry->pszServerName) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } pServEntry->dwFlags = dwFlags; pServEntry->pNext = gpServerSSLList; gpServerSSLList = pServEntry; error: if (FAILED(hr) && pServEntry) { // // Free only pServEntry as the string cannot have // a value in the error case // FreeADsMem(pServEntry); } LEAVE_SERVERLIST_CRITICAL_SECTION(); RRETURN(hr); } void FreeServerSSLSupportList() { PSERVSSLENTRY pList = gpServerSSLList; PSERVSSLENTRY pPrevEntry = NULL; while (pList) { pPrevEntry = pList; FreeADsStr(pList->pszServerName); pList = pList->pNext; FreeADsMem(pPrevEntry); } } #if (!defined(WIN95)) // // Take a AuthI struct and return a cred handle. // HRESULT ConvertAuthIdentityToCredHandle( SEC_WINNT_AUTH_IDENTITY& AuthI, OUT PCredHandle CredentialsHandle ) { SECURITY_STATUS secStatus = SEC_E_OK; TimeStamp Lifetime; secStatus = AcquireCredentialsHandleWrapper( NULL, // New principal MICROSOFT_KERBEROS_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &AuthI, NULL, NULL, CredentialsHandle, &Lifetime ); if (secStatus != SEC_E_OK) { RRETURN(E_FAIL); } else { RRETURN(S_OK); } } // // ***** Caller must free the strings put in the **** // ***** AuthIdentity struct later. **** // HRESULT GetAuthIdentityForCaller( CCredentials& Credentials, IADs * pIADs, OUT SEC_WINNT_AUTH_IDENTITY *pAuthI, BOOL fEnforceMutualAuth ) { HRESULT hr = S_OK; LPWSTR pszNTLMUser = NULL; LPWSTR pszNTLMDomain = NULL; LPWSTR pszDefaultServer = NULL; LPWSTR dn = NULL; LPWSTR passwd = NULL; IADsObjOptPrivate * pADsPrivObjectOptions = NULL; ULONG ulFlags = 0; if (fEnforceMutualAuth) { hr = pIADs->QueryInterface( IID_IADsObjOptPrivate, (void **)&pADsPrivObjectOptions ); BAIL_ON_FAILURE(hr); hr = pADsPrivObjectOptions->GetOption ( LDAP_MUTUAL_AUTH_STATUS, (void *) &ulFlags ); BAIL_ON_FAILURE(hr); if (!(ulFlags & KERB_SUPPORT_FLAGS)) { BAIL_ON_FAILURE(hr = E_FAIL); } } hr = Credentials.GetUserName(&dn); BAIL_ON_FAILURE(hr); hr = Credentials.GetPassword(&passwd); BAIL_ON_FAILURE(hr); // // Get the userName and password into the auth struct. // hr = LdapCrackUserDNtoNTLMUser2( dn, &pszNTLMUser, &pszNTLMDomain ); if (FAILED(hr)) { hr = LdapCrackUserDNtoNTLMUser( dn, &pszNTLMUser, &pszNTLMDomain ); BAIL_ON_FAILURE(hr); } // // If the domain name is NULL and enforceMutualAuth is false, // then we need to throw in the defaultDomainName. This will // be needed subsequently for the LogonUser call. // if (!fEnforceMutualAuth && !pszNTLMDomain) { // // Call GetDefaultServer. // pszDefaultServer = (LPWSTR) AllocADsMem(sizeof(WCHAR) * MAX_PATH); if (!pszDefaultServer) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } pszNTLMDomain = (LPWSTR) AllocADsMem(sizeof(WCHAR) * MAX_PATH); if (!pszNTLMDomain) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } hr = GetDefaultServer( -1, // this will use the default ldap port FALSE, pszNTLMDomain, pszDefaultServer, TRUE ); BAIL_ON_FAILURE(hr); } pAuthI->User = (PWCHAR)pszNTLMUser; pAuthI->UserLength = (pszNTLMUser == NULL)? 0: wcslen(pszNTLMUser); pAuthI->Domain = (PWCHAR)pszNTLMDomain; pAuthI->DomainLength = (pszNTLMDomain == NULL)? 0: wcslen(pszNTLMDomain); pAuthI->Password = (PWCHAR)passwd; pAuthI->PasswordLength = (passwd == NULL)? 0: wcslen(passwd); pAuthI->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; error: if (FAILED(hr)) { // // Free the strings // if (pszNTLMUser) { FreeADsStr(pszNTLMUser); } if (pszNTLMDomain) { FreeADsStr(pszNTLMDomain); } if (passwd) { SecureZeroMemory(passwd, wcslen(passwd)*sizeof(WCHAR)); FreeADsStr(passwd); } } if (pADsPrivObjectOptions) { pADsPrivObjectOptions->Release(); } // // Always free the dn // if (dn) { FreeADsStr(dn); } if (pszDefaultServer) { FreeADsMem(pszDefaultServer); } RRETURN(hr); } #endif // Class CLDAPUser STDMETHODIMP CLDAPUser::get_AccountDisabled(THIS_ VARIANT_BOOL FAR* retval) { if ( retval == NULL ) RRETURN( E_ADS_BAD_PARAMETER ); LONG lUserAcctControl; HRESULT hr = get_LONG_Property( (IADsUser *)this, TEXT("userAccountControl"), &lUserAcctControl ); if ( SUCCEEDED(hr)) *retval = lUserAcctControl & UF_ACCOUNTDISABLE ? VARIANT_TRUE : VARIANT_FALSE; RRETURN(hr); } STDMETHODIMP CLDAPUser::put_AccountDisabled(THIS_ VARIANT_BOOL fAccountDisabled) { LONG lUserAcctControl; IADsObjOptPrivate * pADsPrivObjectOptions = NULL; BOOL fSet = FALSE; HRESULT hr = get_LONG_Property( (IADsUser *)this, TEXT("userAccountControl"), &lUserAcctControl ); if ( SUCCEEDED(hr)) { if ( fAccountDisabled ) lUserAcctControl |= UF_ACCOUNTDISABLE; else lUserAcctControl &= ~UF_ACCOUNTDISABLE; hr = _pADs->QueryInterface( IID_IADsObjOptPrivate, (void **)&pADsPrivObjectOptions ); if(SUCCEEDED(hr)) { hr = pADsPrivObjectOptions->GetOption ( LDAP_USERACCOUNTCONTROL, (void*)&fSet ); } if(!fSet) { lUserAcctControl |= UF_LOCKOUT; } hr = put_LONG_Property( (IADsUser *)this, TEXT("userAccountControl"), lUserAcctControl ); } if(pADsPrivObjectOptions) pADsPrivObjectOptions->Release(); RRETURN(hr); } STDMETHODIMP CLDAPUser::get_AccountExpirationDate(THIS_ DATE FAR* retval) { GET_PROPERTY_FILETIME((IADsUser *)this, AccountExpirationDate); } STDMETHODIMP CLDAPUser::put_AccountExpirationDate(THIS_ DATE daAccountExpirationDate) { PUT_PROPERTY_FILETIME((IADsUser *)this, AccountExpirationDate); } STDMETHODIMP CLDAPUser::get_GraceLoginsAllowed(THIS_ long FAR* retval) { RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CLDAPUser::put_GraceLoginsAllowed(THIS_ long lGraceLoginsAllowed) { RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CLDAPUser::get_GraceLoginsRemaining(THIS_ long FAR* retval) { RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CLDAPUser::put_GraceLoginsRemaining(THIS_ long lGraceLoginsRemaining) { RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CLDAPUser::get_IsAccountLocked(THIS_ VARIANT_BOOL FAR* retval) { HRESULT hr = S_OK; VARIANT var; IADsLargeInteger *pLargeInt = NULL; LONG LowPart, HighPart; if ( retval == NULL ) RRETURN( E_ADS_BAD_PARAMETER ); VariantInit(&var); hr = _pADs->Get(TEXT("lockoutTime"), &var); if (SUCCEEDED(hr)) { // // There's a lockoutTime, we need to determine // if it equals 0 (== not locked-out). // ADsAssert(V_VT(&var) == VT_DISPATCH); if (V_VT(&var) != VT_DISPATCH) { BAIL_ON_FAILURE(hr = E_FAIL); } hr = V_DISPATCH(&var)->QueryInterface(IID_IADsLargeInteger, reinterpret_cast<void**>(&pLargeInt) ); BAIL_ON_FAILURE(hr); hr = pLargeInt->get_LowPart(&LowPart); BAIL_ON_FAILURE(hr); hr = pLargeInt->get_HighPart(&HighPart); BAIL_ON_FAILURE(hr); if ( (LowPart != 0) || (HighPart != 0) ) { *retval = VARIANT_TRUE; } else { *retval = VARIANT_FALSE; } } else if (hr == E_ADS_PROPERTY_NOT_FOUND) { // // If there's no lockoutTime, the account is not // locked-out. // *retval = VARIANT_FALSE; hr = S_OK; } else { BAIL_ON_FAILURE(hr); } error: if (pLargeInt) { pLargeInt->Release(); } VariantClear(&var); RRETURN(hr); } STDMETHODIMP CLDAPUser::put_IsAccountLocked(THIS_ VARIANT_BOOL fIsAccountLocked) { HRESULT hr = S_OK; if (fIsAccountLocked) { // // You cannot set an account to a locked state. // RRETURN(E_ADS_BAD_PARAMETER); } hr = put_LONG_Property( (IADsUser *)this, TEXT("lockoutTime"), 0 ); RRETURN(hr); } STDMETHODIMP CLDAPUser::get_LoginHours(THIS_ VARIANT FAR* retval) { GET_PROPERTY_VARIANT((IADsUser *)this, LoginHours); } STDMETHODIMP CLDAPUser::put_LoginHours(THIS_ VARIANT vLoginHours) { PUT_PROPERTY_VARIANT((IADsUser *)this, LoginHours); } STDMETHODIMP CLDAPUser::get_LoginWorkstations(THIS_ VARIANT FAR* retval) { GET_PROPERTY_BSTRARRAY((IADsUser *)this,LoginWorkstations); } STDMETHODIMP CLDAPUser::put_LoginWorkstations(THIS_ VARIANT vLoginWorkstations) { PUT_PROPERTY_BSTRARRAY((IADsUser *)this,LoginWorkstations); } STDMETHODIMP CLDAPUser::get_MaxLogins(THIS_ long FAR* retval) { RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CLDAPUser::put_MaxLogins(THIS_ long lMaxLogins) { RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CLDAPUser::get_MaxStorage(THIS_ long FAR* retval) { GET_PROPERTY_LONG((IADsUser *)this, MaxStorage); } STDMETHODIMP CLDAPUser::put_MaxStorage(THIS_ long lMaxStorage) { PUT_PROPERTY_LONG((IADsUser *)this, MaxStorage); } STDMETHODIMP CLDAPUser::get_PasswordExpirationDate(THIS_ DATE FAR* retval) { GET_PROPERTY_DATE((IADsUser *)this, PasswordExpirationDate); } STDMETHODIMP CLDAPUser::put_PasswordExpirationDate(THIS_ DATE daPasswordExpirationDate) { PUT_PROPERTY_DATE((IADsUser *)this, PasswordExpirationDate); } STDMETHODIMP CLDAPUser::get_PasswordRequired(THIS_ VARIANT_BOOL FAR* retval) { if ( retval == NULL ) RRETURN( E_ADS_BAD_PARAMETER ); LONG lUserAcctControl; HRESULT hr = get_LONG_Property( (IADsUser *)this, TEXT("userAccountControl"), &lUserAcctControl ); if ( SUCCEEDED(hr)) *retval = lUserAcctControl & UF_PASSWD_NOTREQD ? VARIANT_FALSE: VARIANT_TRUE; RRETURN(hr); } STDMETHODIMP CLDAPUser::put_PasswordRequired(THIS_ VARIANT_BOOL fPasswordRequired) { LONG lUserAcctControl; IADsObjOptPrivate * pADsPrivObjectOptions = NULL; BOOL fSet = FALSE; HRESULT hr = get_LONG_Property( (IADsUser *)this, TEXT("userAccountControl"), &lUserAcctControl ); if ( SUCCEEDED(hr)) { if ( fPasswordRequired ) lUserAcctControl &= ~UF_PASSWD_NOTREQD; else lUserAcctControl |= UF_PASSWD_NOTREQD; hr = _pADs->QueryInterface( IID_IADsObjOptPrivate, (void **)&pADsPrivObjectOptions ); if(SUCCEEDED(hr)) { hr = pADsPrivObjectOptions->GetOption ( LDAP_USERACCOUNTCONTROL, (void*)&fSet ); } if(!fSet) { lUserAcctControl |= UF_LOCKOUT; } hr = put_LONG_Property( (IADsUser *)this, TEXT("userAccountControl"), lUserAcctControl ); } if(pADsPrivObjectOptions) pADsPrivObjectOptions->Release(); RRETURN(hr); } STDMETHODIMP CLDAPUser::get_PasswordMinimumLength(THIS_ LONG FAR* retval) { GET_PROPERTY_LONG((IADsUser *)this, PasswordMinimumLength); } STDMETHODIMP CLDAPUser::put_PasswordMinimumLength(THIS_ LONG lPasswordMinimumLength) { PUT_PROPERTY_LONG((IADsUser *)this, PasswordMinimumLength); } STDMETHODIMP CLDAPUser::get_RequireUniquePassword(THIS_ VARIANT_BOOL FAR* retval) { GET_PROPERTY_VARIANT_BOOL((IADsUser *)this, RequireUniquePassword); } STDMETHODIMP CLDAPUser::put_RequireUniquePassword(THIS_ VARIANT_BOOL fRequireUniquePassword) { PUT_PROPERTY_VARIANT_BOOL((IADsUser *)this, RequireUniquePassword); } BOOLEAN _cdecl ServerCertCallback( PLDAP Connection, PCCERT_CONTEXT pServerCert ) { // // After the secure connection is established, this function is called by // LDAP. This gives the client an opportunity to verify the server cert. // If, for some reason, the client doesn't approve it, it should return FALSE // and the connection will be terminated. Else, return TRUE // fprintf( stderr, "Server cert callback has been called...\n" ); // // Use some way to verify the server certificate. // return TRUE; } STDMETHODIMP CLDAPUser::SetPassword(THIS_ BSTR bstrNewPassword) { HRESULT hr = E_FAIL; BOOLEAN bUseLDAP = FALSE; LPWSTR pszServer = NULL; LPWSTR pszHostName = NULL; DWORD dwLen = 0; int err = 0; BSTR bstrADsPath = NULL; LPWSTR szServerSSL = NULL; LPWSTR szDn = NULL; DWORD dwPortSSL = 0; PADSLDP pAdsLdpSSL = NULL; IADsObjOptPrivate * pADsPrivObjectOptions = NULL; PADSLDP pAdsLdp = NULL; LDAPMessage *pMsgResult = NULL; LDAPMessage *pMsgEntry = NULL; LDAP *pLdapCurrent = NULL; LPWSTR Attributes[] = {L"objectClass", NULL}; VARIANT varSamAccount; DWORD dwServerPwdSupport = SERVER_STATUS_UNKNOWN; LPWSTR pszHostDomainName = NULL; SEC_WINNT_AUTH_IDENTITY AuthI; BOOLEAN fPasswordSet = FALSE; LPWSTR pszTempPwd = NULL; ULONG ulFlags = 0; VARIANT varGetInfoEx; BOOL fCachePrimed = FALSE; BOOL fImpersonating = FALSE; HANDLE hUserToken = INVALID_HANDLE_VALUE; IADsObjectOptions* pADsOpt = NULL; DWORD dwPasswordPort; DWORD dwPasswordMethod; VARIANT var; CCredentials cTempCred = _Credentials; // // Init params we will need to free later. // AuthI.User = NULL; AuthI.Domain = NULL; AuthI.Password = NULL; VariantInit(&varSamAccount); VariantInit(&varGetInfoEx); VariantInit(&var); // // Get the Ldap path of the user object // hr = _pADs->get_ADsPath( &bstrADsPath ); BAIL_ON_FAILURE(hr); hr = BuildLDAPPathFromADsPath2( bstrADsPath, &szServerSSL, &szDn, &dwPortSSL ); BAIL_ON_FAILURE(hr); // // Now do an LDAP Search with Referrals and get the handle to success // connection. This is where we can find the server the referred object // resides on // hr = _pADs->QueryInterface( IID_IADsObjOptPrivate, (void **)&pADsPrivObjectOptions ); BAIL_ON_FAILURE(hr); hr = pADsPrivObjectOptions->GetOption ( LDAP_SERVER, (void*)&pszHostName ); BAIL_ON_FAILURE(hr); // // additional lengh 3 is for '\0' and "\\\\" // dwLen = STRING_LENGTH(pszHostName) + 3; pszServer = (LPWSTR) AllocADsMem( dwLen * sizeof(WCHAR) ); if (!pszServer) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } wcscpy(pszServer,L"\\\\"); wcscat(pszServer, pszHostName); // get the info of password port and password method (SSL or clear text) hr = _pADs->QueryInterface( IID_IADsObjectOptions, (void **)&pADsOpt ); BAIL_ON_FAILURE(hr); hr = pADsOpt->GetOption( ADS_OPTION_PASSWORD_PORTNUMBER, &var ); BAIL_ON_FAILURE(hr); dwPasswordPort = V_I4(&var); VariantClear(&var); hr = pADsOpt->GetOption( ADS_OPTION_PASSWORD_METHOD, &var ); BAIL_ON_FAILURE(hr); dwPasswordMethod = V_I4(&var); if(dwPasswordMethod == ADS_PASSWORD_ENCODE_REQUIRE_SSL) { dwServerPwdSupport = ReadServerSupportsSSL(pszHostName); if (dwServerPwdSupport == ( SERVER_STATUS_UNKNOWN | SERVER_DOES_NOT_SUPPORT_SSL | SERVER_DOES_NOT_SUPPORT_NETUSER | SERVER_DOES_NOT_SUPPORT_KERBEROS ) ) { // // All flags are set, we will reset and rebuild cache // UpdateServerSSLSupportStatus( pszHostName, SERVER_STATUS_UNKNOWN ); dwServerPwdSupport = SERVER_STATUS_UNKNOWN; } if (dwServerPwdSupport == SERVER_STATUS_UNKNOWN || !(dwServerPwdSupport & SERVER_DOES_NOT_SUPPORT_SSL)) { // // Try to establish SSL connection for this Password Operation // // if NULL credential is passed in and auth flag does not contain secure auth, we need to make sure we keep // the default behavior: first try secure auth over SSL, then do anonymous bind over SSL if(cTempCred.IsNullCredentials() && !(cTempCred.GetAuthFlags() & ADS_SECURE_AUTHENTICATION)) { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() | ADS_USE_SSL | ADS_SECURE_AUTHENTICATION); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); // check ERROR_LOGON_FAILURE to be consistent witht the behavior of LdapOpenBindWithDefaultCredentials when // credential is null and auth flag is 0 if (FAILED(hr) && hr != ERROR_LOGON_FAILURE) { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() & ~ADS_SECURE_AUTHENTICATION); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); } } else { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() | ADS_USE_SSL); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); } if (SUCCEEDED(hr)) { int retval; SecPkgContext_ConnectionInfo sslattr; retval = ldap_get_option( pAdsLdpSSL->LdapHandle, LDAP_OPT_SSL_INFO, &sslattr ); if (retval == LDAP_SUCCESS) { // // If Channel is secure enough, enable LDAP Password Change // if (sslattr.dwCipherStrength >= 128) { bUseLDAP = TRUE; } } } // // Update the SSL support if appropriate // if (dwServerPwdSupport == SERVER_STATUS_UNKNOWN || !bUseLDAP) { // // Set the server does not support ssl bit if necessary // UpdateServerSSLSupportStatus( pszHostName, bUseLDAP ? dwServerPwdSupport : dwServerPwdSupport |= SERVER_DOES_NOT_SUPPORT_SSL ); } } } else { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() & ~ADS_USE_SSL); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); if(SUCCEEDED(hr)) bUseLDAP = TRUE; } if (bUseLDAP) { // // LDAP Password Set // PLDAPModW prgMod[2]; LDAPModW ModReplace; struct berval* rgBerVal[2]; struct berval BerVal; int ipwdLen; prgMod[0] = &ModReplace; prgMod[1] = NULL; ModReplace.mod_op = LDAP_MOD_REPLACE | LDAP_MOD_BVALUES; ModReplace.mod_type = L"unicodePwd"; ModReplace.mod_bvalues = rgBerVal; rgBerVal[0] = &BerVal; rgBerVal[1] = NULL; // // 2 extra for "" to put the password in. // if (bstrNewPassword) { ipwdLen = (wcslen(bstrNewPassword) + 2) * sizeof(WCHAR); } else { ipwdLen = 2 * sizeof(WCHAR); } // // Add 1 for the \0. // pszTempPwd = (LPWSTR) AllocADsMem(ipwdLen + sizeof(WCHAR)); if (!pszTempPwd) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } wcscpy(pszTempPwd, L"\""); if (bstrNewPassword) { wcscat(pszTempPwd, bstrNewPassword); } wcscat(pszTempPwd, L"\""); BerVal.bv_len = ipwdLen; BerVal.bv_val = (char*)pszTempPwd; hr = LdapModifyS( pAdsLdpSSL, szDn, prgMod ); BAIL_ON_FAILURE(hr); // // Set flag so that we do not try any other methods. // fPasswordSet = TRUE; } // // Try kerberos setpassword if applicable // #if (!defined(WIN95)) // // Only valid on Win2k // if (!fPasswordSet) { // // If we cached the server as not supporting Kerberos, most likely it // was because we were not mutually authenticated. Do a quick check to // see if that has changed, so that we can update our cached information // if necessary. // if (dwServerPwdSupport & SERVER_DOES_NOT_SUPPORT_KERBEROS) { hr = pADsPrivObjectOptions->GetOption ( LDAP_MUTUAL_AUTH_STATUS, (void *) &ulFlags ); BAIL_ON_FAILURE(hr); if ((ulFlags & KERB_SUPPORT_FLAGS)) { UpdateServerSSLSupportStatus( pszHostName, dwServerPwdSupport &= (~SERVER_DOES_NOT_SUPPORT_KERBEROS) ); } } if (!(dwServerPwdSupport & SERVER_DOES_NOT_SUPPORT_KERBEROS)) { // // Kerberos set password // CredHandle secCredHandle = {0}; SECURITY_STATUS SecStatus; DWORD dwStatus = 0; LPWSTR pszSamAccountArr[] = {L"sAMAccountName"}; if (!fCachePrimed) { hr = ADsBuildVarArrayStr( pszSamAccountArr, 1, &varGetInfoEx ); BAIL_ON_FAILURE(hr); hr = _pADs->GetInfoEx(varGetInfoEx, 0); BAIL_ON_FAILURE(hr); fCachePrimed = TRUE; } hr = _pADs->Get(L"sAMAccountName", &varSamAccount); BAIL_ON_FAILURE(hr); // // The AuthIdentity structure is ueful down the road. // This routine will fail if we were not bound using // kerberos to the server. // hr = GetAuthIdentityForCaller( _Credentials, _pADs, &AuthI, TRUE // enforce mutual auth. ); if (FAILED(hr)) { UpdateServerSSLSupportStatus( pszHostName, dwServerPwdSupport |= SERVER_DOES_NOT_SUPPORT_KERBEROS ); } else { // // Kerb really needs this handle. // hr = ConvertAuthIdentityToCredHandle( AuthI, &secCredHandle ); if (FAILED(hr)) { UpdateServerSSLSupportStatus( pszHostName, dwServerPwdSupport |= SERVER_DOES_NOT_SUPPORT_KERBEROS ); } if (SUCCEEDED(hr)) { // // Get the domain dns name for the user // hr = GetDomainDNSNameFromHost( pszHostName, AuthI, _Credentials, dwPortSSL, &pszHostDomainName ); if (SUCCEEDED(hr)) { dwStatus = KerbSetPasswordUserEx( pszHostDomainName, V_BSTR(&varSamAccount), bstrNewPassword, &secCredHandle, pszHostName ); if (dwStatus) { // // We should have got this to come in here. // hr = HRESULT_FROM_WIN32(ERROR_LOGON_FAILURE); } else { fPasswordSet = TRUE; } } // if domain dns name get succeeded. FreeCredentialsHandleWrapper(&secCredHandle); } // if GetCredentialsForCaller succeeded. } // if we could get authidentity succesfully } // if server supports kerberos } // if password not set. #endif // // At this point server status cannot be unknown, it // will atleast have info about ssl support. // if (!fPasswordSet) { if (!(dwServerPwdSupport & SERVER_DOES_NOT_SUPPORT_NETUSER)) { // // Password Set using NET APIs // NET_API_STATUS nasStatus; DWORD dwParmErr = 0; LPWSTR pszSamAccountArr[] = {L"sAMAccountName"}; // // Get SamAccountName // VariantClear(&varSamAccount); VariantClear(&varGetInfoEx); if (!fCachePrimed) { hr = ADsBuildVarArrayStr( pszSamAccountArr, 1, &varGetInfoEx ); BAIL_ON_FAILURE(hr); hr = _pADs->GetInfoEx(varGetInfoEx, 0); BAIL_ON_FAILURE(hr); fCachePrimed = TRUE; } hr = _pADs->Get(L"sAMAccountName", &varSamAccount); BAIL_ON_FAILURE(hr); // // Set the password // USER_INFO_1003 lpUserInfo1003 ; lpUserInfo1003.usri1003_password = bstrNewPassword; #ifndef Win95 // // At this point if the user credentials are non NULL, // we want to impersonate the user and then make this call. // This will make sure the NetUserSetInfo call is made in the // correct context. // if (!_Credentials.IsNullCredentials()) { // // Need to get the userName and password in the format // usable by the logonUser call. // if ((AuthI.User == NULL) && (AuthI.Domain == NULL) && (AuthI.Password == NULL) ) { // // Get teh Auth identity struct populate if necessary. // hr = GetAuthIdentityForCaller( _Credentials, _pADs, &AuthI, FALSE ); } BAIL_ON_FAILURE(hr); // // Note that if this code is backported, then we might // need to change LOGON32_PROVIDER_WINNT50 to // LOGON32_PROVIDER_DEFAULT as NT4 and below will support // only that option. Also note that Win2k and below, do not // allow all accounts to impersonate. // if (LogonUser( AuthI.User, AuthI.Domain, AuthI.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, &hUserToken ) ) { // // Call succeeded so we should use this context. // if (ImpersonateLoggedOnUser(hUserToken)) { fImpersonating = TRUE; } } if (!fImpersonating) { hr = HRESULT_FROM_WIN32(GetLastError()); } BAIL_ON_FAILURE(hr); } // if credentials are valid. #endif nasStatus = NetUserSetInfo( pszServer, V_BSTR(&varSamAccount), 1003, (LPBYTE)&lpUserInfo1003, &dwParmErr ); #ifndef Win95 if (fImpersonating) { if (RevertToSelf()) { fImpersonating = FALSE; } else { ADsAssert(!"Revert to self failed."); BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(GetLastError())); } } #endif if ( nasStatus == NERR_UserNotFound ) { // User not created yet hr = E_ADS_OBJECT_UNBOUND; BAIL_ON_FAILURE(hr); } hr = HRESULT_FROM_WIN32(nasStatus); if (FAILED(hr) && (nasStatus == ERROR_LOGON_FAILURE)) { // // Was failure and ERROR_LOGON_FAILURE // UpdateServerSSLSupportStatus( pszHostName, dwServerPwdSupport |= SERVER_DOES_NOT_SUPPORT_NETUSER ); // // Need to free the variant as we will re-read in kerb // VariantClear(&varSamAccount); } else { // // password set succeed // fPasswordSet = TRUE; } } } // if Password not set. error: if (bstrADsPath) { ADsFreeString(bstrADsPath); } if (szServerSSL) { FreeADsStr(szServerSSL); } if (szDn) { FreeADsStr(szDn); } if (pAdsLdpSSL) { LdapCloseObject(pAdsLdpSSL); } if (pADsPrivObjectOptions) { pADsPrivObjectOptions->Release(); } if (pADsOpt) { pADsOpt->Release(); } if (pMsgResult) { LdapMsgFree(pMsgResult); } if (pszHostDomainName) { FreeADsStr(pszHostDomainName); } if (AuthI.User) { FreeADsStr(AuthI.User); } if (AuthI.Domain) { FreeADsStr(AuthI.Domain); } if (AuthI.Password) { SecureZeroMemory(AuthI.Password, AuthI.PasswordLength*sizeof(WCHAR)); FreeADsStr(AuthI.Password); } if (pszTempPwd) { SecureZeroMemory(pszTempPwd, wcslen(pszTempPwd)*sizeof(WCHAR)); FreeADsMem(pszTempPwd); } if (pszHostName) { FreeADsStr(pszHostName); } if (pszServer) { FreeADsMem(pszServer); } #ifndef Win95 if (fImpersonating) { // // Try and call revert to self again // RevertToSelf(); } #endif if (hUserToken != INVALID_HANDLE_VALUE ) { CloseHandle(hUserToken); hUserToken = NULL; } VariantClear(&varSamAccount); VariantClear(&varGetInfoEx); VariantClear(&var); RRETURN(hr); } STDMETHODIMP CLDAPUser::ChangePassword(THIS_ BSTR bstrOldPassword, BSTR bstrNewPassword) { HRESULT hr = S_OK; BOOLEAN bUseLDAP = FALSE; LPWSTR pszServer = NULL; LPWSTR pszHostName = NULL; DWORD dwLen = 0; int err = 0; BSTR bstrADsPath = NULL; LPWSTR szServerSSL = NULL; LPWSTR szDn = NULL; DWORD dwPortSSL = 0; PADSLDP pAdsLdpSSL = NULL; IADsObjOptPrivate * pADsPrivObjectOptions = NULL; PADSLDP pAdsLdp = NULL; LDAPMessage *pMsgResult = NULL; LDAPMessage *pMsgEntry = NULL; LDAP *pLdapCurrent = NULL; LPWSTR Attributes[] = {L"objectClass", NULL}; VARIANT varSamAccount; DWORD dwServerSSLSupport = 0; LPWSTR pszNewPassword = NULL; LPWSTR pszOldPassword = NULL; VARIANT varGetInfoEx; SEC_WINNT_AUTH_IDENTITY AuthI; BOOL fImpersonating = FALSE; HANDLE hUserToken = INVALID_HANDLE_VALUE; IADsObjectOptions* pADsOpt = NULL; DWORD dwPasswordPort; DWORD dwPasswordMethod; VARIANT var; CCredentials cTempCred = _Credentials; VariantInit(&varSamAccount); VariantInit(&varGetInfoEx); VariantInit(&var); memset(&AuthI, 0, sizeof(SEC_WINNT_AUTH_IDENTITY)); // // Get the Ldap path of the user object // hr = _pADs->get_ADsPath( &bstrADsPath ); BAIL_ON_FAILURE(hr); hr = BuildLDAPPathFromADsPath2( bstrADsPath, &szServerSSL, &szDn, &dwPortSSL ); BAIL_ON_FAILURE(hr); // // Now do an LDAP Search with Referrals and get the handle to success // connection. This is where we can find the server the referred object // resides on // hr = _pADs->QueryInterface( IID_IADsObjOptPrivate, (void **)&pADsPrivObjectOptions ); BAIL_ON_FAILURE(hr); hr = pADsPrivObjectOptions->GetOption ( LDAP_SERVER, (void *)&pszHostName ); BAIL_ON_FAILURE(hr); // // additional length 3 is for '\0' and "\\\\" // dwLen = STRING_LENGTH(pszHostName) + 3; pszServer = (LPWSTR) AllocADsMem( dwLen * sizeof(WCHAR) ); if (!pszServer) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } wcscpy(pszServer,L"\\\\"); wcscat(pszServer, pszHostName); // get the info of password port and password method (SSL or clear text) hr = _pADs->QueryInterface( IID_IADsObjectOptions, (void **)&pADsOpt ); BAIL_ON_FAILURE(hr); hr = pADsOpt->GetOption( ADS_OPTION_PASSWORD_PORTNUMBER, &var ); BAIL_ON_FAILURE(hr); dwPasswordPort = V_I4(&var); VariantClear(&var); hr = pADsOpt->GetOption( ADS_OPTION_PASSWORD_METHOD, &var ); BAIL_ON_FAILURE(hr); dwPasswordMethod = V_I4(&var); if(dwPasswordMethod == ADS_PASSWORD_ENCODE_REQUIRE_SSL) { dwServerSSLSupport = ReadServerSupportsSSL(pszHostName); if (dwServerSSLSupport == SERVER_STATUS_UNKNOWN || !(dwServerSSLSupport & SERVER_DOES_NOT_SUPPORT_SSL)) { // // Try to establish SSL connection for this Password Operation // // if NULL credential is passed in and auth flag does not contain secure auth, we need to make sure we keep // the default behavior: first try secure auth over SSL, then do anonymous bind over SSL if(cTempCred.IsNullCredentials() && !(cTempCred.GetAuthFlags() & ADS_SECURE_AUTHENTICATION)) { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() | ADS_USE_SSL | ADS_SECURE_AUTHENTICATION); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); // check ERROR_LOGON_FAILURE to be consistent witht the behavior of LdapOpenBindWithDefaultCredentials when // credential is null and auth flag is 0 if (FAILED(hr) && hr != ERROR_LOGON_FAILURE) { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() & ~ADS_SECURE_AUTHENTICATION); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); } } else { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() | ADS_USE_SSL); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); } if (SUCCEEDED(hr)) { int retval; SecPkgContext_ConnectionInfo sslattr; retval = ldap_get_option( pAdsLdpSSL->LdapHandle, LDAP_OPT_SSL_INFO, &sslattr ); if (retval == LDAP_SUCCESS) { // // If Channel is secure enough, enable LDAP Password Change // if (sslattr.dwCipherStrength >= 128) { bUseLDAP = TRUE; } } } // // Update the SSL support if appropriate // if (dwServerSSLSupport == SERVER_STATUS_UNKNOWN || !bUseLDAP) { UpdateServerSSLSupportStatus( pszHostName, bUseLDAP ? dwServerSSLSupport : dwServerSSLSupport |= SERVER_DOES_NOT_SUPPORT_SSL ); } } } else { cTempCred.SetAuthFlags(cTempCred.GetAuthFlags() & ~ADS_USE_SSL); hr = LdapOpenObject( pszHostName, szDn, &pAdsLdpSSL, cTempCred, dwPasswordPort ); if(SUCCEEDED(hr)) bUseLDAP = TRUE; } if (bUseLDAP) { // // LDAP Password Set // PLDAPModW prgMod[3]; LDAPModW ModDelete; LDAPModW ModAdd; int iOldPwdLen, iNewPwdLen; struct berval* rgBerVal[2]; struct berval* rgBerVal2[2]; struct berval BerVal; struct berval BerVal2; prgMod[0] = &ModDelete; prgMod[1] = &ModAdd; prgMod[2] = NULL; ModDelete.mod_op = LDAP_MOD_DELETE | LDAP_MOD_BVALUES; ModDelete.mod_type = L"unicodePwd"; ModDelete.mod_bvalues = rgBerVal; rgBerVal[0] = &BerVal; rgBerVal[1] = NULL; // // Put old pwd in quotes. // if (bstrOldPassword) { iOldPwdLen = (wcslen(bstrOldPassword) + 2) * sizeof(WCHAR); } else { iOldPwdLen = 2 * sizeof(WCHAR); } pszOldPassword = (LPWSTR) AllocADsMem((iOldPwdLen+1) * sizeof(WCHAR)); if (!pszOldPassword) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } wcscpy(pszOldPassword, L"\""); if (bstrOldPassword) { wcscat(pszOldPassword, bstrOldPassword); } wcscat(pszOldPassword, L"\""); BerVal.bv_len = iOldPwdLen; BerVal.bv_val = (char*)pszOldPassword; ModAdd.mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES; ModAdd.mod_type = L"unicodePwd"; ModAdd.mod_bvalues = rgBerVal2; rgBerVal2[0] = &BerVal2; rgBerVal2[1] = NULL; // // Put new password in "" // if (bstrNewPassword) { iNewPwdLen = (wcslen(bstrNewPassword) + 2) * sizeof(WCHAR); } else { iNewPwdLen = 2 * sizeof(WCHAR); } pszNewPassword = (LPWSTR) AllocADsMem(iNewPwdLen + sizeof(WCHAR)); if (!pszNewPassword) { BAIL_ON_FAILURE(hr = E_FAIL); } wcscpy(pszNewPassword, L"\""); if (bstrNewPassword) { wcscat(pszNewPassword, bstrNewPassword); } wcscat(pszNewPassword, L"\""); BerVal2.bv_len = iNewPwdLen; BerVal2.bv_val = (char*)pszNewPassword; hr = LdapModifyS( pAdsLdpSSL, szDn, prgMod ); BAIL_ON_FAILURE(hr); } else { // // Password Set using NET APIs // NET_API_STATUS nasStatus; DWORD dwParmErr = 0; LPWSTR pszSamAccountArr[] = {L"sAMAccountName"}; // // Get SamAccountName // hr = ADsBuildVarArrayStr( pszSamAccountArr, 1, &varGetInfoEx ); BAIL_ON_FAILURE(hr); hr = _pADs->GetInfoEx(varGetInfoEx, 0); BAIL_ON_FAILURE(hr); hr = _pADs->Get(L"sAMAccountName", &varSamAccount); BAIL_ON_FAILURE(hr); #ifndef Win95 // // At this point if the user credentials are non NULL, // we want to impersonate the user and then make this call. // This will make sure the NetUserChangePassword call is made in the // correct context. // if (!_Credentials.IsNullCredentials()) { // // Need to get the userName and password in the format // usable by the logonUser call. // hr = GetAuthIdentityForCaller( _Credentials, _pADs, &AuthI, FALSE ); if SUCCEEDED(hr) { // // Note that if this code is backported, then we might // need to change LOGON32_PROVIDER_WINNT50 to // LOGON32_PROVIDER_DEFAULT as NT4 and below will support // only that option. Also note that Win2k and below, do not // allow all accounts to impersonate. // if (LogonUser( AuthI.User, AuthI.Domain, AuthI.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hUserToken ) ) { // // Call succeeded so we should use this context. // if (ImpersonateLoggedOnUser(hUserToken)) { fImpersonating = TRUE; } } } // if we could successfully get the auth ident structure. // // We will continue to make the ChangePassword call even if // we could not impersonate successfully. // } // if credentials are valid. #endif // // Do the actual change password // nasStatus = NetUserChangePassword( pszServer, V_BSTR(&varSamAccount), bstrOldPassword, bstrNewPassword ); #ifndef Win95 if (fImpersonating) { if (RevertToSelf()) { fImpersonating = FALSE; } else { ADsAssert(!"Revert to self failed."); BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(GetLastError())); } } #endif if ( nasStatus == NERR_UserNotFound ) // User not created yet { hr = E_ADS_OBJECT_UNBOUND; BAIL_ON_FAILURE(hr); } hr = HRESULT_FROM_WIN32(nasStatus); BAIL_ON_FAILURE(hr); } error: if (bstrADsPath) { ADsFreeString(bstrADsPath); } if (szServerSSL) { FreeADsStr(szServerSSL); } if (szDn) { FreeADsStr(szDn); } if (pAdsLdpSSL) { LdapCloseObject(pAdsLdpSSL); } if (pADsPrivObjectOptions) { pADsPrivObjectOptions->Release(); } if (pADsOpt) { pADsOpt->Release(); } if (pMsgResult) { LdapMsgFree(pMsgResult); } if (pszOldPassword) { SecureZeroMemory(pszOldPassword, wcslen(pszOldPassword)*sizeof(WCHAR)); FreeADsMem(pszOldPassword); } if (pszNewPassword) { SecureZeroMemory(pszNewPassword, wcslen(pszNewPassword)*sizeof(WCHAR)); FreeADsMem(pszNewPassword); } if (AuthI.User) { FreeADsStr(AuthI.User); } if (AuthI.Domain) { FreeADsStr(AuthI.Domain); } if (AuthI.Password) { SecureZeroMemory(AuthI.Password, AuthI.PasswordLength*sizeof(WCHAR)); FreeADsStr(AuthI.Password); } if (pszHostName) { FreeADsStr(pszHostName); } if (pszServer) { FreeADsMem(pszServer); } #ifndef Win95 if (fImpersonating) { // // Try and call revert to self again // RevertToSelf(); } #endif if (hUserToken != INVALID_HANDLE_VALUE ) { CloseHandle(hUserToken); hUserToken = NULL; } VariantClear(&varSamAccount); VariantClear(&varGetInfoEx); VariantClear(&var); RRETURN(hr); } //+--------------------------------------------------------------------------- // // GetDomainDNSNameFromHost // // Given the domain dns name for a host, we need to get hold of the // dns name for the domain. // // Arguments: // [szHostName] - name of server. // [Credentials] - Credentials to use for bind. // [dwPort] - Port to connect to server on. // [ppszHostName] - ptr to string for retval. // // Returns: // S_OK - If operation succeeds. // E_* - For other cases. // //---------------------------------------------------------------------------- HRESULT GetDomainDNSNameFromHost( LPWSTR szHostName, SEC_WINNT_AUTH_IDENTITY& AuthI, CCredentials& Credentials, DWORD dwPort, LPWSTR * ppszHostName ) { HRESULT hr = S_OK; PADSLDP ld = NULL; LPTSTR *aValuesNamingContext = NULL; IADsNameTranslate *pNameTranslate = NULL; BSTR bstrName = NULL; int nCount = 0; // // Bind to the ROOTDSE of the server. // hr = LdapOpenObject( szHostName, NULL, // the DN. &ld, Credentials, dwPort ); BAIL_ON_FAILURE(hr); // // Now get the defaultNamingContext // hr = LdapReadAttributeFast( ld, NULL, // the DN. LDAP_OPATT_DEFAULT_NAMING_CONTEXT_W, &aValuesNamingContext, &nCount ); // // Verify we actuall got back at least one value // if (SUCCEEDED(hr) && (nCount < 1)) { hr = HRESULT_FROM_WIN32(ERROR_DS_NO_ATTRIBUTE_OR_VALUE); } BAIL_ON_FAILURE(hr); // // Create nametran object // hr = CoCreateInstance( CLSID_NameTranslate, NULL, CLSCTX_ALL, IID_IADsNameTranslate, (void **) &pNameTranslate ); BAIL_ON_FAILURE(hr); // // Init with defaultNamingContext and get transalte // hr = pNameTranslate->InitEx( ADS_NAME_INITTYPE_SERVER, szHostName, AuthI.User, AuthI.Domain, AuthI.Password ); BAIL_ON_FAILURE(hr); hr = pNameTranslate->Set( ADS_NAME_TYPE_1779, aValuesNamingContext[0] ); BAIL_ON_FAILURE(hr); hr = pNameTranslate->Get( ADS_NAME_TYPE_CANONICAL, &bstrName ); BAIL_ON_FAILURE(hr); if (!bstrName) { BAIL_ON_FAILURE(hr = E_FAIL); } *ppszHostName = AllocADsStr(bstrName); if (!*ppszHostName) { BAIL_ON_FAILURE(hr = E_OUTOFMEMORY); } // // Null terminate one place ahead so we can get rid of / // (*ppszHostName)[wcslen(bstrName)-1] = L'\0'; error : if (ld) { LdapCloseObject(ld); } if (pNameTranslate) { pNameTranslate->Release(); } if (bstrName) { SysFreeString(bstrName); } if (aValuesNamingContext) { LdapValueFree(aValuesNamingContext); } RRETURN(hr); }
27.967253
124
0.502351
[ "object" ]
38652129160f155d8d8e3b4740487108d1cd81c3
3,526
cpp
C++
subset/SSet.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
null
null
null
subset/SSet.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
6
2020-11-29T18:27:05.000Z
2021-12-24T13:14:47.000Z
subset/SSet.cpp
DandyForever/np-complete
9a8912706a85425f9da284173ce09c7eedbf7db0
[ "MIT" ]
8
2020-11-03T17:09:11.000Z
2021-12-04T14:24:49.000Z
#include "SSet.h" #include <algorithm> #include <iterator> bool SSet::checkSumOptimized(DataType expected) { positive_sum = 0; negative_sum = 0; for (auto n : set_) { if (n > 0) positive_sum += n; if (n < 0) negative_sum += n; } return set_.empty() ? false : checkSumOptimizedRecursive(set_.size() - 1, expected); } bool SSet::checkSumOptimizedRecursive(int i, DataType expected) { if ((expected > positive_sum) || (expected < negative_sum)) return false; if (i == 0) return set_[i] == expected; std::pair<int, DataType> key(i, expected); if (Q_results_map.count(key)) return Q_results_map[key]; bool res = checkSumOptimizedRecursive(i - 1, expected) || (set_[i] == expected) || checkSumOptimizedRecursive(i - 1, expected - set_[i]); Q_results_map[key] = res; return res; } std::vector<SSet::DataType> SSet::subsetSums(const std::vector<DataType>& set) { long long total = 1 << set.size(); // total number of subsets = size of power set = 2^n std::vector<SSet::DataType> sums(total, 0); sums[1] = set[0]; int effectiveBits = 1, prevPowOf2 = 1; for (long long i = 2; i < total; ++i) { if (i && (!(i & (i - 1)))) { ++effectiveBits; prevPowOf2 *= 2; } sums[i] = set[effectiveBits - 1] + sums[i - prevPowOf2]; } sums.erase(sums.begin()); return sums; } bool SSet::checkSumOptimizedHS(DataType expected) { std::size_t half_size = set_.size() / 2; std::vector<DataType> firstpart(set_.begin(), set_.begin() + half_size); std::vector<DataType> secondpart(set_.begin() + half_size, set_.end()); std::vector<DataType> firstlist = subsetSums(firstpart); std::vector<DataType> secondlist = subsetSums(secondpart); auto firstit = firstlist.begin(); auto secondit = secondlist.begin(); std::sort(firstlist.begin(), firstlist.end()); std::sort(secondlist.begin(), secondlist.end()); for (firstit = firstlist.begin(); firstit != firstlist.end(); firstit++) { for (secondit = secondlist.begin(); secondit != secondlist.end(); secondit++) { if ((*firstit == 0) || (*secondit == 0)) return true; DataType sum = *firstit + *secondit; if (sum == expected) return true; if (sum > expected) break; } } return false; } bool SSet::checkSumSlow(DataType expected) { for (size_t i = 1; i <= set_.size(); i++) if (checkSumOfNSlow(expected, i)) return true; // Kept you waiting, huh? return false; } bool SSet::checkSumOfNSlow(DataType expected, size_t N) { std::vector<DataType> sub_set(N); return checkSumOfNRecursive(sub_set, expected, N, 0, 0); } /* data ---> Temporary array to store current combination N ---> Size of a combination to be checked index ---> Current index in data i ---> index of current element in set_ */ bool SSet::checkSumOfNRecursive(std::vector<DataType> &data, DataType expected, size_t N, size_t index, size_t i) { // Current cobination is ready, print it if (index == N) return sumSet(data) == expected; // When no more elements are there to put in data[] if (i >= set_.size()) return false; // current is included, put next at next location data[index] = set_[i]; if (checkSumOfNRecursive(data, expected, N, index + 1, i + 1)) return true; // current is excluded, replace it with next // (Note that i+1 is passed, but index is not // changed) if (checkSumOfNRecursive(data, expected, N, index, i + 1)) return true; return false; }
32.953271
90
0.640953
[ "vector" ]
386574a91a051fcd7b73ce1412dd737989ba98cc
937
cpp
C++
src/gt01/gt01.cpp
TeaInside/AI_gt01
6086adfe8f04ee25b01075402e037b3b835214d6
[ "MIT" ]
3
2019-03-09T13:25:46.000Z
2019-03-10T03:14:50.000Z
src/gt01/gt01.cpp
TeaInside/AI_gt01
6086adfe8f04ee25b01075402e037b3b835214d6
[ "MIT" ]
null
null
null
src/gt01/gt01.cpp
TeaInside/AI_gt01
6086adfe8f04ee25b01075402e037b3b835214d6
[ "MIT" ]
null
null
null
#include <gt01/gt01.hpp> Php::Value tea_gt01(Php::Parameters &p) { gt01 *t = new gt01; t->set_name(p[1], p[2]); t->set_text(p[0]); std::string response; bool got_response = t->exec(); if (got_response) { response = t->get_response(); } delete t; t = nullptr; return got_response ? response : ""; } void gt01::set_name(std::string name, std::string nickname) { this->name = name; this->nickname = nickname; } void gt01::set_text(std::string text) { this->text = text; } bool gt01::exec() { return this->check(); } std::string gt01::get_response() { std::vector<std::string> r1; std::vector<std::string> r2; r1.push_back(std::string("{name}")); r2.push_back(std::string(this->name)); r1.push_back(std::string("{cname}")); r2.push_back(std::string(this->nickname)); return Php::call("str_replace", r1, r2, this->response); } void gt01::set_response(std::string response) { this->response = response; }
18.372549
61
0.65635
[ "vector" ]
3871a4cb9d180fb006bf164e6bf728079a8ba4a2
1,322
cpp
C++
wrapcppdll/mycpp/my_cpp_api.cpp
rdotnet/rdotnet-support
dfa991211f251ef853470f14b26682cc50a52818
[ "MIT" ]
null
null
null
wrapcppdll/mycpp/my_cpp_api.cpp
rdotnet/rdotnet-support
dfa991211f251ef853470f14b26682cc50a52818
[ "MIT" ]
null
null
null
wrapcppdll/mycpp/my_cpp_api.cpp
rdotnet/rdotnet-support
dfa991211f251ef853470f14b26682cc50a52818
[ "MIT" ]
1
2015-06-08T13:00:19.000Z
2015-06-08T13:00:19.000Z
#include "my_cpp_api.h" #define SAMPLE_LENGTH 10 int c_api_call_getlength() { return SAMPLE_LENGTH; } SEXP some_R_calculations() { int size = SAMPLE_LENGTH; int tmp[SAMPLE_LENGTH] = { 1, 2, 3, 2, 3, 4, 5, 4, 5, 6 }; return make_int_sexp(size, tmp); } void c_api_call(int * result) { SEXP p = some_R_calculations(); int* int_ptr = INTEGER_POINTER(p); int n = length(p); for (int i = 0; i < n; i++) result[i] = int_ptr[i]; // We are done with p; irrespective of where some_R_calculations got it, // we can notify the R GC that this function releases it. R_ReleaseObject(p); } // Source: https://github.com/jmp75/rClr/blob/master/src/rClr.cpp SEXP make_int_sexp(int n, int * values) { SEXP result; long i = 0; int * int_ptr; // If you PROTECT an R object, you should make sure you UNPROTECT. // Better do it in the same function if you can. PROTECT(result = NEW_INTEGER(n)); int_ptr = INTEGER_POINTER(result); for (i = 0; i < n; i++) { int_ptr[i] = values[i]; } UNPROTECT(1); return result; } int sexp_input(SEXP input) { // SHOULD DO: //if (!isInteger(input)) //{ //} int n = length(input); // SHOULD DO: // if (n<1) do something // We could do complicated stuff with R native functions. // For the sake of this sample, just: int* values = INTEGER(input); return values[0]; }
22.033333
74
0.667171
[ "object" ]
387df4cd7041bfe886927b849d1715012ee2a944
456
cpp
C++
math/sum_of_totient_function/gen/boundaryA.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
290
2019-06-06T22:20:36.000Z
2022-03-27T12:45:04.000Z
math/sum_of_totient_function/gen/boundaryA.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
536
2019-06-06T18:25:36.000Z
2022-03-29T11:46:36.000Z
math/sum_of_totient_function/gen/boundaryA.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
82
2019-06-06T18:17:55.000Z
2022-03-21T07:40:31.000Z
#include "random.h" #include <iostream> #include <vector> #include <cassert> #include "../params.h" using namespace std; using ll = long long; ll f(ll n) { ll ret = 1; while((ret+1)*(ret+1)<=n)++ret; return ret*ret; } int main(int, char* argv[]) { long long seed = atoll(argv[1]); auto gen = Random(seed); ll N = gen.uniform<ll>(1000LL, N_MAX-10L); ll d = gen.uniform<ll>(-3LL, 3L); printf("%lld\n", f(N)+d); return 0; }
17.538462
46
0.589912
[ "vector" ]
38837ed6688351d32d4f33e5896f13c11fbba932
3,543
hpp
C++
include/Nazara/Widgets/Canvas.hpp
DigitalPulseSoftware/NazaraEngine
bf1eff7bb5b17648667ed972517315b11bc1a539
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
376
2015-01-09T03:14:48.000Z
2022-03-26T17:59:18.000Z
include/Nazara/Widgets/Canvas.hpp
DigitalPulseSoftware/NazaraEngine
bf1eff7bb5b17648667ed972517315b11bc1a539
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
252
2015-01-21T17:34:39.000Z
2022-03-20T16:15:50.000Z
include/Nazara/Widgets/Canvas.hpp
DigitalPulseSoftware/NazaraEngine
bf1eff7bb5b17648667ed972517315b11bc1a539
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
104
2015-01-18T11:03:41.000Z
2022-03-11T05:40:47.000Z
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Widgets module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_CANVAS_HPP #define NAZARA_CANVAS_HPP #include <Nazara/Platform/CursorController.hpp> #include <Nazara/Platform/EventHandler.hpp> #include <Nazara/Widgets/BaseWidget.hpp> #include <entt/entity/registry.hpp> namespace Nz { class NAZARA_WIDGETS_API Canvas : public BaseWidget { friend BaseWidget; public: inline Canvas(entt::registry& registry, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController); Canvas(const Canvas&) = delete; Canvas(Canvas&&) = delete; inline ~Canvas(); inline entt::registry& GetRegistry(); inline const entt::registry& GetRegistry() const; Canvas& operator=(const Canvas&) = delete; Canvas& operator=(Canvas&&) = delete; NazaraSignal(OnUnhandledKeyPressed, const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& /*event*/); NazaraSignal(OnUnhandledKeyReleased, const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& /*event*/); protected: inline void ClearKeyboardOwner(std::size_t canvasIndex); inline bool IsKeyboardOwner(std::size_t canvasIndex) const; inline void NotifyWidgetBoxUpdate(std::size_t index); inline void NotifyWidgetCursorUpdate(std::size_t index); std::size_t RegisterWidget(BaseWidget* widget); inline void SetKeyboardOwner(std::size_t canvasIndex); void UnregisterWidget(std::size_t index); private: void OnEventMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); void OnEventMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); void OnEventMouseLeft(const Nz::EventHandler* eventHandler); void OnEventMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event); void OnEventMouseWheelMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseWheelEvent& event); void OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); void OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); void OnEventTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event); void OnEventTextEdited(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::EditEvent& event); struct WidgetEntry { BaseWidget* widget; Nz::Boxf box; Nz::SystemCursor cursor; }; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); NazaraSlot(Nz::EventHandler, OnKeyReleased, m_keyReleasedSlot); NazaraSlot(Nz::EventHandler, OnMouseButtonPressed, m_mouseButtonPressedSlot); NazaraSlot(Nz::EventHandler, OnMouseButtonReleased, m_mouseButtonReleasedSlot); NazaraSlot(Nz::EventHandler, OnMouseLeft, m_mouseLeftSlot); NazaraSlot(Nz::EventHandler, OnMouseMoved, m_mouseMovedSlot); NazaraSlot(Nz::EventHandler, OnMouseWheelMoved, m_mouseWheelMovedSlot); NazaraSlot(Nz::EventHandler, OnTextEntered, m_textEnteredSlot); NazaraSlot(Nz::EventHandler, OnTextEdited, m_textEditedSlot); std::size_t m_keyboardOwner; std::size_t m_hoveredWidget; std::vector<WidgetEntry> m_widgetEntries; entt::registry& m_registry; Nz::CursorControllerHandle m_cursorController; }; } #include <Nazara/Widgets/Canvas.inl> #endif // NDK_CANVAS_HPP
39.808989
126
0.772791
[ "vector" ]
388c4f1205a523311fe68919bf676384f616543d
8,403
cpp
C++
src/TinyTrainable.cpp
maxzwang/TinyTrainable
ce7a9ca85d13d6009298052345ddd4fb364406f2
[ "MIT" ]
null
null
null
src/TinyTrainable.cpp
maxzwang/TinyTrainable
ce7a9ca85d13d6009298052345ddd4fb364406f2
[ "MIT" ]
2
2021-01-15T18:23:39.000Z
2021-03-05T20:00:05.000Z
src/TinyTrainable.cpp
maxzwang/TinyTrainable
ce7a9ca85d13d6009298052345ddd4fb364406f2
[ "MIT" ]
null
null
null
/// @file TinyTrainable.cpp /// @brief Arduino library for Tiny Trainable Instruments /// @author montoyamoraga, peter-parque, maxzwang /// @date November 2020 // include local library #include "TinyTrainable.h" // TinyTrainable::TinyTrainable() {} // initialize static variables bool TinyTrainable::_serialDebugging = false; int TinyTrainable::_baudRate = 9600; // constructor method TinyTrainable::TinyTrainable(Input *newInput, Output *newOutput) { myInput = newInput; myOutput = newOutput; // TODO: research the name of this linking way if (myInput != nullptr) { myInput->tiny = this; } if (myOutput != nullptr) { myOutput->tiny = this; } setupLEDs(); } // destructor method // useful against memory leaks? TinyTrainable::~TinyTrainable() { if (myInput != nullptr) { delete myInput; myInput = nullptr; } if (myOutput != nullptr) { delete myOutput; myOutput = nullptr; } } void TinyTrainable::setupInstrument(bool serialDebugging) { if (myInput != nullptr) { myInput->setupInstrument(serialDebugging); } }; void TinyTrainable::playOutput(int classification) { if (myOutput != nullptr) { myOutput->playOutput(classification); } } // methods for input color void TinyTrainable::trainKNN(int k, int examplesPerClass, float colorThreshold, String objects[3]) { if (myInput != nullptr) { myInput->trainKNN(k, examplesPerClass, colorThreshold, objects); } }; void TinyTrainable::identify() { if (myInput != nullptr) { myInput->identify(); } } void TinyTrainable::setupLEDs() { // setting up orange built-in LED pinMode(LED_BUILTIN, OUTPUT); // initial state off is HIGH for on digitalWrite(LED_BUILTIN, HIGH); // setting up RGB LED pinMode(LEDR, OUTPUT); pinMode(LEDG, OUTPUT); pinMode(LEDB, OUTPUT); // default state off is HIGH digitalWrite(LEDR, HIGH); digitalWrite(LEDG, HIGH); digitalWrite(LEDB, HIGH); } // function for turning on and off the built-in LED void TinyTrainable::setStateLEDBuiltIn(bool turnOn) { if (turnOn) { digitalWrite(LED_BUILTIN, HIGH); } else { digitalWrite(LED_BUILTIN, LOW); } } void TinyTrainable::blinkLEDBuiltIn(int blinks) { setStateLEDBuiltIn(false); for (int i = 0; i < blinks; i++) { setStateLEDBuiltIn(true); delay(500); setStateLEDBuiltIn(false); delay(500); } } // function for turning on and off the RGB LED void TinyTrainable::setStateLEDRGB(bool turnOn, Colors color) { // first turn off digitalWrite(LEDR, HIGH); digitalWrite(LEDG, HIGH); digitalWrite(LEDB, HIGH); // then turn on according to color if (turnOn) { switch (color) { case red: digitalWrite(LEDR, LOW); break; case green: digitalWrite(LEDG, LOW); break; case blue: digitalWrite(LEDB, LOW); break; case yellow: digitalWrite(LEDR, LOW); digitalWrite(LEDG, LOW); break; case magenta: digitalWrite(LEDR, LOW); digitalWrite(LEDB, LOW); break; case cyan: digitalWrite(LEDG, LOW); digitalWrite(LEDB, LOW); break; } } } // traps the arduino in an infinite loop with RGB LED blinking, to signal // some setup missing. explanations in docs by instrument. // void TinyTrainable::errorBlink(Colors color, int blinkNum) { // while (true) { // for (int i = 0; i <= blinkNum; i++) { // // turn on with the color // setStateLEDRGB(true, color); // delay(1000); // // turn off // setStateLEDRGB(false, color); // delay(1000); // } // blinkLEDBuiltIn(1); // } // } // TODO // void TinyTrainable::helloOutputsSetup(OutputMode outputToTest) { // switch (outputToTest) { // case outputMIDI: // setupOutputMIDI(10, 127); // break; // case outputSerialUSB: // Serial.begin(9600); // while (!Serial) // ; // break; // case outputUndefined: // pinMode(LED_BUILTIN, OUTPUT); // digitalWrite(LED_BUILTIN, LOW); // break; // } // } // TODO // void TinyTrainable::helloOutputsSetup(OutputMode outputToTest, int outputPin) // { // switch (outputToTest) { // case outputBuzzer: // // update internal variable // _outputPinTest = outputPin; // // setup pin // pinMode(_outputPinTest, OUTPUT); // break; // case outputLED: // _outputPinTest = outputPin; // pinMode(outputPin, OUTPUT); // break; // case outputServo: // setupOutputServo(outputPin, 0, 180); // setServoTempo(0, 20); // break; // } // } // TODO // void TinyTrainable::helloOutputs(OutputMode outputToTest) { // int timeDelay = 3000; // switch (outputToTest) { // case outputBuzzer: // tone(_outputPinTest, 260, timeDelay); // delay(timeDelay); // tone(_outputPinTest, 330, timeDelay); // delay(timeDelay); // tone(_outputPinTest, 392, timeDelay); // delay(timeDelay); // tone(_outputPinTest, 523, timeDelay); // delay(timeDelay); // break; // case outputLED: // digitalWrite(_outputPinTest, LOW); // delay(timeDelay); // digitalWrite(_outputPinTest, HIGH); // delay(timeDelay); // break; // case outputMIDI: // sendSerialMIDINote(_midiChannel, 37, _midiVelocity); // delay(timeDelay); // sendSerialMIDINote(_midiChannel, 38, _midiVelocity); // delay(timeDelay); // sendSerialMIDINote(_midiChannel, 39, _midiVelocity); // delay(timeDelay); // break; // case outputSerialUSB: // Serial.println("hello world!"); // delay(timeDelay); // break; // case outputServo: // moveServo(0); // break; // case outputUndefined: // blinkLEDBuiltIn(3); // delay(timeDelay); // break; // } // } // functions for buzzer void TinyTrainable::setupOutputBuzzer(int outputPin) { if (myOutput != nullptr) { myOutput->setupOutputBuzzer(outputPin); } } void TinyTrainable::setBuzzerFrequency(int object, int frequency) { if (myOutput != nullptr) { myOutput->setBuzzerFrequency(object, frequency); } } void TinyTrainable::setBuzzerFrequency(int object, int freqMin, int freqMax) { if (myOutput != nullptr) { myOutput->setBuzzerFrequency(object, freqMin, freqMax); } } void TinyTrainable::setBuzzerFrequency(int object, int *arrayFrequencies, int arrayFreqCount) { if (myOutput != nullptr) { myOutput->setBuzzerFrequency(object, *arrayFrequencies, arrayFreqCount); } } void TinyTrainable::setBuzzerDuration(int object, int duration) { if (myOutput != nullptr) { myOutput->setBuzzerDuration(object, duration); } } void TinyTrainable::setBuzzerDuration(int object, int durationMin, int durationMax) { if (myOutput != nullptr) { myOutput->setBuzzerDuration(object, durationMin, durationMax); } } void TinyTrainable::setBuzzerDuration(int object, int *arrayDurations, int arrayDurationCount) { if (myOutput != nullptr) { myOutput->setBuzzerDuration(object, *arrayDurations, arrayDurationCount); } } // functions for output LED void TinyTrainable::setupOutputLED(int outputPin0, int outputPin1, int outputPin2) { if (myOutput != nullptr) { myOutput->setupOutputLED(outputPin0, outputPin1, outputPin2); } } // functions for output MIDI void TinyTrainable::setupOutputMIDI(byte midiChannel, byte midiVelocity) { if (myOutput != nullptr) { myOutput->setupOutputMIDI(midiChannel, midiVelocity); } } void TinyTrainable::setMIDINote(int object, int note){ if (myOutput != nullptr) { myOutput->setMIDINote(object, note); } } // functions for output serial void TinyTrainable::setupOutputSerial() { if (myOutput != nullptr) { myOutput->setupOutputSerial(); } } // functions for output servo void TinyTrainable::setupOutputServo(int outputPin, int servoAngleMin, int servoAngleMax) { if (myOutput != nullptr) { myOutput->setupOutputServo(outputPin, servoAngleMin, servoAngleMax); } } void TinyTrainable::setServoTempo(int object, int tempo) { if (myOutput != nullptr) { myOutput->setServoTempo(object, tempo); } } int TinyTrainable::bpmToMs(int tempo) { if (myOutput != nullptr) { return myOutput->bpmToMs(tempo); } } void TinyTrainable::moveServo(int classification) { if (myOutput != nullptr) { myOutput->moveServo(classification); } }
24.787611
91
0.657979
[ "object" ]
3895acf1bea8f822a2467d3d086ab2cb1e2a6ebd
18,430
cpp
C++
src/main.cpp
JamesDiDonato/CarND-Path-Planning
cdc541f6bc07420e17272bc33003f69ca9c8bd95
[ "MIT" ]
null
null
null
src/main.cpp
JamesDiDonato/CarND-Path-Planning
cdc541f6bc07420e17272bc33003f69ca9c8bd95
[ "MIT" ]
null
null
null
src/main.cpp
JamesDiDonato/CarND-Path-Planning
cdc541f6bc07420e17272bc33003f69ca9c8bd95
[ "MIT" ]
null
null
null
#include <fstream> #include <math.h> #include <uWS/uWS.h> #include <chrono> #include <algorithm> #include <iostream> #include <thread> #include <vector> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "json.hpp" #include "vehicle.h" using namespace std; // for convenience using json = nlohmann::json; // For converting back and forth between radians and degrees. constexpr double pi() { return M_PI; } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. string hasData(string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_first_of("}"); if (found_null != string::npos) { return ""; } else if (b1 != string::npos && b2 != string::npos) { return s.substr(b1, b2 - b1 + 2); } return ""; } double distance(double x1, double y1, double x2, double y2) { return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y) { double closestLen = 100000; //large number int closestWaypoint = 0; for(int i = 0; i < maps_x.size(); i++) { double map_x = maps_x[i]; double map_y = maps_y[i]; double dist = distance(x,y,map_x,map_y); if(dist < closestLen) { closestLen = dist; closestWaypoint = i; } } return closestWaypoint; } int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y) { int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y); double map_x = maps_x[closestWaypoint]; double map_y = maps_y[closestWaypoint]; double heading = atan2((map_y-y),(map_x-x)); double angle = fabs(theta-heading); angle = min(2*pi() - angle, angle); if(angle > pi()/4) { closestWaypoint++; if (closestWaypoint == maps_x.size()) { closestWaypoint = 0; } } return closestWaypoint; } // Transform from Cartesian x,y coordinates to Frenet s,d coordinates vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y) { int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y); int prev_wp; prev_wp = next_wp-1; if(next_wp == 0) { prev_wp = maps_x.size()-1; } double n_x = maps_x[next_wp]-maps_x[prev_wp]; double n_y = maps_y[next_wp]-maps_y[prev_wp]; double x_x = x - maps_x[prev_wp]; double x_y = y - maps_y[prev_wp]; // find the projection of x onto n double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y); double proj_x = proj_norm*n_x; double proj_y = proj_norm*n_y; double frenet_d = distance(x_x,x_y,proj_x,proj_y); //see if d value is positive or negative by comparing it to a center point double center_x = 1000-maps_x[prev_wp]; double center_y = 2000-maps_y[prev_wp]; double centerToPos = distance(center_x,center_y,x_x,x_y); double centerToRef = distance(center_x,center_y,proj_x,proj_y); if(centerToPos <= centerToRef) { frenet_d *= -1; } // calculate s value double frenet_s = 0; for(int i = 0; i < prev_wp; i++) { frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]); } frenet_s += distance(0,0,proj_x,proj_y); return {frenet_s,frenet_d}; } // // Transform from Frenet s,d coordinates to Cartesian x,y // vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y) // { // int prev_wp = -1; // while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) )) // { // prev_wp++; // } // int wp2 = (prev_wp+1)%maps_x.size(); // double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp])); // // the x,y,s along the segment // double seg_s = (s-maps_s[prev_wp]); // double seg_x = maps_x[prev_wp]+seg_s*cos(heading); // double seg_y = maps_y[prev_wp]+seg_s*sin(heading); // double perp_heading = heading-pi()/2; // double x = seg_x + d*cos(perp_heading); // double y = seg_y + d*sin(perp_heading); // return {x,y}; // } int main() { uWS::Hub h; Vehicle ego = Vehicle(); // Load up map values for waypoint's x,y,s and d normalized normal vectors vector<double> map_waypoints_x; vector<double> map_waypoints_y; vector<double> map_waypoints_s; vector<double> map_waypoints_dx; vector<double> map_waypoints_dy; // Waypoint map to read from string map_file_ = "../data/highway_map.csv"; // The max s value before wrapping around the track back to 0 double max_s = 6945.554; ifstream in_map_(map_file_.c_str(), ifstream::in); string line; while (getline(in_map_, line)) { istringstream iss(line); double x; double y; float s; float d_x; float d_y; iss >> x; iss >> y; iss >> s; iss >> d_x; iss >> d_y; map_waypoints_x.push_back(x); map_waypoints_y.push_back(y); map_waypoints_s.push_back(s); map_waypoints_dx.push_back(d_x); map_waypoints_dy.push_back(d_y); ego.map_waypoints_x.push_back(x); ego.map_waypoints_y.push_back(y); ego.map_waypoints_s.push_back(s); } h.onMessage([&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy,&ego](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event //auto sdata = string(data).substr(0, length); //cout << sdata << endl; if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(data); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { //cout << ego.num_points << endl; // j[1] is the data JSON object // Main car's localization Data double car_x = j[1]["x"]; double car_y = j[1]["y"]; double car_s = j[1]["s"]; double car_d = j[1]["d"]; double car_yaw = j[1]["yaw"]; double car_speed = j[1]["speed"]; // Previous path data given to the Planner auto previous_path_x = j[1]["previous_path_x"]; auto previous_path_y = j[1]["previous_path_y"]; //Previous path's end s and d values double end_path_s = j[1]["end_path_s"]; double end_path_d = j[1]["end_path_d"]; // Sensor Fusion Data, a list of all other cars on the same side of the road. auto sensor_fusion = j[1]["sensor_fusion"]; //Sensor Fusion Format : [ id, x, y, vx, vy, s, d] cout << "***** Start of Iteration*****" <<endl; cout << endl; // PROJECT CODE BEGINS: //Update Ego Vehicle with data from simulator: ego.x = car_x; ego.y = car_y; ego.s = car_s; ego.d = car_d; ego.yaw = car_yaw; ego.speed = car_speed; ego.prev_size = previous_path_x.size(); ego.prev_x_vals = previous_path_x.get<vector<double>>(); ego.prev_y_vals = previous_path_y.get<vector<double>>(); ego.sensor_fusion = sensor_fusion.get<vector<vector<double>>>(); ego.GetSuccessorStates(); ego.StateTransition(); ego.AdaptiveCruise(); ego.GenerateTrajectory(); json msgJson; msgJson["next_x"] = ego.next_x_vals; msgJson["next_y"] = ego.next_y_vals; cout << "\n***** End of Iteration*****\n" <<endl; // // Old Code (pre Vehicle object commit) // vector<double> next_x_vals; // vector<double> next_y_vals; // bool displayPoints = false; // whether to dislpay the calculated points or not. // //Points to represent the last and second last points from the previous path // double ref_x; // double ref_y; // double ref_x_prev; // double ref_y_prev; // double ref_yaw; // uint prev_size = previous_path_x.size(); // double speed_limit = 47; //speed limit in mph // uint total_points = 50; // uint keep_points = prev_size - 10; //Number of points to include from previous path // uint ego_lane = 1; // double v_adj = 2.0; //Speed to adjust each iteration by // bool too_close = false; // double ref_v = car_speed; // cout << "\n\nPrevious Size Remainder = " << prev_size << endl; // cout << "Current Ego Position = [ " << car_x << " , " << car_y << " ]" <<endl; // cout << "Current Ego Speed = " << car_speed << endl; // double id,x,y,vx,vy,sf,dist; // for ( int i = 0; i <sensor_fusion.size();i++) // { // dist = sensor_fusion[i][6]; // sf = sensor_fusion[i][5]; // id = sensor_fusion[i][0]; // //cout << "Checking Vehicle "<< sensor_fusion[i][0] << "."<< endl; // //Determine if vehicle is in ego lane // if(dist <(4+ 4*ego_lane) && dist > (4*ego_lane)) // { // double vx = sensor_fusion[i][3]; // double vy = sensor_fusion[i][4]; // double check_speed = sqrt(vx*vx + vy*vy); // if ( abs(sf - car_s < 30) && (sf > car_s)) // { // too_close = true; // cout << "Found a vehicle too close!!!! = " << car_speed << endl; // } // } // } // if(too_close) // { // ref_v -= v_adj; // cout << "Decreasing Speed to "<< ref_v << "." << endl; // } // else if(ref_v < speed_limit) // { // ref_v += v_adj; // cout << "Increasing Speed to "<< ref_v << "." << endl; // } // /* Generate Spline for Path*/ // vector<double> ptsy; // vector<double> ptsx; // double spline_starting_x; // double spline_starting_y; // // If previous size is almost empty, estimate the previous // // 2 way points based on vehicle orientation // if (prev_size <2) // { // ref_yaw = deg2rad(car_yaw); // double prev_car_x = car_x - cos(ref_yaw); // double prev_car_y = car_y - sin(ref_yaw); // ptsx.push_back(prev_car_x); // ptsx.push_back(car_x); // ptsy.push_back(prev_car_y); // ptsy.push_back(car_y); // spline_starting_x = prev_car_x; // spline_starting_y = prev_car_y; // ref_x = car_x; // ref_y = car_y; // } // else //Use the previous path's ending points as the starting point // { // //redefine reference state as the end of the previous point array // ref_x = previous_path_x[keep_points-1]; // ref_y = previous_path_y[keep_points-1]; // ref_x_prev = previous_path_x[keep_points-2]; // ref_y_prev = previous_path_y[keep_points-2]; // spline_starting_x = ref_x_prev; // spline_starting_y = ref_y_prev; // ref_yaw = atan2(ref_y - ref_y_prev, ref_x - ref_x_prev); // ptsx.push_back(ref_x_prev); // ptsx.push_back(ref_x); // ptsy.push_back(ref_y_prev); // ptsy.push_back(ref_y); // } // //Get waypoints up the road to generate spline // vector<double> next_wp0 = getXY(car_s + 30, 2+4*ego_lane , map_waypoints_s, map_waypoints_x, map_waypoints_y); // vector<double> next_wp1 = getXY(car_s + 60, 2+4*ego_lane , map_waypoints_s, map_waypoints_x, map_waypoints_y); // vector<double> next_wp2 = getXY(car_s + 90, 2+4*ego_lane , map_waypoints_s, map_waypoints_x, map_waypoints_y); // ptsx.push_back(next_wp0[0]); // ptsx.push_back(next_wp1[0]); // ptsx.push_back(next_wp2[0]); // ptsy.push_back(next_wp0[1]); // ptsy.push_back(next_wp1[1]); // ptsy.push_back(next_wp2[1]); // if(displayPoints){ // //Print Global Spline Waypoints // cout << "Global Spline Waypoints: " << endl; // for (int i = 0 ; i < ptsx.size(); i++) // { // //print Global Spline Waypoints : // cout << "\t[ " << ptsx[i] << "," << ptsy[i] << " ]" << endl; // } // cout << endl; // } // // Transform to local coordinates by setting the origin to the start of the spline path // for (int i = 0 ; i < ptsx.size(); i++) // { // double shift_x = ptsx[i] - spline_starting_x; // double shift_y = ptsy[i] - spline_starting_y; // ptsx[i] = (shift_x * cos(0 - ref_yaw) - shift_y * sin(0- ref_yaw)); // ptsy[i] = (shift_x * sin(0 - ref_yaw) + shift_y * cos(0- ref_yaw)); // } // if(displayPoints){ // //Print Local Spline Waypoints // cout << "Local Spline Waypoints: " <<endl; // for (int i = 0 ; i < ptsx.size(); i++) // { // //print spline waypoints Global: // cout << "\t[" << ptsx[i] << "," << ptsy[i] << "]" << endl; // } // cout << endl; // } // //Create spline that maps to lane path // tk::spline s; // s.set_points(ptsx,ptsy); // /* Write to the output points */ // // Push the old values if there are any, defined by keep_points // int i; // cout << "\nAdding " << min(prev_size,keep_points) <<" points from previous path:" <<endl; // for (i = 0; i < min(prev_size,keep_points); i++) // { // next_x_vals.push_back(previous_path_x[i]); // next_y_vals.push_back(previous_path_y[i]); // if(displayPoints){cout << "\t Adding Previous Point = [" << previous_path_x[i] << " , " << previous_path_y[i] <<"]" << endl;} // } // cout << "Done Adding points from previous path.\n" <<endl; // //Generate new points: // double local_x_coord = 0; // double local_y_coord = 0; // double global_x_coord = 0; // double global_y_coord = 0; // //Compute longitudinal increment based on reference speed & simulator physics // double x_inc = ref_v*0.02/(2.237); // cout << "\nGenerating "<< total_points - min(keep_points,prev_size) << " Points for Future Vehicle Path:" <<endl; // for (i = 0; i < total_points - min(keep_points,prev_size); i ++) // { // //Local (x,y) coordinate for point // local_x_coord += x_inc; // local_y_coord = s(local_x_coord); //Generate spline value // if(displayPoints){cout << "\tLocal = [" << local_x_coord <<" , " << local_y_coord <<"] , ";} // //Convert local coordinates back to global: // double x_ref = local_x_coord; // double y_ref = local_y_coord; // global_x_coord = (x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw)); // global_y_coord = (x_ref * sin(ref_yaw) + y_ref*cos(ref_yaw)); // global_x_coord += ref_x; // global_y_coord += ref_y; // next_x_vals.push_back(global_x_coord); // next_y_vals.push_back(global_y_coord); // if(displayPoints){cout << "Global = [" << global_x_coord <<" , " << global_y_coord <<"] " << endl;} // } // cout << "Done Generating New Points.\n" <<endl; // json msgJson; // msgJson["next_x"] = next_x_vals; // msgJson["next_y"] = next_y_vals; auto msg = "42[\"control\","+ msgJson.dump()+"]"; //this_thread::sleep_for(chrono::milliseconds(1000)); ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } } }); // We don't need this since we're not using HTTP but if it's removed the // program // doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
31.775862
167
0.525827
[ "object", "vector", "transform" ]
389919dc402f018046b2f84f08a6cf449e375084
3,621
cpp
C++
tests/BidiagonalFactorization.cpp
dassencio/freeaml
26e9f3e3b0d86f098f33408e39ea8b46c68fd82d
[ "BSD-2-Clause" ]
1
2017-05-25T19:49:49.000Z
2017-05-25T19:49:49.000Z
tests/BidiagonalFactorization.cpp
dassencio/freeaml
26e9f3e3b0d86f098f33408e39ea8b46c68fd82d
[ "BSD-2-Clause" ]
null
null
null
tests/BidiagonalFactorization.cpp
dassencio/freeaml
26e9f3e3b0d86f098f33408e39ea8b46c68fd82d
[ "BSD-2-Clause" ]
null
null
null
#include <BidiagonalFactorization.h> #include <Matrix.h> #include <SparseMatrix.h> #include <Vector.h> #include <gtest/gtest.h> TEST(BidiagonalFactorizationTest, Factorize4x4Matrix) { /* matrix to be factorized */ freeaml::SparseMatrix<double> A = {{3.11, 4.20, 4.25, 1.73}, {2.73, 1.23, 3.89, 2.11}, {4.63, 0.00, 1.51, 2.67}, {3.70, 0.00, 0.31, 3.84}}; freeaml::Matrix<double> U, V; freeaml::SparseMatrix<double> Z; /* compute the bidiagonal factorization A = UZV^t */ bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V); EXPECT_TRUE(status); /* compute UZV^t */ freeaml::Matrix<double> UZVt = U * Z * V.transpose(); /* compute U^t*U and V^t*V */ freeaml::Matrix<double> UtU = U.transpose() * U; freeaml::Matrix<double> VtV = V.transpose() * V; /* I is the 4×4 identity matrix */ freeaml::Matrix<double> I = freeaml::identity_matrix<double>(4); EXPECT_LE((A - UZVt).max_norm(), 1.e-10); EXPECT_LE((UtU - I).max_norm(), 1.e-10); EXPECT_LE((VtV - I).max_norm(), 1.e-10); } TEST(BidiagonalFactorizationTest, Factorize6x4Matrix) { /* matrix to be factorized */ freeaml::Matrix<double> A = {{3.11, 4.20, 4.25, 1.73}, {2.73, 1.23, 3.89, 2.11}, {4.63, 0.00, 1.51, 2.67}, {3.70, 0.00, 0.31, 3.84}, {2.35, 0.67, 1.48, 4.82}, {1.94, 0.48, 0.00, 1.44}}; freeaml::Matrix<double> U, V; freeaml::SparseMatrix<double> Z; /* compute the bidiagonal factorization A = UZV^t */ bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V); EXPECT_TRUE(status); /* compute UZV^t */ freeaml::Matrix<double> UZVt = U * Z * V.transpose(); /* compute U^t*U and V^t*V */ freeaml::Matrix<double> UtU = U.transpose() * U; freeaml::Matrix<double> VtV = V.transpose() * V; /* I4 and I6 are the 4×4 and 6×6 identity matrices respectively */ freeaml::Matrix<double> I4 = freeaml::identity_matrix<double>(4); freeaml::Matrix<double> I6 = freeaml::identity_matrix<double>(6); EXPECT_LE((A - UZVt).max_norm(), 1.e-10); EXPECT_LE((UtU - I6).max_norm(), 1.e-10); EXPECT_LE((VtV - I4).max_norm(), 1.e-10); } TEST(BidiagonalFactorizationTest, Factorize4x6Matrix) { /* matrix to be factorized */ freeaml::Matrix<double> A = {{2.02, 0.07, 3.56, 0.96, 3.09, 2.93}, {0.23, 1.13, 1.04, 4.56, 0.77, 2.89}, {0.51, 1.93, 2.06, 4.80, 0.68, 2.28}, {0.28, 0.83, 4.07, 2.25, 3.83, 0.13}}; freeaml::Matrix<double> U, V; freeaml::SparseMatrix<double> Z; /* compute the bidiagonal factorization A = UZV^t */ bool status = freeaml::BidiagonalFactorization::factorize(A, U, Z, V); EXPECT_TRUE(status); /* compute UZV^t */ freeaml::Matrix<double> UZVt = U * Z * V.transpose(); /* compute U^t*U and V^t*V */ freeaml::Matrix<double> UtU = U.transpose() * U; freeaml::Matrix<double> VtV = V.transpose() * V; /* I4 and I6 are the 4×4 and 6×6 identity matrices respectively */ freeaml::Matrix<double> I4 = freeaml::identity_matrix<double>(4); freeaml::Matrix<double> I6 = freeaml::identity_matrix<double>(6); EXPECT_LE((A - UZVt).max_norm(), 1.e-10); EXPECT_LE((UtU - I4).max_norm(), 1.e-10); EXPECT_LE((VtV - I6).max_norm(), 1.e-10); }
35.15534
74
0.555095
[ "vector" ]
389ae2d88a9d606bf84d1ac4a059dc6d4598db1d
6,192
cpp
C++
lighthouse/src/v20200324/model/DataDiskPrice.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
lighthouse/src/v20200324/model/DataDiskPrice.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
lighthouse/src/v20200324/model/DataDiskPrice.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/lighthouse/v20200324/model/DataDiskPrice.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Lighthouse::V20200324::Model; using namespace std; DataDiskPrice::DataDiskPrice() : m_diskIdHasBeenSet(false), m_originalDiskPriceHasBeenSet(false), m_originalPriceHasBeenSet(false), m_discountHasBeenSet(false), m_discountPriceHasBeenSet(false) { } CoreInternalOutcome DataDiskPrice::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("DiskId") && !value["DiskId"].IsNull()) { if (!value["DiskId"].IsString()) { return CoreInternalOutcome(Core::Error("response `DataDiskPrice.DiskId` IsString=false incorrectly").SetRequestId(requestId)); } m_diskId = string(value["DiskId"].GetString()); m_diskIdHasBeenSet = true; } if (value.HasMember("OriginalDiskPrice") && !value["OriginalDiskPrice"].IsNull()) { if (!value["OriginalDiskPrice"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `DataDiskPrice.OriginalDiskPrice` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_originalDiskPrice = value["OriginalDiskPrice"].GetDouble(); m_originalDiskPriceHasBeenSet = true; } if (value.HasMember("OriginalPrice") && !value["OriginalPrice"].IsNull()) { if (!value["OriginalPrice"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `DataDiskPrice.OriginalPrice` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_originalPrice = value["OriginalPrice"].GetDouble(); m_originalPriceHasBeenSet = true; } if (value.HasMember("Discount") && !value["Discount"].IsNull()) { if (!value["Discount"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `DataDiskPrice.Discount` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_discount = value["Discount"].GetDouble(); m_discountHasBeenSet = true; } if (value.HasMember("DiscountPrice") && !value["DiscountPrice"].IsNull()) { if (!value["DiscountPrice"].IsLosslessDouble()) { return CoreInternalOutcome(Core::Error("response `DataDiskPrice.DiscountPrice` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_discountPrice = value["DiscountPrice"].GetDouble(); m_discountPriceHasBeenSet = true; } return CoreInternalOutcome(true); } void DataDiskPrice::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_diskIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DiskId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_diskId.c_str(), allocator).Move(), allocator); } if (m_originalDiskPriceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OriginalDiskPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_originalDiskPrice, allocator); } if (m_originalPriceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OriginalPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_originalPrice, allocator); } if (m_discountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Discount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_discount, allocator); } if (m_discountPriceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DiscountPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_discountPrice, allocator); } } string DataDiskPrice::GetDiskId() const { return m_diskId; } void DataDiskPrice::SetDiskId(const string& _diskId) { m_diskId = _diskId; m_diskIdHasBeenSet = true; } bool DataDiskPrice::DiskIdHasBeenSet() const { return m_diskIdHasBeenSet; } double DataDiskPrice::GetOriginalDiskPrice() const { return m_originalDiskPrice; } void DataDiskPrice::SetOriginalDiskPrice(const double& _originalDiskPrice) { m_originalDiskPrice = _originalDiskPrice; m_originalDiskPriceHasBeenSet = true; } bool DataDiskPrice::OriginalDiskPriceHasBeenSet() const { return m_originalDiskPriceHasBeenSet; } double DataDiskPrice::GetOriginalPrice() const { return m_originalPrice; } void DataDiskPrice::SetOriginalPrice(const double& _originalPrice) { m_originalPrice = _originalPrice; m_originalPriceHasBeenSet = true; } bool DataDiskPrice::OriginalPriceHasBeenSet() const { return m_originalPriceHasBeenSet; } double DataDiskPrice::GetDiscount() const { return m_discount; } void DataDiskPrice::SetDiscount(const double& _discount) { m_discount = _discount; m_discountHasBeenSet = true; } bool DataDiskPrice::DiscountHasBeenSet() const { return m_discountHasBeenSet; } double DataDiskPrice::GetDiscountPrice() const { return m_discountPrice; } void DataDiskPrice::SetDiscountPrice(const double& _discountPrice) { m_discountPrice = _discountPrice; m_discountPriceHasBeenSet = true; } bool DataDiskPrice::DiscountPriceHasBeenSet() const { return m_discountPriceHasBeenSet; }
28.534562
157
0.701712
[ "model" ]
38a6a82be2dbe17f8b68ec5a84d63488d0730b4e
17,594
hpp
C++
packages/core/include/soss/utilities.hpp
aaronchongth/soss_v2
b531c2046e24684670a4a2ea2fd3c134fcba0591
[ "Apache-2.0" ]
null
null
null
packages/core/include/soss/utilities.hpp
aaronchongth/soss_v2
b531c2046e24684670a4a2ea2fd3c134fcba0591
[ "Apache-2.0" ]
null
null
null
packages/core/include/soss/utilities.hpp
aaronchongth/soss_v2
b531c2046e24684670a4a2ea2fd3c134fcba0591
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef SOSS__UTILITIES_HPP #define SOSS__UTILITIES_HPP #include <soss/Message.hpp> #include <algorithm> #include <mutex> #include <type_traits> #include <vector> namespace soss { //============================================================================== template<typename Container> void vector_resize(Container& vector, std::size_t size) { vector.resize(size); } template<typename T, std::size_t N> void vector_resize(std::array<T, N>& /*array*/, std::size_t /*size*/) { // Do nothing. Arrays don't need to be resized. } //============================================================================== template<typename Container> void vector_reserve(Container& vector, std::size_t size) { vector.reserve(size); } template<typename T, std::size_t N> void vector_reserve(std::array<T, N>& /*array*/, std::size_t /*size*/) { // Do nothing. Arrays don't need to be reserved. } //============================================================================== template<typename Container, typename Arg> void vector_push_back(Container& vector, Arg&& arg) { vector.push_back(std::forward<Arg>(arg)); } //============================================================================== template<typename T, std::size_t N, typename Arg> void vector_push_back(std::array<T, N>& /*array*/, Arg&& /*arg*/) { // Do nothing. Arrays will never be told to push_back(). This overload only // exists to satisfy the compiler. } //============================================================================== /// \brief Convenience function for converting a bounded vector of /// soss::Messages into a bounded vector of middleware-specific messages. /// /// To make the limit unbounded, set the UpperBound argument to /// std::numeric_limits<VectorType::size_type>::max() /// /// This is effectively a function, but we wrap it in a struct so that it can be /// used as a template argument. template<typename ElementType, std::size_t UpperBound> struct convert_bounded_vector { template<typename FromType, typename ToType, typename FromContainer, typename ToContainer> static void convert( const FromContainer& from, ToContainer& to, void(*convert)(const FromType& from, ToType& to), ToType(*initialize)() = []() { return ToType(); }) { // TODO(MXG): Should we emit a warning when the incoming data exceeds the // upper bound? const std::size_t N = std::min(from.size(), UpperBound); vector_reserve(to, N); for(std::size_t i=0; i < N; ++i) { const FromType& from_msg = from[i]; if(i < to.size()) { (*convert)(from_msg, to[i]); } else { ToType to_msg = (*initialize)(); (*convert)(from_msg, to_msg); vector_push_back(to, std::move(to_msg)); } } if(to.size() > N) vector_resize(to, N); } }; //============================================================================== /// \brief This template specialization is needed to deal with the edge case /// produced by vectors of bools. std::vector<bool> is specialized to be /// implemented as a bitmap, and as a result its operator[] cannot return its /// bool elements by reference. Instead it returns a "reference" proxy object, /// which is not something can be used by the standard convert_bounded_vector /// function. template<std::size_t UpperBound> struct convert_bounded_vector<bool, UpperBound> { template<typename FromContainer, typename ToContainer> static void convert( const FromContainer& from, ToContainer& to, void(* /*unused*/ )( const typename FromContainer::value_type& from, typename ToContainer::value_type& to), typename ToContainer::value_type(* /*unused*/ )() = []() { return typename ToContainer::value_type(); }) { const std::size_t N = std::min(from.size(), UpperBound); vector_resize(to, N); for(std::size_t i=0; i < N; ++i) to[i] = static_cast<typename ToContainer::value_type>(from[i]); } }; //============================================================================== /// \brief A utility to help with converting data between generic soss Field /// objects and middleware-specific data structures. /// /// This struct will work as-is on primitive types (a.k.a. arithmetic types or /// strings), but you should create a template specialization for converting to /// or from any complex class types. template<typename Type> struct Convert { using native_type = Type; using soss_type = native_type; using field_iterator = std::map<std::string, Field>::iterator; using const_field_iterator = std::map<std::string, Field>::const_iterator; static constexpr bool type_is_primitive = std::is_arithmetic<Type>::value || std::is_same<std::string, Type>::value || std::is_same<std::basic_string<char16_t>, Type>::value; /// \brief Create an instance of the generic soss version of this type /// /// For primitive types, this will be the same as the native type template<typename... Args> static soss_type make_soss(Args&&... args) { static_assert(type_is_primitive, "The soss::Convert struct should be specialized for non-primitive types"); return soss_type(std::forward<Args>(args)...); } /// \brief Create a field containing the generic soss version of this type template<typename... Args> static Field make_soss_field(Args&&... args) { static_assert(type_is_primitive, "The soss::Convert struct should be specialized for non-primitive types"); return soss::make_field<soss_type>(make_soss(std::forward<Args>(args)...)); } /// \brief Add a field of this type to the specified message /// /// \param[out] msg /// The message to add the field to /// /// \param[in] name /// The name that should be given to the field static void add_field(soss::Message& msg, const std::string& name) { static_assert(type_is_primitive, "The soss::Convert struct should be specialized for non-primitive types"); msg.data[name] = make_soss_field(); } /// \brief Move data from a generic soss data structure to a native middleware /// data structure static void from_soss(const soss_type& from, native_type& to) { static_assert(type_is_primitive, "The soss::Convert struct should be specialized for non-primitive types"); to = from; } /// \brief Move data from a generic soss message field to a native middleware /// data structure static void from_soss_field(const const_field_iterator& from, native_type& to) { static_assert(type_is_primitive, "The soss::Convert struct should be specialized for non-primitive types"); to = *from->second.cast<soss_type>(); } /// \brief Move data from a native middleware data structure to a generic soss /// data structure. static void to_soss(const native_type& from, soss_type& to) { to = from; } /// \brief Move data from a native middleware data structure to a generic soss /// message field. static void to_soss_field(const native_type& from, field_iterator to) { static_assert(type_is_primitive, "The soss::Convert struct should be specialized for non-primitive types"); *to->second.cast<soss_type>() = from; } }; //============================================================================== /// \brief A class that ensures that low-precision data values will be stored as /// their higher precision equivalents in the soss::Message, and that low /// precision values can be assigned from higher precision data within a /// soss::Message. This helps convert messages between middlewares that care /// about precision and those that don't. /// /// The macro SOSS_CONVERT_LOW_PRECISION(H, L) will create the specialization, /// but most potential low-precision conversions are already provided. template<typename HighPrecision, typename LowPrecision> struct LowPrecisionConvert { using native_type = LowPrecision; using soss_type = HighPrecision; using field_iterator = std::map<std::string, Field>::iterator; using const_field_iterator = std::map<std::string, Field>::const_iterator; static constexpr bool type_is_primitive = std::is_arithmetic<HighPrecision>::value || std::is_same<std::string, HighPrecision>::value || std::is_same<std::basic_string<char16_t>, HighPrecision>::value; // Documentation inherited from Convert template<typename... Args> static soss_type make_soss(Args&&... args) { return soss_type(std::forward<Args>(args)...); } // Documentation inherited from Convert template<typename... Args> static Field make_soss_field(Args&&... args) { return soss::make_field<soss_type>(make_soss(std::forward<Args>(args)...)); } // Documentation inherited from Convert static void add_field(soss::Message& msg, const std::string& name) { msg.data[name] = make_soss_field(); } // Documentation inherited from Convert static void from_soss(const soss_type& from, native_type& to) { to = static_cast<native_type>(from); } // Documentation inherited from Convert static void from_soss_field(const const_field_iterator& from, native_type& to) { to = static_cast<native_type>(*from->second.cast<soss_type>()); } // Documentation inherited from Convert static void to_soss(const native_type& from, soss_type& to) { to = from; } // Documentation inherited from Convert static void to_soss_field(const native_type& from, field_iterator to) { *to->second.cast<soss_type>() = from; } }; #define SOSS_CONVERT_LOW_PRECISION(H, L) \ template<> struct Convert<L> : LowPrecisionConvert<H, L> { } SOSS_CONVERT_LOW_PRECISION(double, float); SOSS_CONVERT_LOW_PRECISION(uint64_t, uint8_t); SOSS_CONVERT_LOW_PRECISION(uint64_t, uint16_t); SOSS_CONVERT_LOW_PRECISION(uint64_t, uint32_t); SOSS_CONVERT_LOW_PRECISION(int64_t, int8_t); SOSS_CONVERT_LOW_PRECISION(int64_t, int16_t); SOSS_CONVERT_LOW_PRECISION(int64_t, int32_t); /// This is done to accommodate ROS1, which represents booleans using uint8. /// Hopefully using xtypes can remedy this in the future. SOSS_CONVERT_LOW_PRECISION(uint64_t, bool); //============================================================================== /// \brief A class that helps create a Convert<> specialization for compound /// message types. /// /// To create a specialization for a native middleware message type, do the /// following: /// /// \code /// namespace soss { /// /// template<> /// struct Convert<native::middleware::type> /// : soss::MessageConvert< /// native::middleware::type, /// &native::middleware::instantiate_type_fnc, /// &native::middleware::convert_from_soss_fnc, /// &native::middleware::convert_to_soss_fnc /// > { }; /// /// } // namespace soss /// \endcode /// /// Make sure that this template specialization is put into the root soss /// namespace. template< typename Type, Message (*_initialize_message)(), void (*_from_soss)(const soss::Message& from, Type& to), void (*_to_soss)(const Type& from, soss::Message& to)> struct MessageConvert { using native_type = Type; using soss_type = Message; using field_iterator = std::map<std::string, Field>::iterator; using const_field_iterator = std::map<std::string, Field>::const_iterator; static constexpr bool type_is_primitive = false; // Documentation inherited from Convert template<typename... Args> static soss_type make_soss(Args&&... args) { return (*_initialize_message)(std::forward<Args>(args)...); } // Documentation inherited from Convert template<typename... Args> static Field make_soss_field(Args&&... args) { return soss::make_field<soss::Message>(make_soss(std::forward<Args>(args)...)); } // Documentation inherited from Convert static void add_field(soss::Message& msg, const std::string& name) { msg.data[name] = make_soss_field(); } // Documentation inherited from Convert static void from_soss(const soss_type& from, native_type& to) { (*_from_soss)(from, to); } // Documentation inherited from Convert static void from_soss_field(const const_field_iterator& from, native_type& to) { from_soss(*from->second.cast<soss::Message>(), to); } // Documentation inherited from Convert static void to_soss(const native_type& from, soss_type& to) { (*_to_soss)(from, to); } // Documentation inherited from Convert static void to_soss_field(const native_type& from, field_iterator to) { to_soss(from, *to->second.cast<soss::Message>()); } }; //============================================================================== template< typename ElementType, typename NativeType, typename SossType, class ContainerConversionImpl> struct ContainerConvert { using native_type = NativeType; using soss_type = SossType; using field_iterator = std::map<std::string, Field>::iterator; using const_field_iterator = std::map<std::string, Field>::const_iterator; static constexpr bool type_is_primitive = Convert<ElementType>::type_is_primitive; // Documentation inherited from Convert template<typename... Args> static soss_type make_soss(Args&&... args) { return soss_type(std::forward<Args>(args)...); } // Documentation inherited from Convert template<typename... Args> static Field make_soss_field(Args&&... args) { return soss::make_field<soss_type>(make_soss(std::forward<Args>(args)...)); } // Documentation inherited from Convert static void add_field(soss::Message& msg, const std::string& name) { msg.data[name] = make_soss_field(); } // Documentation inherited from Convert static void from_soss(const soss_type& from, native_type& to) { ContainerConversionImpl::convert( from, to, &Convert<ElementType>::from_soss); } // Documentation inherited from Convert static void from_soss_field(const const_field_iterator& from, native_type& to) { from_soss(*from->second.cast<soss_type>(), to); } static void to_soss(const native_type& from, soss_type& to) { ContainerConversionImpl::convert( from, to, &Convert<ElementType>::to_soss, &Convert<ElementType>::make_soss); } // Documentation inherited from Convert static void to_soss_field(const native_type& from, field_iterator to) { to_soss(from, *to->second.cast<soss_type>()); } }; //============================================================================== template<typename ElementType, typename Allocator> struct Convert<std::vector<ElementType, Allocator>> : ContainerConvert< ElementType, std::vector<typename Convert<ElementType>::native_type, Allocator>, std::vector<typename Convert<ElementType>::soss_type>, soss::convert_bounded_vector<ElementType, std::numeric_limits< typename std::vector<ElementType, Allocator>::size_type>::max()>> { }; //============================================================================== template<typename ElementType, std::size_t N> struct Convert<std::array<ElementType, N>> : ContainerConvert< ElementType, std::array<typename Convert<ElementType>::native_type, N>, std::vector<typename Convert<ElementType>::soss_type>, soss::convert_bounded_vector<ElementType, N>> { }; //============================================================================== /// \brief A thread-safe repository for resources to avoid unnecessary /// allocations template<typename Resource, Resource(*initializerT)()> class ResourcePool { public: ResourcePool(const std::size_t initial_depth = 1) { _queue.reserve(initial_depth); for(std::size_t i=0; i < initial_depth; ++i) _queue.emplace_back((_initializer)()); } void setInitializer(std::function<Resource()> initializer) { _initializer = std::move(initializer); } Resource pop() { if(_queue.empty()) { return (_initializer)(); } std::unique_lock<std::mutex> lock(_mutex); Resource r = std::move(_queue.back()); _queue.pop_back(); return r; } void recycle(Resource&& r) { std::unique_lock<std::mutex> lock(_mutex); _queue.emplace_back(std::move(r)); } private: std::vector<Resource> _queue; std::mutex _mutex; std::function<Resource()> _initializer = initializerT; }; //============================================================================== template<typename Resource> using UniqueResourcePool = ResourcePool<std::unique_ptr<Resource>, &std::make_unique<Resource>>; template<typename Resource> std::unique_ptr<Resource> initialize_unique_null() { return nullptr; } template<typename Resource> using SharedResourcePool = ResourcePool<std::shared_ptr<Resource>, &std::make_shared<Resource>>; template<typename Resource> std::shared_ptr<Resource> initialize_shared_null() { return nullptr; } } // namespace soss #endif // SOSS__MESSAGEUTILITIES_HPP
32.105839
83
0.660225
[ "object", "vector" ]
38a80c46e773cf7e6941d17f449c9078ffe3c927
1,530
cpp
C++
solutions/uncrossed_lines.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/uncrossed_lines.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/uncrossed_lines.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
// We write the integers of A and B (in the order they are given) on two separate horizontal lines. // Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: // A[i] == B[j]; // The line we draw does not intersect any other connecting (non-horizontal) line. // Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. // Return the maximum number of connecting lines we can draw in this way. // Example 1: // Input: A = [1,4,2], B = [1,2,4] // Output: 2 // Explanation: We can draw 2 uncrossed lines as in the diagram. // We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. // Example 2: // Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] // Output: 3 // Example 3: // Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] // Output: 2 // Note: // 1 <= A.length <= 500 // 1 <= B.length <= 500 // 1 <= A[i], B[i] <= 2000 // solution: dp class Solution { public: int maxUncrossedLines(vector<int>& A, vector<int>& B) { vector<vector<int>> dp(A.size()+1, vector<int>(B.size()+1, 0)); for (int i = 1; i <= A.size(); i++) { for (int j = 1; j <= B.size(); j++) { if (A[i-1] == B[j-1]) { dp[i][j] = 1 + dp[i-1][j-1]; } else { dp[i][j] = max(dp[i][j-1], dp[i-1][j]); } } } return dp[A.size()][B.size()]; } };
27.818182
123
0.545098
[ "vector" ]
38a969a168aaf37d7e939d1eb33364029183c8b2
12,668
hh
C++
parser/ast.hh
patrickf2000/upl
a58e3fd3f185e52d40332d4e7473ff7de8245f04
[ "BSD-3-Clause" ]
null
null
null
parser/ast.hh
patrickf2000/upl
a58e3fd3f185e52d40332d4e7473ff7de8245f04
[ "BSD-3-Clause" ]
6
2019-06-15T12:38:26.000Z
2019-06-15T13:03:05.000Z
parser/ast.hh
patrickf2000/upl
a58e3fd3f185e52d40332d4e7473ff7de8245f04
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vector> #include <string> #include <map> #include <sstream> #include <lex.hh> //Denotes the types of our nodes so we can upcast enum AstType { Scope, //Function stuff FuncDec, ExternFunc, FuncCall, End, Return, //Structure stuff Struct, StructDec, StructAcc, StructMod, //Conditional stuff If, Elif, Else, EndIf, //Loop stuff While, Loop, ForEach, //Variable stuff VarDec, VarAssign, MultiVarAssign, Id, Int, Hex, Char, Bool, Float, Int64, Int128, Int256, Float64, Float80, Float128, Float256, Str, ArrayDec, ArrayAccess, ArrayAssign, Math, //Operator Add, Sub, Mul, Div, Mod, Inc, DMul, //Logical operators And, Or, Xor }; //Holds variable information struct Var { std::string name; DataType type; bool is_array; bool is_param; //Needed for the assembler int stack_pos; int size; }; //The base of all our nodes class AstNode { public: explicit AstNode() {} explicit AstNode(AstType t) { type = t; } virtual ~AstNode() {} virtual std::string writeDot(std::string prefix = ""); std::string writeDotStd(std::string prefix, std::string val, std::string color = ""); std::string writeDotParent(std::string prefix, std::string nodeName, std::string shape = ""); AstType type; std::vector<AstNode *> children; Line ln; }; // The top-most AST node class AstTree : public AstNode { public: AstTree(std::string file) { this->file = file; } std::string writeDot(); private: std::string file; }; //The base class for nodes that have a string attribute class AstAttrNode : public AstNode { public: std::string get_name() { return name; } void set_name(std::string n) { name = n; } protected: std::string name = ""; }; //Represents a scope class AstScope : public AstAttrNode { public: AstScope() { type = AstType::Scope; } std::map<std::string, Var> vars; std::string writeDot(std::string prefix = ""); }; //The function declaration type class AstFuncDec : public AstAttrNode { public: explicit AstFuncDec() { type = AstType::FuncDec; } explicit AstFuncDec(std::string n) { type = AstType::FuncDec; name = n; } std::string writeDot(std::string prefix = ""); std::vector<Var> args; bool is_global = false; }; //Extern function declarations class AstExternFunc : public AstFuncDec { public: explicit AstExternFunc() { type = AstType::ExternFunc; } explicit AstExternFunc(std::string n) { type = AstType::ExternFunc; name = n; } std::string writeDot(std::string prefix = "") { return ""; } }; //The function call type class AstFuncCall : public AstAttrNode { public: explicit AstFuncCall() { type = AstType::FuncCall; } explicit AstFuncCall(std::string n) { type = AstType::FuncCall; name = n; } std::string writeDot(std::string prefix = ""); }; //The return keyword class AstReturn : public AstNode { public: AstReturn() { type = AstType::Return; } std::string writeDot(std::string prefix = ""); }; //Structure declarations class AstStructDec : public AstAttrNode { public: explicit AstStructDec() { type = AstType::StructDec; } explicit AstStructDec(std::string n) { type = AstType::StructDec; name = n; } std::string writeDot(std::string prefix = "") { return ""; } }; //A struct variable class AstStruct : public AstNode { public: explicit AstStruct() { type = AstType::Struct; } std::string writeDot(std::string prefix = "") { return ""; } std::string str_name = ""; //Refers to the structure being used std::string var_name = ""; //The name of our structure variable }; //A struct access class AstStructAcc : public AstStruct { public: explicit AstStructAcc() { type = AstType::StructAcc; } std::string writeDot(std::string prefix = "") { return ""; } }; //A struct modification class AstStructMod : public AstStruct { public: explicit AstStructMod() { type = AstType::StructMod; } std::string writeDot(std::string prefix = "") { return ""; } }; //The base class for conditionals class AstCond : public AstNode { public: CondOp get_op() { return op; } void set_op(CondOp o) { op = o; } AstNode *lval; AstNode *rval; private: CondOp op; }; //The If keyword class AstIf : public AstCond { public: AstIf() { type = AstType::If; } std::string writeDot(std::string prefix = "") { return ""; } }; class AstElif : public AstCond { public: AstElif() { type = AstType::Elif; } std::string writeDot(std::string prefix = "") { return ""; } }; //The else keyword class AstElse : public AstNode { public: AstElse() { type = AstType::Else; } std::string writeDot(std::string prefix = "") { return ""; } }; //The while keyword class AstWhile : public AstCond { public: AstWhile() { type = AstType::While; } std::string writeDot(std::string prefix = "") { return ""; } }; //The loop keyword class AstLoop : public AstNode { public: AstLoop() { type = AstType::Loop; } std::string writeDot(std::string prefix = "") { return ""; } AstNode *param; std::string i_var = ""; }; //The foreach keyword class AstForEach : public AstAttrNode { public: AstForEach() { type = AstType::ForEach; } std::string writeDot(std::string prefix = "") { return ""; } std::string i_var = ""; //Index std::string r_var = ""; //Range std::string i_var_in = ""; //Internal index counter }; //Variable declaration //initial value go as children class AstVarDec : public AstAttrNode { public: explicit AstVarDec() { type = AstType::VarDec; } explicit AstVarDec(std::string n) { type = AstType::VarDec; name = n; } std::string writeDot(std::string prefix = ""); DataType get_type() { return dtype; } void set_type(DataType t) { dtype = t; } protected: DataType dtype; }; //Variable assignment/operation class AstVarAssign : public AstVarDec { public: explicit AstVarAssign() { type = AstType::VarAssign; } explicit AstVarAssign(std::string n) { type = AstType::VarAssign; name = n; } std::string writeDot(std::string prefix = ""); }; //Represents a math operation class AstMath : public AstNode { public: explicit AstMath() { type = AstType::Math; } std::string writeDot(std::string prefix = ""); }; //The ID type class AstID : public AstAttrNode { public: explicit AstID() { type = AstType::Id; } explicit AstID(std::string n) { type = AstType::Id; name = n; } std::string writeDot(std::string prefix = ""); }; //The Integer type class AstInt : public AstNode { public: explicit AstInt() { type = AstType::Int; } explicit AstInt(int i) { type = AstType::Int; no = i; } int get_val() { return no; } void set_val(int i) { no = i; } std::string writeDot(std::string prefix = ""); private: int no = 0; }; //The hex type class AstHex : public AstNode { public: explicit AstHex() { type = AstType::Hex; } explicit AstHex(unsigned short b) { type = AstType::Hex; byte = b; } unsigned short get_val() { return byte; } void set_val(unsigned short b) { byte = b; } void set_val(std::string str) { std::stringstream ss(str); ss.flags(std::ios_base::hex); ss >> byte; } std::string writeDot(std::string prefix = "") { return ""; } private: unsigned short byte; }; //The char type class AstChar : public AstNode { public: explicit AstChar() { type = AstType::Char; } explicit AstChar(char c) { type = AstType::Char; ch = c; } char get_val() { return ch; } void set_val(char c) { ch = c; } std::string writeDot(std::string prefix = "") { return ""; } private: char ch = 0; }; //The bool types class AstBool : public AstNode { public: explicit AstBool() { type = AstType::Bool; } explicit AstBool(bool b) { type = AstType::Bool; val = b; } bool get_val() { return val; } void set_val(bool b) { val = b; } std::string writeDot(std::string prefix = "") { return ""; } private: bool val = false; }; //The float type class AstFloat : public AstNode { public: explicit AstFloat() { type = AstType::Float; } explicit AstFloat(float n) { type = AstType::Float; no = n; } float get_val() { return no; } void set_val(float n) { no = n; } std::string writeDot(std::string prefix = "") { return ""; } protected: float no = 0; }; //The int-64 type //Holds two integer types class AstInt64 : public AstVarDec { public: explicit AstInt64() { type = AstType::Int64; dtype = DataType::Int64; } std::string writeDot(std::string prefix = "") { return ""; } }; //The int-128 type //Tells the compiler to use SSE extensions (with integers) class AstInt128 : public AstVarDec { public: explicit AstInt128() { type = AstType::Int128; dtype = DataType::Int128; } std::string writeDot(std::string prefix = "") { return ""; } }; //The int-256 type //Tells the compiler to use AVX extensions (with integers) class AstInt256 : public AstVarDec { public: explicit AstInt256() { type = AstType::Int256; dtype = DataType::Int256; } std::string writeDot(std::string prefix = "") { return ""; } }; //The float-64 type //Holds two floating-point values class AstFloat64 : public AstVarDec { public: explicit AstFloat64() { type = AstType::Float64; dtype = DataType::Float64; } std::string writeDot(std::string prefix = "") { return ""; } }; //The float-80 type //This tells the compiler to use the FPU unit, which handles // 80-bit types (hence the name) class AstFloat80: public AstFloat { public: explicit AstFloat80() { type = AstType::Float80; } explicit AstFloat80(double n) { type = AstType::Float80; no = n; } std::string writeDot(std::string prefix = "") { return ""; } }; //The float-128 type //Tells the compiler to use SSE extensions class AstFloat128 : public AstVarDec { public: explicit AstFloat128() { type = AstType::Float128; dtype = DataType::Float128; } std::string writeDot(std::string prefix = "") { return ""; } }; //The float-256 type //Tells the compiler to use AVX extensions class AstFloat256 : public AstVarDec { public: explicit AstFloat256() { type = AstType::Float256; dtype = DataType::Float256; } std::string writeDot(std::string prefix = "") { return ""; } }; //The string type class AstString : public AstNode { public: explicit AstString() { type = AstType::Str; } explicit AstString(std::string s) { type = AstType::Str; val = s; } std::string get_val() { return val; } void set_val(std::string s) { val = s; } std::string writeDot(std::string prefix = ""); private: std::string val = ""; }; //Mutli-variable assignment class AstMultiVarAssign : public AstNode { public: explicit AstMultiVarAssign() { type = AstType::MultiVarAssign; } std::string writeDot(std::string prefix = "") { return ""; } std::vector<AstID *> vars; }; //The array type class AstArrayDec : public AstVarDec { public: explicit AstArrayDec() { type = AstType::ArrayDec; } int get_size() { return size; } void set_size(int s) { size = s; } std::string writeDot(std::string prefix = "") { return ""; } private: int size; }; //Array access class AstArrayAcc : public AstVarDec { public: explicit AstArrayAcc() { type = AstType::ArrayAccess; } explicit AstArrayAcc(std::string n) { type = AstType::ArrayAccess; name = n; } std::string writeDot(std::string prefix = "") { return ""; } }; //Array assignment class AstArrayAssign : public AstVarDec { public: explicit AstArrayAssign() { type = AstType::ArrayAssign; } explicit AstArrayAssign(std::string n) { type = AstType::ArrayAssign; name = n; } std::string writeDot(std::string prefix = "") { return ""; } AstNode *index; };
22.146853
97
0.603805
[ "shape", "vector" ]
38b74a0c48116ecde1c93f29402d104841c1ce44
1,670
cpp
C++
iOS/G3MiOSSDK/Commons/Cameras/CameraRenderer.cpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
1
2016-08-23T10:29:44.000Z
2016-08-23T10:29:44.000Z
iOS/G3MiOSSDK/Commons/Cameras/CameraRenderer.cpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MiOSSDK/Commons/Cameras/CameraRenderer.cpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
// // CameraRenderer.cpp // G3MiOSSDK // // Created by Agustin Trujillo Pino on 30/07/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "CameraRenderer.hpp" #include "Camera.hpp" #include "CameraEventHandler.hpp" #include "TouchEvent.hpp" CameraRenderer::~CameraRenderer() { delete _cameraContext; const int handlersSize = _handlers.size(); for (int i = 0; i < handlersSize; i++) { CameraEventHandler* handler = _handlers[i]; delete handler; } } void CameraRenderer::render(const G3MRenderContext* rc, GLState* glState) { // create the CameraContext if (_cameraContext == NULL) { _cameraContext = new CameraContext(None, rc->getNextCamera()); } // render camera object // rc->getCurrentCamera()->render(rc, parentState); const int handlersSize = _handlers.size(); for (unsigned int i = 0; i < handlersSize; i++) { _handlers[i]->render(rc, _cameraContext); } } bool CameraRenderer::onTouchEvent(const G3MEventContext* ec, const TouchEvent* touchEvent) { if (_processTouchEvents) { // abort all the camera effect currently running if (touchEvent->getType() == Down) { EffectTarget* target = _cameraContext->getNextCamera()->getEffectTarget(); ec->getEffectsScheduler()->cancelAllEffectsFor(target); } // pass the event to all the handlers const int handlersSize = _handlers.size(); for (unsigned int i = 0; i < handlersSize; i++) { if (_handlers[i]->onTouchEvent(ec, touchEvent, _cameraContext)) { return true; } } } // if no handler processed the event, return not-handled return false; }
27.833333
80
0.672455
[ "render", "object" ]
38bac1200c28faa23ea5bdc3ca79d7ab01f9a712
211,279
cpp
C++
B2G/gecko/content/base/src/nsContentUtils.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/content/base/src/nsContentUtils.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/content/base/src/nsContentUtils.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 sw=2 et tw=78: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A namespace class for static layout utilities. */ #include "mozilla/Util.h" #include "jsapi.h" #include "jsdbgapi.h" #include "jsfriendapi.h" #include <math.h> #include "Layers.h" #include "nsJSUtils.h" #include "nsCOMPtr.h" #include "nsAString.h" #include "nsPrintfCString.h" #include "nsIScriptGlobalObject.h" #include "nsIScriptContext.h" #include "nsDOMCID.h" #include "nsContentUtils.h" #include "nsIXPConnect.h" #include "nsIContent.h" #include "mozilla/dom/Element.h" #include "nsIDocument.h" #include "nsINodeInfo.h" #include "nsIIdleService.h" #include "nsIDOMDocument.h" #include "nsIDOMNodeList.h" #include "nsIDOMNode.h" #include "nsIIOService.h" #include "nsNetCID.h" #include "nsNetUtil.h" #include "nsIScriptSecurityManager.h" #include "nsPIDOMWindow.h" #include "nsIJSContextStack.h" #include "nsIDocShell.h" #include "nsIDocShellTreeItem.h" #include "nsParserCIID.h" #include "nsIParser.h" #include "nsIFragmentContentSink.h" #include "nsIContentSink.h" #include "nsContentList.h" #include "nsIHTMLDocument.h" #include "nsIDOMHTMLFormElement.h" #include "nsIDOMHTMLElement.h" #include "nsIForm.h" #include "nsIFormControl.h" #include "nsGkAtoms.h" #include "imgIDecoderObserver.h" #include "imgIRequest.h" #include "imgIContainer.h" #include "imgILoader.h" #include "nsDocShellCID.h" #include "nsIImageLoadingContent.h" #include "nsIInterfaceRequestor.h" #include "nsIInterfaceRequestorUtils.h" #include "nsILoadGroup.h" #include "nsIObserver.h" #include "nsIObserverService.h" #include "nsContentPolicyUtils.h" #include "nsNodeInfoManager.h" #include "nsCRT.h" #include "nsIDOMEvent.h" #include "nsIDOMEventTarget.h" #ifdef MOZ_XTF #include "nsIXTFService.h" static NS_DEFINE_CID(kXTFServiceCID, NS_XTFSERVICE_CID); #endif #include "nsIMIMEService.h" #include "nsLWBrkCIID.h" #include "nsILineBreaker.h" #include "nsIWordBreaker.h" #include "nsUnicodeProperties.h" #include "harfbuzz/hb.h" #include "nsIJSRuntimeService.h" #include "nsBindingManager.h" #include "nsIURI.h" #include "nsIURL.h" #include "nsICharsetConverterManager.h" #include "nsEventListenerManager.h" #include "nsAttrName.h" #include "nsIDOMUserDataHandler.h" #include "nsContentCreatorFunctions.h" #include "nsMutationEvent.h" #include "nsIMEStateManager.h" #include "nsError.h" #include "nsUnicharUtilCIID.h" #include "nsINativeKeyBindings.h" #include "nsXULPopupManager.h" #include "nsIPermissionManager.h" #include "nsIScriptObjectPrincipal.h" #include "nsNullPrincipal.h" #include "nsIRunnable.h" #include "nsDOMJSUtils.h" #include "nsGenericHTMLElement.h" #include "nsAttrValue.h" #include "nsAttrValueInlines.h" #include "nsReferencedElement.h" #include "nsIDragService.h" #include "nsIChannelEventSink.h" #include "nsIAsyncVerifyRedirectCallback.h" #include "nsIOfflineCacheUpdate.h" #include "nsCPrefetchService.h" #include "nsIChromeRegistry.h" #include "nsEventDispatcher.h" #include "nsIDOMXULCommandEvent.h" #include "nsDOMDataTransfer.h" #include "nsHtml5Module.h" #include "nsPresContext.h" #include "nsLayoutStatics.h" #include "nsFocusManager.h" #include "nsTextEditorState.h" #include "nsIPluginHost.h" #include "nsICategoryManager.h" #include "nsIViewManager.h" #include "nsEventStateManager.h" #include "nsIDOMHTMLInputElement.h" #include "nsParserConstants.h" #include "nsIWebNavigation.h" #include "nsILoadContext.h" #include "nsTextFragment.h" #include "mozilla/Selection.h" #include "nsSVGUtils.h" #include "nsISVGChildFrame.h" #include "nsRenderingContext.h" #include "gfxSVGGlyphs.h" #include "mozilla/dom/EncodingUtils.h" #ifdef IBMBIDI #include "nsIBidiKeyboard.h" #endif #include "nsCycleCollectionParticipant.h" // for ReportToConsole #include "nsIStringBundle.h" #include "nsIScriptError.h" #include "nsIConsoleService.h" #include "mozAutoDocUpdate.h" #include "imgICache.h" #include "imgLoader.h" #include "xpcprivate.h" // nsXPConnect #include "nsScriptSecurityManager.h" #include "nsIChannelPolicy.h" #include "nsChannelPolicy.h" #include "nsIContentSecurityPolicy.h" #include "nsContentDLF.h" #ifdef MOZ_MEDIA #include "nsHTMLMediaElement.h" #endif #include "nsDOMTouchEvent.h" #include "nsIContentViewer.h" #include "nsIObjectLoadingContent.h" #include "nsCCUncollectableMarker.h" #include "mozilla/Base64.h" #include "mozilla/Preferences.h" #include "nsDOMMutationObserver.h" #include "nsIDOMDocumentType.h" #include "nsCharSeparatedTokenizer.h" #include "nsICharsetDetector.h" #include "nsICharsetDetectionObserver.h" #include "nsIPlatformCharset.h" #include "nsIEditor.h" #include "nsIEditorDocShell.h" #include "mozilla/Attributes.h" #include "nsIParserService.h" #include "nsIDOMScriptObjectFactory.h" #include "nsSandboxFlags.h" #include "nsWrapperCacheInlines.h" #include "nsViewportInfo.h" extern "C" int MOZ_XMLTranslateEntity(const char* ptr, const char* end, const char** next, PRUnichar* result); extern "C" int MOZ_XMLCheckQName(const char* ptr, const char* end, int ns_aware, const char** colon); using namespace mozilla::dom; using namespace mozilla::layers; using namespace mozilla::widget; using namespace mozilla; const char kLoadAsData[] = "loadAsData"; nsIDOMScriptObjectFactory *nsContentUtils::sDOMScriptObjectFactory = nullptr; nsIXPConnect *nsContentUtils::sXPConnect; nsIScriptSecurityManager *nsContentUtils::sSecurityManager; nsIThreadJSContextStack *nsContentUtils::sThreadJSContextStack; nsIParserService *nsContentUtils::sParserService = nullptr; nsINameSpaceManager *nsContentUtils::sNameSpaceManager; nsIIOService *nsContentUtils::sIOService; #ifdef MOZ_XTF nsIXTFService *nsContentUtils::sXTFService = nullptr; #endif imgILoader *nsContentUtils::sImgLoader; imgILoader *nsContentUtils::sPrivateImgLoader; imgICache *nsContentUtils::sImgCache; imgICache *nsContentUtils::sPrivateImgCache; nsIConsoleService *nsContentUtils::sConsoleService; nsDataHashtable<nsISupportsHashKey, EventNameMapping>* nsContentUtils::sAtomEventTable = nullptr; nsDataHashtable<nsStringHashKey, EventNameMapping>* nsContentUtils::sStringEventTable = nullptr; nsCOMArray<nsIAtom>* nsContentUtils::sUserDefinedEvents = nullptr; nsIStringBundleService *nsContentUtils::sStringBundleService; nsIStringBundle *nsContentUtils::sStringBundles[PropertiesFile_COUNT]; nsIContentPolicy *nsContentUtils::sContentPolicyService; bool nsContentUtils::sTriedToGetContentPolicy = false; nsILineBreaker *nsContentUtils::sLineBreaker; nsIWordBreaker *nsContentUtils::sWordBreaker; #ifdef IBMBIDI nsIBidiKeyboard *nsContentUtils::sBidiKeyboard = nullptr; #endif uint32_t nsContentUtils::sScriptBlockerCount = 0; #ifdef DEBUG uint32_t nsContentUtils::sDOMNodeRemovedSuppressCount = 0; #endif uint32_t nsContentUtils::sMicroTaskLevel = 0; nsTArray< nsCOMPtr<nsIRunnable> >* nsContentUtils::sBlockedScriptRunners = nullptr; uint32_t nsContentUtils::sRunnersCountAtFirstBlocker = 0; nsIInterfaceRequestor* nsContentUtils::sSameOriginChecker = nullptr; bool nsContentUtils::sIsHandlingKeyBoardEvent = false; bool nsContentUtils::sAllowXULXBL_for_file = false; nsString* nsContentUtils::sShiftText = nullptr; nsString* nsContentUtils::sControlText = nullptr; nsString* nsContentUtils::sMetaText = nullptr; nsString* nsContentUtils::sOSText = nullptr; nsString* nsContentUtils::sAltText = nullptr; nsString* nsContentUtils::sModifierSeparator = nullptr; bool nsContentUtils::sInitialized = false; bool nsContentUtils::sIsFullScreenApiEnabled = false; bool nsContentUtils::sTrustedFullScreenOnly = true; bool nsContentUtils::sIsIdleObserverAPIEnabled = false; uint32_t nsContentUtils::sHandlingInputTimeout = 1000; nsHtml5StringParser* nsContentUtils::sHTMLFragmentParser = nullptr; nsIParser* nsContentUtils::sXMLFragmentParser = nullptr; nsIFragmentContentSink* nsContentUtils::sXMLFragmentSink = nullptr; bool nsContentUtils::sFragmentParsingActive = false; namespace { static const char kJSStackContractID[] = "@mozilla.org/js/xpc/ContextStack;1"; static NS_DEFINE_CID(kParserServiceCID, NS_PARSERSERVICE_CID); static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID); static PLDHashTable sEventListenerManagersHash; class EventListenerManagerMapEntry : public PLDHashEntryHdr { public: EventListenerManagerMapEntry(const void *aKey) : mKey(aKey) { } ~EventListenerManagerMapEntry() { NS_ASSERTION(!mListenerManager, "caller must release and disconnect ELM"); } private: const void *mKey; // must be first, to look like PLDHashEntryStub public: nsRefPtr<nsEventListenerManager> mListenerManager; }; static bool EventListenerManagerHashInitEntry(PLDHashTable *table, PLDHashEntryHdr *entry, const void *key) { // Initialize the entry with placement new new (entry) EventListenerManagerMapEntry(key); return true; } static void EventListenerManagerHashClearEntry(PLDHashTable *table, PLDHashEntryHdr *entry) { EventListenerManagerMapEntry *lm = static_cast<EventListenerManagerMapEntry *>(entry); // Let the EventListenerManagerMapEntry clean itself up... lm->~EventListenerManagerMapEntry(); } class SameOriginChecker MOZ_FINAL : public nsIChannelEventSink, public nsIInterfaceRequestor { NS_DECL_ISUPPORTS NS_DECL_NSICHANNELEVENTSINK NS_DECL_NSIINTERFACEREQUESTOR }; class CharsetDetectionObserver MOZ_FINAL : public nsICharsetDetectionObserver { public: NS_DECL_ISUPPORTS NS_IMETHOD Notify(const char *aCharset, nsDetectionConfident aConf) { mCharset = aCharset; return NS_OK; } const nsACString& GetResult() const { return mCharset; } private: nsCString mCharset; }; } // anonymous namespace /* static */ TimeDuration nsContentUtils::HandlingUserInputTimeout() { return TimeDuration::FromMilliseconds(sHandlingInputTimeout); } // static nsresult nsContentUtils::Init() { if (sInitialized) { NS_WARNING("Init() called twice"); return NS_OK; } nsresult rv = NS_GetNameSpaceManager(&sNameSpaceManager); NS_ENSURE_SUCCESS(rv, rv); nsXPConnect* xpconnect = nsXPConnect::GetXPConnect(); NS_ENSURE_TRUE(xpconnect, NS_ERROR_FAILURE); sXPConnect = xpconnect; sThreadJSContextStack = xpconnect; sSecurityManager = nsScriptSecurityManager::GetScriptSecurityManager(); if(!sSecurityManager) return NS_ERROR_FAILURE; NS_ADDREF(sSecurityManager); rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService); if (NS_FAILED(rv)) { // This makes life easier, but we can live without it. sIOService = nullptr; } rv = CallGetService(NS_LBRK_CONTRACTID, &sLineBreaker); NS_ENSURE_SUCCESS(rv, rv); rv = CallGetService(NS_WBRK_CONTRACTID, &sWordBreaker); NS_ENSURE_SUCCESS(rv, rv); if (!InitializeEventTable()) return NS_ERROR_FAILURE; if (!sEventListenerManagersHash.ops) { static PLDHashTableOps hash_table_ops = { PL_DHashAllocTable, PL_DHashFreeTable, PL_DHashVoidPtrKeyStub, PL_DHashMatchEntryStub, PL_DHashMoveEntryStub, EventListenerManagerHashClearEntry, PL_DHashFinalizeStub, EventListenerManagerHashInitEntry }; if (!PL_DHashTableInit(&sEventListenerManagersHash, &hash_table_ops, nullptr, sizeof(EventListenerManagerMapEntry), 16)) { sEventListenerManagersHash.ops = nullptr; return NS_ERROR_OUT_OF_MEMORY; } } sBlockedScriptRunners = new nsTArray< nsCOMPtr<nsIRunnable> >; Preferences::AddBoolVarCache(&sAllowXULXBL_for_file, "dom.allow_XUL_XBL_for_file"); Preferences::AddBoolVarCache(&sIsFullScreenApiEnabled, "full-screen-api.enabled"); Preferences::AddBoolVarCache(&sTrustedFullScreenOnly, "full-screen-api.allow-trusted-requests-only"); sIsIdleObserverAPIEnabled = Preferences::GetBool("dom.idle-observers-api.enabled", true); Preferences::AddUintVarCache(&sHandlingInputTimeout, "dom.event.handling-user-input-time-limit", 1000); nsGenericElement::InitCCCallbacks(); sInitialized = true; return NS_OK; } void nsContentUtils::GetShiftText(nsAString& text) { if (!sShiftText) InitializeModifierStrings(); text.Assign(*sShiftText); } void nsContentUtils::GetControlText(nsAString& text) { if (!sControlText) InitializeModifierStrings(); text.Assign(*sControlText); } void nsContentUtils::GetMetaText(nsAString& text) { if (!sMetaText) InitializeModifierStrings(); text.Assign(*sMetaText); } void nsContentUtils::GetOSText(nsAString& text) { if (!sOSText) { InitializeModifierStrings(); } text.Assign(*sOSText); } void nsContentUtils::GetAltText(nsAString& text) { if (!sAltText) InitializeModifierStrings(); text.Assign(*sAltText); } void nsContentUtils::GetModifierSeparatorText(nsAString& text) { if (!sModifierSeparator) InitializeModifierStrings(); text.Assign(*sModifierSeparator); } void nsContentUtils::InitializeModifierStrings() { //load the display strings for the keyboard accelerators nsCOMPtr<nsIStringBundleService> bundleService = mozilla::services::GetStringBundleService(); nsCOMPtr<nsIStringBundle> bundle; DebugOnly<nsresult> rv = NS_OK; if (bundleService) { rv = bundleService->CreateBundle( "chrome://global-platform/locale/platformKeys.properties", getter_AddRefs(bundle)); } NS_ASSERTION(NS_SUCCEEDED(rv) && bundle, "chrome://global/locale/platformKeys.properties could not be loaded"); nsXPIDLString shiftModifier; nsXPIDLString metaModifier; nsXPIDLString osModifier; nsXPIDLString altModifier; nsXPIDLString controlModifier; nsXPIDLString modifierSeparator; if (bundle) { //macs use symbols for each modifier key, so fetch each from the bundle, which also covers i18n bundle->GetStringFromName(NS_LITERAL_STRING("VK_SHIFT").get(), getter_Copies(shiftModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_META").get(), getter_Copies(metaModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_WIN").get(), getter_Copies(osModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_ALT").get(), getter_Copies(altModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("VK_CONTROL").get(), getter_Copies(controlModifier)); bundle->GetStringFromName(NS_LITERAL_STRING("MODIFIER_SEPARATOR").get(), getter_Copies(modifierSeparator)); } //if any of these don't exist, we get an empty string sShiftText = new nsString(shiftModifier); sMetaText = new nsString(metaModifier); sOSText = new nsString(osModifier); sAltText = new nsString(altModifier); sControlText = new nsString(controlModifier); sModifierSeparator = new nsString(modifierSeparator); } bool nsContentUtils::sImgLoaderInitialized; void nsContentUtils::InitImgLoader() { sImgLoaderInitialized = true; // Ignore failure and just don't load images nsresult rv = CallCreateInstance("@mozilla.org/image/loader;1", &sImgLoader); NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "Creation should have succeeded"); rv = CallCreateInstance("@mozilla.org/image/loader;1", &sPrivateImgLoader); NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "Creation should have succeeded"); rv = CallQueryInterface(sImgLoader, &sImgCache); NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "imgICache and imgILoader should be paired"); rv = CallQueryInterface(sPrivateImgLoader, &sPrivateImgCache); NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "imgICache and imgILoader should be paired"); sPrivateImgCache->RespectPrivacyNotifications(); } bool nsContentUtils::InitializeEventTable() { NS_ASSERTION(!sAtomEventTable, "EventTable already initialized!"); NS_ASSERTION(!sStringEventTable, "EventTable already initialized!"); static const EventNameMapping eventArray[] = { #define EVENT(name_, _id, _type, _struct) \ { nsGkAtoms::on##name_, _id, _type, _struct }, #define WINDOW_ONLY_EVENT EVENT #define NON_IDL_EVENT EVENT #include "nsEventNameList.h" #undef WINDOW_ONLY_EVENT #undef EVENT { nullptr } }; sAtomEventTable = new nsDataHashtable<nsISupportsHashKey, EventNameMapping>; sStringEventTable = new nsDataHashtable<nsStringHashKey, EventNameMapping>; sUserDefinedEvents = new nsCOMArray<nsIAtom>(64); sAtomEventTable->Init(int(ArrayLength(eventArray) / 0.75) + 1); sStringEventTable->Init(int(ArrayLength(eventArray) / 0.75) + 1); // Subtract one from the length because of the trailing null for (uint32_t i = 0; i < ArrayLength(eventArray) - 1; ++i) { sAtomEventTable->Put(eventArray[i].mAtom, eventArray[i]); sStringEventTable->Put(Substring(nsDependentAtomString(eventArray[i].mAtom), 2), eventArray[i]); } return true; } void nsContentUtils::InitializeTouchEventTable() { static bool sEventTableInitialized = false; if (!sEventTableInitialized && sAtomEventTable && sStringEventTable) { sEventTableInitialized = true; static const EventNameMapping touchEventArray[] = { #define EVENT(name_, _id, _type, _struct) #define TOUCH_EVENT(name_, _id, _type, _struct) \ { nsGkAtoms::on##name_, _id, _type, _struct }, #include "nsEventNameList.h" #undef TOUCH_EVENT #undef EVENT { nullptr } }; // Subtract one from the length because of the trailing null for (uint32_t i = 0; i < ArrayLength(touchEventArray) - 1; ++i) { sAtomEventTable->Put(touchEventArray[i].mAtom, touchEventArray[i]); sStringEventTable->Put(Substring(nsDependentAtomString(touchEventArray[i].mAtom), 2), touchEventArray[i]); } } } static bool Is8bit(const nsAString& aString) { static const PRUnichar EIGHT_BIT = PRUnichar(~0x00FF); nsAString::const_iterator done_reading; aString.EndReading(done_reading); // for each chunk of |aString|... uint32_t fragmentLength = 0; nsAString::const_iterator iter; for (aString.BeginReading(iter); iter != done_reading; iter.advance(int32_t(fragmentLength))) { fragmentLength = uint32_t(iter.size_forward()); const PRUnichar* c = iter.get(); const PRUnichar* fragmentEnd = c + fragmentLength; // for each character in this chunk... while (c < fragmentEnd) { if (*c++ & EIGHT_BIT) { return false; } } } return true; } nsresult nsContentUtils::Btoa(const nsAString& aBinaryData, nsAString& aAsciiBase64String) { if (!Is8bit(aBinaryData)) { aAsciiBase64String.Truncate(); return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } return Base64Encode(aBinaryData, aAsciiBase64String); } nsresult nsContentUtils::Atob(const nsAString& aAsciiBase64String, nsAString& aBinaryData) { if (!Is8bit(aAsciiBase64String)) { aBinaryData.Truncate(); return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } nsresult rv = Base64Decode(aAsciiBase64String, aBinaryData); if (NS_FAILED(rv) && rv == NS_ERROR_INVALID_ARG) { return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } return rv; } bool nsContentUtils::IsAutocompleteEnabled(nsIDOMHTMLInputElement* aInput) { NS_PRECONDITION(aInput, "aInput should not be null!"); nsAutoString autocomplete; aInput->GetAutocomplete(autocomplete); if (autocomplete.IsEmpty()) { nsCOMPtr<nsIDOMHTMLFormElement> form; aInput->GetForm(getter_AddRefs(form)); if (!form) { return true; } form->GetAutocomplete(autocomplete); } return autocomplete.EqualsLiteral("on"); } #define SKIP_WHITESPACE(iter, end_iter, end_res) \ while ((iter) != (end_iter) && nsCRT::IsAsciiSpace(*(iter))) { \ ++(iter); \ } \ if ((iter) == (end_iter)) { \ return (end_res); \ } #define SKIP_ATTR_NAME(iter, end_iter) \ while ((iter) != (end_iter) && !nsCRT::IsAsciiSpace(*(iter)) && \ *(iter) != '=') { \ ++(iter); \ } bool nsContentUtils::GetPseudoAttributeValue(const nsString& aSource, nsIAtom *aName, nsAString& aValue) { aValue.Truncate(); const PRUnichar *start = aSource.get(); const PRUnichar *end = start + aSource.Length(); const PRUnichar *iter; while (start != end) { SKIP_WHITESPACE(start, end, false) iter = start; SKIP_ATTR_NAME(iter, end) if (start == iter) { return false; } // Remember the attr name. const nsDependentSubstring & attrName = Substring(start, iter); // Now check whether this is a valid name="value" pair. start = iter; SKIP_WHITESPACE(start, end, false) if (*start != '=') { // No '=', so this is not a name="value" pair. We don't know // what it is, and we have no way to handle it. return false; } // Have to skip the value. ++start; SKIP_WHITESPACE(start, end, false) PRUnichar q = *start; if (q != kQuote && q != kApostrophe) { // Not a valid quoted value, so bail. return false; } ++start; // Point to the first char of the value. iter = start; while (iter != end && *iter != q) { ++iter; } if (iter == end) { // Oops, unterminated quoted string. return false; } // At this point attrName holds the name of the "attribute" and // the value is between start and iter. if (aName->Equals(attrName)) { // We'll accumulate as many characters as possible (until we hit either // the end of the string or the beginning of an entity). Chunks will be // delimited by start and chunkEnd. const PRUnichar *chunkEnd = start; while (chunkEnd != iter) { if (*chunkEnd == kLessThan) { aValue.Truncate(); return false; } if (*chunkEnd == kAmpersand) { aValue.Append(start, chunkEnd - start); // Point to first character after the ampersand. ++chunkEnd; const PRUnichar *afterEntity = nullptr; PRUnichar result[2]; uint32_t count = MOZ_XMLTranslateEntity(reinterpret_cast<const char*>(chunkEnd), reinterpret_cast<const char*>(iter), reinterpret_cast<const char**>(&afterEntity), result); if (count == 0) { aValue.Truncate(); return false; } aValue.Append(result, count); // Advance to after the entity and begin a new chunk. start = chunkEnd = afterEntity; } else { ++chunkEnd; } } // Append remainder. aValue.Append(start, iter - start); return true; } // Resume scanning after the end of the attribute value (past the quote // char). start = iter + 1; } return false; } bool nsContentUtils::IsJavaScriptLanguage(const nsString& aName, uint32_t *aFlags) { JSVersion version = JSVERSION_UNKNOWN; if (aName.LowerCaseEqualsLiteral("javascript") || aName.LowerCaseEqualsLiteral("livescript") || aName.LowerCaseEqualsLiteral("mocha")) { version = JSVERSION_DEFAULT; } else if (aName.LowerCaseEqualsLiteral("javascript1.0")) { version = JSVERSION_1_0; } else if (aName.LowerCaseEqualsLiteral("javascript1.1")) { version = JSVERSION_1_1; } else if (aName.LowerCaseEqualsLiteral("javascript1.2")) { version = JSVERSION_1_2; } else if (aName.LowerCaseEqualsLiteral("javascript1.3")) { version = JSVERSION_1_3; } else if (aName.LowerCaseEqualsLiteral("javascript1.4")) { version = JSVERSION_1_4; } else if (aName.LowerCaseEqualsLiteral("javascript1.5")) { version = JSVERSION_1_5; } else if (aName.LowerCaseEqualsLiteral("javascript1.6")) { version = JSVERSION_1_6; } else if (aName.LowerCaseEqualsLiteral("javascript1.7")) { version = JSVERSION_1_7; } else if (aName.LowerCaseEqualsLiteral("javascript1.8")) { version = JSVERSION_1_8; } if (version == JSVERSION_UNKNOWN) { return false; } *aFlags = version; return true; } JSVersion nsContentUtils::ParseJavascriptVersion(const nsAString& aVersionStr) { if (aVersionStr.Length() != 3 || aVersionStr[0] != '1' || aVersionStr[1] != '.') { return JSVERSION_UNKNOWN; } switch (aVersionStr[2]) { case '0': return JSVERSION_1_0; case '1': return JSVERSION_1_1; case '2': return JSVERSION_1_2; case '3': return JSVERSION_1_3; case '4': return JSVERSION_1_4; case '5': return JSVERSION_1_5; case '6': return JSVERSION_1_6; case '7': return JSVERSION_1_7; case '8': return JSVERSION_1_8; default: return JSVERSION_UNKNOWN; } } void nsContentUtils::SplitMimeType(const nsAString& aValue, nsString& aType, nsString& aParams) { aType.Truncate(); aParams.Truncate(); int32_t semiIndex = aValue.FindChar(PRUnichar(';')); if (-1 != semiIndex) { aType = Substring(aValue, 0, semiIndex); aParams = Substring(aValue, semiIndex + 1, aValue.Length() - (semiIndex + 1)); aParams.StripWhitespace(); } else { aType = aValue; } aType.StripWhitespace(); } nsresult nsContentUtils::IsUserIdle(uint32_t aRequestedIdleTimeInMS, bool* aUserIsIdle) { nsresult rv; nsCOMPtr<nsIIdleService> idleService = do_GetService("@mozilla.org/widget/idleservice;1", &rv); NS_ENSURE_SUCCESS(rv, rv); uint32_t idleTimeInMS; rv = idleService->GetIdleTime(&idleTimeInMS); NS_ENSURE_SUCCESS(rv, rv); *aUserIsIdle = idleTimeInMS >= aRequestedIdleTimeInMS; return NS_OK; } /** * Access a cached parser service. Don't addref. We need only one * reference to it and this class has that one. */ /* static */ nsIParserService* nsContentUtils::GetParserService() { // XXX: This isn't accessed from several threads, is it? if (!sParserService) { // Lock, recheck sCachedParserService and aquire if this should be // safe for multiple threads. nsresult rv = CallGetService(kParserServiceCID, &sParserService); if (NS_FAILED(rv)) { sParserService = nullptr; } } return sParserService; } /** * A helper function that parses a sandbox attribute (of an <iframe> or * a CSP directive) and converts it to the set of flags used internally. * * @param aAttribute the value of the sandbox attribute * @return the set of flags */ uint32_t nsContentUtils::ParseSandboxAttributeToFlags(const nsAString& aSandboxAttrValue) { // If there's a sandbox attribute at all (and there is if this is being // called), start off by setting all the restriction flags. uint32_t out = SANDBOXED_NAVIGATION | SANDBOXED_TOPLEVEL_NAVIGATION | SANDBOXED_PLUGINS | SANDBOXED_ORIGIN | SANDBOXED_FORMS | SANDBOXED_SCRIPTS | SANDBOXED_AUTOMATIC_FEATURES | SANDBOXED_POINTER_LOCK; if (!aSandboxAttrValue.IsEmpty()) { // The separator optional flag is used because the HTML5 spec says any // whitespace is ok as a separator, which is what this does. HTMLSplitOnSpacesTokenizer tokenizer(aSandboxAttrValue, ' ', nsCharSeparatedTokenizerTemplate<nsContentUtils::IsHTMLWhitespace>::SEPARATOR_OPTIONAL); while (tokenizer.hasMoreTokens()) { nsDependentSubstring token = tokenizer.nextToken(); if (token.LowerCaseEqualsLiteral("allow-same-origin")) { out &= ~SANDBOXED_ORIGIN; } else if (token.LowerCaseEqualsLiteral("allow-forms")) { out &= ~SANDBOXED_FORMS; } else if (token.LowerCaseEqualsLiteral("allow-scripts")) { // allow-scripts removes both SANDBOXED_SCRIPTS and // SANDBOXED_AUTOMATIC_FEATURES. out &= ~SANDBOXED_SCRIPTS; out &= ~SANDBOXED_AUTOMATIC_FEATURES; } else if (token.LowerCaseEqualsLiteral("allow-top-navigation")) { out &= ~SANDBOXED_TOPLEVEL_NAVIGATION; } else if (token.LowerCaseEqualsLiteral("allow-pointer-lock")) { out &= ~SANDBOXED_POINTER_LOCK; } } } return out; } #ifdef MOZ_XTF nsIXTFService* nsContentUtils::GetXTFService() { if (!sXTFService) { nsresult rv = CallGetService(kXTFServiceCID, &sXTFService); if (NS_FAILED(rv)) { sXTFService = nullptr; } } return sXTFService; } #endif #ifdef IBMBIDI nsIBidiKeyboard* nsContentUtils::GetBidiKeyboard() { if (!sBidiKeyboard) { nsresult rv = CallGetService("@mozilla.org/widget/bidikeyboard;1", &sBidiKeyboard); if (NS_FAILED(rv)) { sBidiKeyboard = nullptr; } } return sBidiKeyboard; } #endif template <class OutputIterator> struct NormalizeNewlinesCharTraits { public: typedef typename OutputIterator::value_type value_type; public: NormalizeNewlinesCharTraits(OutputIterator& aIterator) : mIterator(aIterator) { } void writechar(typename OutputIterator::value_type aChar) { *mIterator++ = aChar; } private: OutputIterator mIterator; }; #ifdef HAVE_CPP_PARTIAL_SPECIALIZATION template <class CharT> struct NormalizeNewlinesCharTraits<CharT*> { public: typedef CharT value_type; public: NormalizeNewlinesCharTraits(CharT* aCharPtr) : mCharPtr(aCharPtr) { } void writechar(CharT aChar) { *mCharPtr++ = aChar; } private: CharT* mCharPtr; }; #else template <> struct NormalizeNewlinesCharTraits<char*> { public: typedef char value_type; public: NormalizeNewlinesCharTraits(char* aCharPtr) : mCharPtr(aCharPtr) { } void writechar(char aChar) { *mCharPtr++ = aChar; } private: char* mCharPtr; }; template <> struct NormalizeNewlinesCharTraits<PRUnichar*> { public: typedef PRUnichar value_type; public: NormalizeNewlinesCharTraits(PRUnichar* aCharPtr) : mCharPtr(aCharPtr) { } void writechar(PRUnichar aChar) { *mCharPtr++ = aChar; } private: PRUnichar* mCharPtr; }; #endif template <class OutputIterator> class CopyNormalizeNewlines { public: typedef typename OutputIterator::value_type value_type; public: CopyNormalizeNewlines(OutputIterator* aDestination, bool aLastCharCR=false) : mLastCharCR(aLastCharCR), mDestination(aDestination), mWritten(0) { } uint32_t GetCharsWritten() { return mWritten; } bool IsLastCharCR() { return mLastCharCR; } void write(const typename OutputIterator::value_type* aSource, uint32_t aSourceLength) { const typename OutputIterator::value_type* done_writing = aSource + aSourceLength; // If the last source buffer ended with a CR... if (mLastCharCR) { // ..and if the next one is a LF, then skip it since // we've already written out a newline if (aSourceLength && (*aSource == value_type('\n'))) { ++aSource; } mLastCharCR = false; } uint32_t num_written = 0; while ( aSource < done_writing ) { if (*aSource == value_type('\r')) { mDestination->writechar('\n'); ++aSource; // If we've reached the end of the buffer, record // that we wrote out a CR if (aSource == done_writing) { mLastCharCR = true; } // If the next character is a LF, skip it else if (*aSource == value_type('\n')) { ++aSource; } } else { mDestination->writechar(*aSource++); } ++num_written; } mWritten += num_written; } private: bool mLastCharCR; OutputIterator* mDestination; uint32_t mWritten; }; // static uint32_t nsContentUtils::CopyNewlineNormalizedUnicodeTo(const nsAString& aSource, uint32_t aSrcOffset, PRUnichar* aDest, uint32_t aLength, bool& aLastCharCR) { typedef NormalizeNewlinesCharTraits<PRUnichar*> sink_traits; sink_traits dest_traits(aDest); CopyNormalizeNewlines<sink_traits> normalizer(&dest_traits,aLastCharCR); nsReadingIterator<PRUnichar> fromBegin, fromEnd; copy_string(aSource.BeginReading(fromBegin).advance( int32_t(aSrcOffset) ), aSource.BeginReading(fromEnd).advance( int32_t(aSrcOffset+aLength) ), normalizer); aLastCharCR = normalizer.IsLastCharCR(); return normalizer.GetCharsWritten(); } // static uint32_t nsContentUtils::CopyNewlineNormalizedUnicodeTo(nsReadingIterator<PRUnichar>& aSrcStart, const nsReadingIterator<PRUnichar>& aSrcEnd, nsAString& aDest) { typedef nsWritingIterator<PRUnichar> WritingIterator; typedef NormalizeNewlinesCharTraits<WritingIterator> sink_traits; WritingIterator iter; aDest.BeginWriting(iter); sink_traits dest_traits(iter); CopyNormalizeNewlines<sink_traits> normalizer(&dest_traits); copy_string(aSrcStart, aSrcEnd, normalizer); return normalizer.GetCharsWritten(); } /** * This is used to determine whether a character is in one of the punctuation * mark classes which CSS says should be part of the first-letter. * See http://www.w3.org/TR/CSS2/selector.html#first-letter and * http://www.w3.org/TR/selectors/#first-letter */ // static bool nsContentUtils::IsFirstLetterPunctuation(uint32_t aChar) { uint8_t cat = mozilla::unicode::GetGeneralCategory(aChar); return (cat == HB_UNICODE_GENERAL_CATEGORY_OPEN_PUNCTUATION || // Ps cat == HB_UNICODE_GENERAL_CATEGORY_CLOSE_PUNCTUATION || // Pe cat == HB_UNICODE_GENERAL_CATEGORY_INITIAL_PUNCTUATION || // Pi cat == HB_UNICODE_GENERAL_CATEGORY_FINAL_PUNCTUATION || // Pf cat == HB_UNICODE_GENERAL_CATEGORY_OTHER_PUNCTUATION); // Po } // static bool nsContentUtils::IsFirstLetterPunctuationAt(const nsTextFragment* aFrag, uint32_t aOffset) { PRUnichar h = aFrag->CharAt(aOffset); if (!IS_SURROGATE(h)) { return IsFirstLetterPunctuation(h); } if (NS_IS_HIGH_SURROGATE(h) && aOffset + 1 < aFrag->GetLength()) { PRUnichar l = aFrag->CharAt(aOffset + 1); if (NS_IS_LOW_SURROGATE(l)) { return IsFirstLetterPunctuation(SURROGATE_TO_UCS4(h, l)); } } return false; } // static bool nsContentUtils::IsAlphanumeric(uint32_t aChar) { nsIUGenCategory::nsUGenCategory cat = mozilla::unicode::GetGenCategory(aChar); return (cat == nsIUGenCategory::kLetter || cat == nsIUGenCategory::kNumber); } // static bool nsContentUtils::IsAlphanumericAt(const nsTextFragment* aFrag, uint32_t aOffset) { PRUnichar h = aFrag->CharAt(aOffset); if (!IS_SURROGATE(h)) { return IsAlphanumeric(h); } if (NS_IS_HIGH_SURROGATE(h) && aOffset + 1 < aFrag->GetLength()) { PRUnichar l = aFrag->CharAt(aOffset + 1); if (NS_IS_LOW_SURROGATE(l)) { return IsAlphanumeric(SURROGATE_TO_UCS4(h, l)); } } return false; } /* static */ bool nsContentUtils::IsHTMLWhitespace(PRUnichar aChar) { return aChar == PRUnichar(0x0009) || aChar == PRUnichar(0x000A) || aChar == PRUnichar(0x000C) || aChar == PRUnichar(0x000D) || aChar == PRUnichar(0x0020); } /* static */ bool nsContentUtils::IsHTMLBlock(nsIAtom* aLocalName) { return (aLocalName == nsGkAtoms::address) || (aLocalName == nsGkAtoms::article) || (aLocalName == nsGkAtoms::aside) || (aLocalName == nsGkAtoms::blockquote) || (aLocalName == nsGkAtoms::center) || (aLocalName == nsGkAtoms::dir) || (aLocalName == nsGkAtoms::div) || (aLocalName == nsGkAtoms::dl) || // XXX why not dt and dd? (aLocalName == nsGkAtoms::fieldset) || (aLocalName == nsGkAtoms::figure) || // XXX shouldn't figcaption be on this list (aLocalName == nsGkAtoms::footer) || (aLocalName == nsGkAtoms::form) || (aLocalName == nsGkAtoms::h1) || (aLocalName == nsGkAtoms::h2) || (aLocalName == nsGkAtoms::h3) || (aLocalName == nsGkAtoms::h4) || (aLocalName == nsGkAtoms::h5) || (aLocalName == nsGkAtoms::h6) || (aLocalName == nsGkAtoms::header) || (aLocalName == nsGkAtoms::hgroup) || (aLocalName == nsGkAtoms::hr) || (aLocalName == nsGkAtoms::li) || (aLocalName == nsGkAtoms::listing) || (aLocalName == nsGkAtoms::menu) || (aLocalName == nsGkAtoms::multicol) || // XXX get rid of this one? (aLocalName == nsGkAtoms::nav) || (aLocalName == nsGkAtoms::ol) || (aLocalName == nsGkAtoms::p) || (aLocalName == nsGkAtoms::pre) || (aLocalName == nsGkAtoms::section) || (aLocalName == nsGkAtoms::table) || (aLocalName == nsGkAtoms::ul) || (aLocalName == nsGkAtoms::xmp); } /* static */ bool nsContentUtils::IsHTMLVoid(nsIAtom* aLocalName) { return (aLocalName == nsGkAtoms::area) || (aLocalName == nsGkAtoms::base) || (aLocalName == nsGkAtoms::basefont) || (aLocalName == nsGkAtoms::bgsound) || (aLocalName == nsGkAtoms::br) || (aLocalName == nsGkAtoms::col) || (aLocalName == nsGkAtoms::command) || (aLocalName == nsGkAtoms::embed) || (aLocalName == nsGkAtoms::frame) || (aLocalName == nsGkAtoms::hr) || (aLocalName == nsGkAtoms::img) || (aLocalName == nsGkAtoms::input) || (aLocalName == nsGkAtoms::keygen) || (aLocalName == nsGkAtoms::link) || (aLocalName == nsGkAtoms::meta) || (aLocalName == nsGkAtoms::param) || #ifdef MOZ_MEDIA (aLocalName == nsGkAtoms::source) || #endif (aLocalName == nsGkAtoms::track) || (aLocalName == nsGkAtoms::wbr); } /* static */ bool nsContentUtils::ParseIntMarginValue(const nsAString& aString, nsIntMargin& result) { nsAutoString marginStr(aString); marginStr.CompressWhitespace(true, true); if (marginStr.IsEmpty()) { return false; } int32_t start = 0, end = 0; for (int count = 0; count < 4; count++) { if ((uint32_t)end >= marginStr.Length()) return false; // top, right, bottom, left if (count < 3) end = Substring(marginStr, start).FindChar(','); else end = Substring(marginStr, start).Length(); if (end <= 0) return false; nsresult ec; int32_t val = nsString(Substring(marginStr, start, end)).ToInteger(&ec); if (NS_FAILED(ec)) return false; switch(count) { case 0: result.top = val; break; case 1: result.right = val; break; case 2: result.bottom = val; break; case 3: result.left = val; break; } start += end + 1; } return true; } // static int32_t nsContentUtils::ParseLegacyFontSize(const nsAString& aValue) { nsAString::const_iterator iter, end; aValue.BeginReading(iter); aValue.EndReading(end); while (iter != end && nsContentUtils::IsHTMLWhitespace(*iter)) { ++iter; } if (iter == end) { return 0; } bool relative = false; bool negate = false; if (*iter == PRUnichar('-')) { relative = true; negate = true; ++iter; } else if (*iter == PRUnichar('+')) { relative = true; ++iter; } if (*iter < PRUnichar('0') || *iter > PRUnichar('9')) { return 0; } // We don't have to worry about overflow, since we can bail out as soon as // we're bigger than 7. int32_t value = 0; while (iter != end && *iter >= PRUnichar('0') && *iter <= PRUnichar('9')) { value = 10*value + (*iter - PRUnichar('0')); if (value >= 7) { break; } ++iter; } if (relative) { if (negate) { value = 3 - value; } else { value = 3 + value; } } return clamped(value, 1, 7); } /* static */ void nsContentUtils::GetOfflineAppManifest(nsIDocument *aDocument, nsIURI **aURI) { Element* docElement = aDocument->GetRootElement(); if (!docElement) { return; } nsAutoString manifestSpec; docElement->GetAttr(kNameSpaceID_None, nsGkAtoms::manifest, manifestSpec); // Manifest URIs can't have fragment identifiers. if (manifestSpec.IsEmpty() || manifestSpec.FindChar('#') != kNotFound) { return; } nsContentUtils::NewURIWithDocumentCharset(aURI, manifestSpec, aDocument, aDocument->GetDocBaseURI()); } /* static */ bool nsContentUtils::OfflineAppAllowed(nsIURI *aURI) { nsCOMPtr<nsIOfflineCacheUpdateService> updateService = do_GetService(NS_OFFLINECACHEUPDATESERVICE_CONTRACTID); if (!updateService) { return false; } bool allowed; nsresult rv = updateService->OfflineAppAllowedForURI(aURI, Preferences::GetRootBranch(), &allowed); return NS_SUCCEEDED(rv) && allowed; } /* static */ bool nsContentUtils::OfflineAppAllowed(nsIPrincipal *aPrincipal) { nsCOMPtr<nsIOfflineCacheUpdateService> updateService = do_GetService(NS_OFFLINECACHEUPDATESERVICE_CONTRACTID); if (!updateService) { return false; } bool allowed; nsresult rv = updateService->OfflineAppAllowed(aPrincipal, Preferences::GetRootBranch(), &allowed); return NS_SUCCEEDED(rv) && allowed; } // static void nsContentUtils::Shutdown() { sInitialized = false; NS_IF_RELEASE(sContentPolicyService); sTriedToGetContentPolicy = false; uint32_t i; for (i = 0; i < PropertiesFile_COUNT; ++i) NS_IF_RELEASE(sStringBundles[i]); NS_IF_RELEASE(sStringBundleService); NS_IF_RELEASE(sConsoleService); NS_IF_RELEASE(sDOMScriptObjectFactory); sXPConnect = nullptr; sThreadJSContextStack = nullptr; NS_IF_RELEASE(sSecurityManager); NS_IF_RELEASE(sNameSpaceManager); NS_IF_RELEASE(sParserService); NS_IF_RELEASE(sIOService); NS_IF_RELEASE(sLineBreaker); NS_IF_RELEASE(sWordBreaker); #ifdef MOZ_XTF NS_IF_RELEASE(sXTFService); #endif NS_IF_RELEASE(sImgLoader); NS_IF_RELEASE(sPrivateImgLoader); NS_IF_RELEASE(sImgCache); NS_IF_RELEASE(sPrivateImgCache); #ifdef IBMBIDI NS_IF_RELEASE(sBidiKeyboard); #endif delete sAtomEventTable; sAtomEventTable = nullptr; delete sStringEventTable; sStringEventTable = nullptr; delete sUserDefinedEvents; sUserDefinedEvents = nullptr; if (sEventListenerManagersHash.ops) { NS_ASSERTION(sEventListenerManagersHash.entryCount == 0, "Event listener manager hash not empty at shutdown!"); // See comment above. // However, we have to handle this table differently. If it still // has entries, we want to leak it too, so that we can keep it alive // in case any elements are destroyed. Because if they are, we need // their event listener managers to be destroyed too, or otherwise // it could leave dangling references in DOMClassInfo's preserved // wrapper table. if (sEventListenerManagersHash.entryCount == 0) { PL_DHashTableFinish(&sEventListenerManagersHash); sEventListenerManagersHash.ops = nullptr; } } NS_ASSERTION(!sBlockedScriptRunners || sBlockedScriptRunners->Length() == 0, "How'd this happen?"); delete sBlockedScriptRunners; sBlockedScriptRunners = nullptr; delete sShiftText; sShiftText = nullptr; delete sControlText; sControlText = nullptr; delete sMetaText; sMetaText = nullptr; delete sOSText; sOSText = nullptr; delete sAltText; sAltText = nullptr; delete sModifierSeparator; sModifierSeparator = nullptr; NS_IF_RELEASE(sSameOriginChecker); EncodingUtils::Shutdown(); nsTextEditorState::ShutDown(); } // static bool nsContentUtils::CallerHasUniversalXPConnect() { return IsCallerChrome(); } /** * Checks whether two nodes come from the same origin. aTrustedNode is * considered 'safe' in that a user can operate on it and that it isn't * a js-object that implements nsIDOMNode. * Never call this function with the first node provided by script, it * must always be known to be a 'real' node! */ // static nsresult nsContentUtils::CheckSameOrigin(nsINode *aTrustedNode, nsIDOMNode *aUnTrustedNode) { MOZ_ASSERT(aTrustedNode); // Make sure it's a real node. nsCOMPtr<nsINode> unTrustedNode = do_QueryInterface(aUnTrustedNode); NS_ENSURE_TRUE(unTrustedNode, NS_ERROR_UNEXPECTED); return CheckSameOrigin(aTrustedNode, unTrustedNode); } nsresult nsContentUtils::CheckSameOrigin(nsINode* aTrustedNode, nsINode* unTrustedNode) { MOZ_ASSERT(aTrustedNode); MOZ_ASSERT(unTrustedNode); bool isSystem = false; nsresult rv = sSecurityManager->SubjectPrincipalIsSystem(&isSystem); NS_ENSURE_SUCCESS(rv, rv); if (isSystem) { // we're running as system, grant access to the node. return NS_OK; } /* * Get hold of each node's principal */ nsIPrincipal* trustedPrincipal = aTrustedNode->NodePrincipal(); nsIPrincipal* unTrustedPrincipal = unTrustedNode->NodePrincipal(); if (trustedPrincipal == unTrustedPrincipal) { return NS_OK; } bool equal; // XXXbz should we actually have a Subsumes() check here instead? Or perhaps // a separate method for that, with callers using one or the other? if (NS_FAILED(trustedPrincipal->Equals(unTrustedPrincipal, &equal)) || !equal) { return NS_ERROR_DOM_PROP_ACCESS_DENIED; } return NS_OK; } // static bool nsContentUtils::CanCallerAccess(nsIPrincipal* aSubjectPrincipal, nsIPrincipal* aPrincipal) { bool subsumes; nsresult rv = aSubjectPrincipal->Subsumes(aPrincipal, &subsumes); NS_ENSURE_SUCCESS(rv, false); if (subsumes) { return true; } // The subject doesn't subsume aPrincipal. Allow access only if the subject // has UniversalXPConnect. return CallerHasUniversalXPConnect(); } // static bool nsContentUtils::CanCallerAccess(nsIDOMNode *aNode) { // XXXbz why not check the IsCapabilityEnabled thing up front, and not bother // with the system principal games? But really, there should be a simpler // API here, dammit. nsCOMPtr<nsIPrincipal> subjectPrincipal; nsresult rv = sSecurityManager->GetSubjectPrincipal(getter_AddRefs(subjectPrincipal)); NS_ENSURE_SUCCESS(rv, false); if (!subjectPrincipal) { // we're running as system, grant access to the node. return true; } nsCOMPtr<nsINode> node = do_QueryInterface(aNode); NS_ENSURE_TRUE(node, false); return CanCallerAccess(subjectPrincipal, node->NodePrincipal()); } // static bool nsContentUtils::CanCallerAccess(nsPIDOMWindow* aWindow) { // XXXbz why not check the IsCapabilityEnabled thing up front, and not bother // with the system principal games? But really, there should be a simpler // API here, dammit. nsCOMPtr<nsIPrincipal> subjectPrincipal; nsresult rv = sSecurityManager->GetSubjectPrincipal(getter_AddRefs(subjectPrincipal)); NS_ENSURE_SUCCESS(rv, false); if (!subjectPrincipal) { // we're running as system, grant access to the node. return true; } nsCOMPtr<nsIScriptObjectPrincipal> scriptObject = do_QueryInterface(aWindow->IsOuterWindow() ? aWindow->GetCurrentInnerWindow() : aWindow); NS_ENSURE_TRUE(scriptObject, false); return CanCallerAccess(subjectPrincipal, scriptObject->GetPrincipal()); } //static bool nsContentUtils::InProlog(nsINode *aNode) { NS_PRECONDITION(aNode, "missing node to nsContentUtils::InProlog"); nsINode* parent = aNode->GetNodeParent(); if (!parent || !parent->IsNodeOfType(nsINode::eDOCUMENT)) { return false; } nsIDocument* doc = static_cast<nsIDocument*>(parent); nsIContent* root = doc->GetRootElement(); return !root || doc->IndexOf(aNode) < doc->IndexOf(root); } JSContext * nsContentUtils::GetContextFromDocument(nsIDocument *aDocument) { nsIScriptGlobalObject *sgo = aDocument->GetScopeObject(); if (!sgo) { // No script global, no context. return nullptr; } nsIScriptContext *scx = sgo->GetContext(); if (!scx) { // No context left in the scope... return nullptr; } return scx->GetNativeContext(); } //static void nsContentUtils::TraceSafeJSContext(JSTracer* aTrc) { if (!sThreadJSContextStack) { return; } JSContext* cx = sThreadJSContextStack->GetSafeJSContext(); if (!cx) { return; } if (JSObject* global = JS_GetGlobalObject(cx)) { JS_CALL_OBJECT_TRACER(aTrc, global, "safe context"); } } nsresult nsContentUtils::ReparentContentWrappersInScope(JSContext *cx, nsIScriptGlobalObject *aOldScope, nsIScriptGlobalObject *aNewScope) { JSObject *oldScopeObj = aOldScope->GetGlobalJSObject(); JSObject *newScopeObj = aNewScope->GetGlobalJSObject(); if (!newScopeObj || !oldScopeObj) { // We can't really do anything without the JSObjects. return NS_ERROR_NOT_AVAILABLE; } return sXPConnect->MoveWrappers(cx, oldScopeObj, newScopeObj); } nsPIDOMWindow * nsContentUtils::GetWindowFromCaller() { JSContext *cx = nullptr; sThreadJSContextStack->Peek(&cx); if (cx) { nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(nsJSUtils::GetDynamicScriptGlobal(cx)); return win; } return nullptr; } nsIDOMDocument * nsContentUtils::GetDocumentFromCaller() { JSContext *cx = nullptr; JSObject *obj = nullptr; sXPConnect->GetCaller(&cx, &obj); NS_ASSERTION(cx && obj, "Caller ensures something is running"); JSAutoCompartment ac(cx, obj); nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(nsJSUtils::GetStaticScriptGlobal(cx, obj)); if (!win) { return nullptr; } return win->GetExtantDocument(); } nsIDOMDocument * nsContentUtils::GetDocumentFromContext() { JSContext *cx = nullptr; sThreadJSContextStack->Peek(&cx); if (cx) { nsIScriptGlobalObject *sgo = nsJSUtils::GetDynamicScriptGlobal(cx); if (sgo) { nsCOMPtr<nsPIDOMWindow> pwin = do_QueryInterface(sgo); if (pwin) { return pwin->GetExtantDocument(); } } } return nullptr; } bool nsContentUtils::IsCallerChrome() { bool is_caller_chrome = false; nsresult rv = sSecurityManager->SubjectPrincipalIsSystem(&is_caller_chrome); if (NS_FAILED(rv)) { return false; } if (is_caller_chrome) { return true; } // If the check failed, look for UniversalXPConnect on the cx compartment. return xpc::IsUniversalXPConnectEnabled(GetCurrentJSContext()); } bool nsContentUtils::IsCallerTrustedForRead() { return CallerHasUniversalXPConnect(); } bool nsContentUtils::IsCallerTrustedForWrite() { return CallerHasUniversalXPConnect(); } bool nsContentUtils::IsImageSrcSetDisabled() { return Preferences::GetBool("dom.disable_image_src_set") && !IsCallerChrome(); } // static nsINode* nsContentUtils::GetCrossDocParentNode(nsINode* aChild) { NS_PRECONDITION(aChild, "The child is null!"); nsINode* parent = aChild->GetNodeParent(); if (parent || !aChild->IsNodeOfType(nsINode::eDOCUMENT)) return parent; nsIDocument* doc = static_cast<nsIDocument*>(aChild); nsIDocument* parentDoc = doc->GetParentDocument(); return parentDoc ? parentDoc->FindContentForSubDocument(doc) : nullptr; } // static bool nsContentUtils::ContentIsDescendantOf(const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor) { NS_PRECONDITION(aPossibleDescendant, "The possible descendant is null!"); NS_PRECONDITION(aPossibleAncestor, "The possible ancestor is null!"); do { if (aPossibleDescendant == aPossibleAncestor) return true; aPossibleDescendant = aPossibleDescendant->GetNodeParent(); } while (aPossibleDescendant); return false; } // static bool nsContentUtils::ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant, nsINode* aPossibleAncestor) { NS_PRECONDITION(aPossibleDescendant, "The possible descendant is null!"); NS_PRECONDITION(aPossibleAncestor, "The possible ancestor is null!"); do { if (aPossibleDescendant == aPossibleAncestor) return true; aPossibleDescendant = GetCrossDocParentNode(aPossibleDescendant); } while (aPossibleDescendant); return false; } // static nsresult nsContentUtils::GetAncestors(nsINode* aNode, nsTArray<nsINode*>& aArray) { while (aNode) { aArray.AppendElement(aNode); aNode = aNode->GetNodeParent(); } return NS_OK; } // static nsresult nsContentUtils::GetAncestorsAndOffsets(nsIDOMNode* aNode, int32_t aOffset, nsTArray<nsIContent*>* aAncestorNodes, nsTArray<int32_t>* aAncestorOffsets) { NS_ENSURE_ARG_POINTER(aNode); nsCOMPtr<nsIContent> content(do_QueryInterface(aNode)); if (!content) { return NS_ERROR_FAILURE; } if (!aAncestorNodes->IsEmpty()) { NS_WARNING("aAncestorNodes is not empty"); aAncestorNodes->Clear(); } if (!aAncestorOffsets->IsEmpty()) { NS_WARNING("aAncestorOffsets is not empty"); aAncestorOffsets->Clear(); } // insert the node itself aAncestorNodes->AppendElement(content.get()); aAncestorOffsets->AppendElement(aOffset); // insert all the ancestors nsIContent* child = content; nsIContent* parent = child->GetParent(); while (parent) { aAncestorNodes->AppendElement(parent); aAncestorOffsets->AppendElement(parent->IndexOf(child)); child = parent; parent = parent->GetParent(); } return NS_OK; } // static nsresult nsContentUtils::GetCommonAncestor(nsIDOMNode *aNode, nsIDOMNode *aOther, nsIDOMNode** aCommonAncestor) { *aCommonAncestor = nullptr; nsCOMPtr<nsINode> node1 = do_QueryInterface(aNode); nsCOMPtr<nsINode> node2 = do_QueryInterface(aOther); NS_ENSURE_TRUE(node1 && node2, NS_ERROR_UNEXPECTED); nsINode* common = GetCommonAncestor(node1, node2); NS_ENSURE_TRUE(common, NS_ERROR_NOT_AVAILABLE); return CallQueryInterface(common, aCommonAncestor); } // static nsINode* nsContentUtils::GetCommonAncestor(nsINode* aNode1, nsINode* aNode2) { if (aNode1 == aNode2) { return aNode1; } // Build the chain of parents nsAutoTArray<nsINode*, 30> parents1, parents2; do { parents1.AppendElement(aNode1); aNode1 = aNode1->GetNodeParent(); } while (aNode1); do { parents2.AppendElement(aNode2); aNode2 = aNode2->GetNodeParent(); } while (aNode2); // Find where the parent chain differs uint32_t pos1 = parents1.Length(); uint32_t pos2 = parents2.Length(); nsINode* parent = nullptr; uint32_t len; for (len = NS_MIN(pos1, pos2); len > 0; --len) { nsINode* child1 = parents1.ElementAt(--pos1); nsINode* child2 = parents2.ElementAt(--pos2); if (child1 != child2) { break; } parent = child1; } return parent; } /* static */ int32_t nsContentUtils::ComparePoints(nsINode* aParent1, int32_t aOffset1, nsINode* aParent2, int32_t aOffset2, bool* aDisconnected) { if (aParent1 == aParent2) { return aOffset1 < aOffset2 ? -1 : aOffset1 > aOffset2 ? 1 : 0; } nsAutoTArray<nsINode*, 32> parents1, parents2; nsINode* node1 = aParent1; nsINode* node2 = aParent2; do { parents1.AppendElement(node1); node1 = node1->GetNodeParent(); } while (node1); do { parents2.AppendElement(node2); node2 = node2->GetNodeParent(); } while (node2); uint32_t pos1 = parents1.Length() - 1; uint32_t pos2 = parents2.Length() - 1; bool disconnected = parents1.ElementAt(pos1) != parents2.ElementAt(pos2); if (aDisconnected) { *aDisconnected = disconnected; } if (disconnected) { NS_ASSERTION(aDisconnected, "unexpected disconnected nodes"); return 1; } // Find where the parent chains differ nsINode* parent = parents1.ElementAt(pos1); uint32_t len; for (len = NS_MIN(pos1, pos2); len > 0; --len) { nsINode* child1 = parents1.ElementAt(--pos1); nsINode* child2 = parents2.ElementAt(--pos2); if (child1 != child2) { return parent->IndexOf(child1) < parent->IndexOf(child2) ? -1 : 1; } parent = child1; } // The parent chains never differed, so one of the nodes is an ancestor of // the other NS_ASSERTION(!pos1 || !pos2, "should have run out of parent chain for one of the nodes"); if (!pos1) { nsINode* child2 = parents2.ElementAt(--pos2); return aOffset1 <= parent->IndexOf(child2) ? -1 : 1; } nsINode* child1 = parents1.ElementAt(--pos1); return parent->IndexOf(child1) < aOffset2 ? -1 : 1; } /* static */ int32_t nsContentUtils::ComparePoints(nsIDOMNode* aParent1, int32_t aOffset1, nsIDOMNode* aParent2, int32_t aOffset2, bool* aDisconnected) { nsCOMPtr<nsINode> parent1 = do_QueryInterface(aParent1); nsCOMPtr<nsINode> parent2 = do_QueryInterface(aParent2); NS_ENSURE_TRUE(parent1 && parent2, -1); return ComparePoints(parent1, aOffset1, parent2, aOffset2); } inline bool IsCharInSet(const char* aSet, const PRUnichar aChar) { PRUnichar ch; while ((ch = *aSet)) { if (aChar == PRUnichar(ch)) { return true; } ++aSet; } return false; } /** * This method strips leading/trailing chars, in given set, from string. */ // static const nsDependentSubstring nsContentUtils::TrimCharsInSet(const char* aSet, const nsAString& aValue) { nsAString::const_iterator valueCurrent, valueEnd; aValue.BeginReading(valueCurrent); aValue.EndReading(valueEnd); // Skip characters in the beginning while (valueCurrent != valueEnd) { if (!IsCharInSet(aSet, *valueCurrent)) { break; } ++valueCurrent; } if (valueCurrent != valueEnd) { for (;;) { --valueEnd; if (!IsCharInSet(aSet, *valueEnd)) { break; } } ++valueEnd; // Step beyond the last character we want in the value. } // valueEnd should point to the char after the last to copy return Substring(valueCurrent, valueEnd); } /** * This method strips leading and trailing whitespace from a string. */ // static template<bool IsWhitespace(PRUnichar)> const nsDependentSubstring nsContentUtils::TrimWhitespace(const nsAString& aStr, bool aTrimTrailing) { nsAString::const_iterator start, end; aStr.BeginReading(start); aStr.EndReading(end); // Skip whitespace characters in the beginning while (start != end && IsWhitespace(*start)) { ++start; } if (aTrimTrailing) { // Skip whitespace characters in the end. while (end != start) { --end; if (!IsWhitespace(*end)) { // Step back to the last non-whitespace character. ++end; break; } } } // Return a substring for the string w/o leading and/or trailing // whitespace return Substring(start, end); } // Declaring the templates we are going to use avoid linking issues without // inlining the method. Considering there is not so much spaces checking // methods we can consider this to be better than inlining. template const nsDependentSubstring nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(const nsAString&, bool); template const nsDependentSubstring nsContentUtils::TrimWhitespace<nsContentUtils::IsHTMLWhitespace>(const nsAString&, bool); static inline void KeyAppendSep(nsACString& aKey) { if (!aKey.IsEmpty()) { aKey.Append('>'); } } static inline void KeyAppendString(const nsAString& aString, nsACString& aKey) { KeyAppendSep(aKey); // Could escape separator here if collisions happen. > is not a legal char // for a name or type attribute, so we should be safe avoiding that extra work. AppendUTF16toUTF8(aString, aKey); } static inline void KeyAppendString(const nsACString& aString, nsACString& aKey) { KeyAppendSep(aKey); // Could escape separator here if collisions happen. > is not a legal char // for a name or type attribute, so we should be safe avoiding that extra work. aKey.Append(aString); } static inline void KeyAppendInt(int32_t aInt, nsACString& aKey) { KeyAppendSep(aKey); aKey.Append(nsPrintfCString("%d", aInt)); } static inline void KeyAppendAtom(nsIAtom* aAtom, nsACString& aKey) { NS_PRECONDITION(aAtom, "KeyAppendAtom: aAtom can not be null!\n"); KeyAppendString(nsAtomCString(aAtom), aKey); } static inline bool IsAutocompleteOff(const nsIContent* aElement) { return aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::autocomplete, NS_LITERAL_STRING("off"), eIgnoreCase); } /*static*/ nsresult nsContentUtils::GenerateStateKey(nsIContent* aContent, const nsIDocument* aDocument, nsIStatefulFrame::SpecialStateID aID, nsACString& aKey) { aKey.Truncate(); uint32_t partID = aDocument ? aDocument->GetPartID() : 0; // SpecialStateID case - e.g. scrollbars around the content window // The key in this case is a special state id if (nsIStatefulFrame::eNoID != aID) { KeyAppendInt(partID, aKey); // first append a partID KeyAppendInt(aID, aKey); return NS_OK; } // We must have content if we're not using a special state id NS_ENSURE_TRUE(aContent, NS_ERROR_FAILURE); // Don't capture state for anonymous content if (aContent->IsInAnonymousSubtree()) { return NS_OK; } if (IsAutocompleteOff(aContent)) { return NS_OK; } nsCOMPtr<nsIHTMLDocument> htmlDocument(do_QueryInterface(aContent->GetCurrentDoc())); KeyAppendInt(partID, aKey); // first append a partID // Make sure we can't possibly collide with an nsIStatefulFrame // special id of some sort KeyAppendInt(nsIStatefulFrame::eNoID, aKey); bool generatedUniqueKey = false; if (htmlDocument) { // Flush our content model so it'll be up to date // If this becomes unnecessary and the following line is removed, // please also remove the corresponding flush operation from // nsHtml5TreeBuilderCppSupplement.h. (Look for "See bug 497861." there.) aContent->GetCurrentDoc()->FlushPendingNotifications(Flush_Content); nsContentList *htmlForms = htmlDocument->GetForms(); nsContentList *htmlFormControls = htmlDocument->GetFormControls(); NS_ENSURE_TRUE(htmlForms && htmlFormControls, NS_ERROR_OUT_OF_MEMORY); // If we have a form control and can calculate form information, use that // as the key - it is more reliable than just recording position in the // DOM. // XXXbz Is it, really? We have bugs on this, I think... // Important to have a unique key, and tag/type/name may not be. // // If the control has a form, the format of the key is: // f>type>IndOfFormInDoc>IndOfControlInForm>FormName>name // else: // d>type>IndOfControlInDoc>name // // XXX We don't need to use index if name is there // XXXbz We don't? Why not? I don't follow. // nsCOMPtr<nsIFormControl> control(do_QueryInterface(aContent)); if (control && htmlFormControls && htmlForms) { // Append the control type KeyAppendInt(control->GetType(), aKey); // If in a form, add form name / index of form / index in form int32_t index = -1; Element *formElement = control->GetFormElement(); if (formElement) { if (IsAutocompleteOff(formElement)) { aKey.Truncate(); return NS_OK; } KeyAppendString(NS_LITERAL_CSTRING("f"), aKey); // Append the index of the form in the document index = htmlForms->IndexOf(formElement, false); if (index <= -1) { // // XXX HACK this uses some state that was dumped into the document // specifically to fix bug 138892. What we are trying to do is *guess* // which form this control's state is found in, with the highly likely // guess that the highest form parsed so far is the one. // This code should not be on trunk, only branch. // index = htmlDocument->GetNumFormsSynchronous() - 1; } if (index > -1) { KeyAppendInt(index, aKey); // Append the index of the control in the form nsCOMPtr<nsIForm> form(do_QueryInterface(formElement)); index = form->IndexOfControl(control); if (index > -1) { KeyAppendInt(index, aKey); generatedUniqueKey = true; } } // Append the form name nsAutoString formName; formElement->GetAttr(kNameSpaceID_None, nsGkAtoms::name, formName); KeyAppendString(formName, aKey); } else { KeyAppendString(NS_LITERAL_CSTRING("d"), aKey); // If not in a form, add index of control in document // Less desirable than indexing by form info. // Hash by index of control in doc (we are not in a form) // These are important as they are unique, and type/name may not be. // We have to flush sink notifications at this point to make // sure that htmlFormControls is up to date. index = htmlFormControls->IndexOf(aContent, true); if (index > -1) { KeyAppendInt(index, aKey); generatedUniqueKey = true; } } // Append the control name nsAutoString name; aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::name, name); KeyAppendString(name, aKey); } } if (!generatedUniqueKey) { // Either we didn't have a form control or we aren't in an HTML document so // we can't figure out form info. Append the tag name if it's an element // to avoid restoring state for one type of element on another type. if (aContent->IsElement()) { KeyAppendString(nsDependentAtomString(aContent->Tag()), aKey); } else { // Append a character that is not "d" or "f" to disambiguate from // the case when we were a form control in an HTML document. KeyAppendString(NS_LITERAL_CSTRING("o"), aKey); } // Now start at aContent and append the indices of it and all its ancestors // in their containers. That should at least pin down its position in the // DOM... nsINode* parent = aContent->GetNodeParent(); nsINode* content = aContent; while (parent) { KeyAppendInt(parent->IndexOf(content), aKey); content = parent; parent = content->GetNodeParent(); } } return NS_OK; } // static nsIPrincipal* nsContentUtils::GetSubjectPrincipal() { nsCOMPtr<nsIPrincipal> subject; sSecurityManager->GetSubjectPrincipal(getter_AddRefs(subject)); // When the ssm says the subject is null, that means system principal. if (!subject) sSecurityManager->GetSystemPrincipal(getter_AddRefs(subject)); return subject; } // static nsresult nsContentUtils::NewURIWithDocumentCharset(nsIURI** aResult, const nsAString& aSpec, nsIDocument* aDocument, nsIURI* aBaseURI) { return NS_NewURI(aResult, aSpec, aDocument ? aDocument->GetDocumentCharacterSet().get() : nullptr, aBaseURI, sIOService); } // static bool nsContentUtils::BelongsInForm(nsIContent *aForm, nsIContent *aContent) { NS_PRECONDITION(aForm, "Must have a form"); NS_PRECONDITION(aContent, "Must have a content node"); if (aForm == aContent) { // A form does not belong inside itself, so we return false here return false; } nsIContent* content = aContent->GetParent(); while (content) { if (content == aForm) { // aContent is contained within the form so we return true. return true; } if (content->Tag() == nsGkAtoms::form && content->IsHTML()) { // The child is contained within a form, but not the right form // so we ignore it. return false; } content = content->GetParent(); } if (aForm->GetChildCount() > 0) { // The form is a container but aContent wasn't inside the form, // return false return false; } // The form is a leaf and aContent wasn't inside any other form so // we check whether the content comes after the form. If it does, // return true. If it does not, then it couldn't have been inside // the form in the HTML. if (PositionIsBefore(aForm, aContent)) { // We could be in this form! // In the future, we may want to get document.forms, look at the // form after aForm, and if aContent is after that form after // aForm return false here.... return true; } return false; } // static nsresult nsContentUtils::CheckQName(const nsAString& aQualifiedName, bool aNamespaceAware, const PRUnichar** aColon) { const char* colon = nullptr; const PRUnichar* begin = aQualifiedName.BeginReading(); const PRUnichar* end = aQualifiedName.EndReading(); int result = MOZ_XMLCheckQName(reinterpret_cast<const char*>(begin), reinterpret_cast<const char*>(end), aNamespaceAware, &colon); if (!result) { if (aColon) { *aColon = reinterpret_cast<const PRUnichar*>(colon); } return NS_OK; } // MOZ_EXPAT_EMPTY_QNAME || MOZ_EXPAT_INVALID_CHARACTER if (result == (1 << 0) || result == (1 << 1)) { return NS_ERROR_DOM_INVALID_CHARACTER_ERR; } return NS_ERROR_DOM_NAMESPACE_ERR; } //static nsresult nsContentUtils::SplitQName(const nsIContent* aNamespaceResolver, const nsAFlatString& aQName, int32_t *aNamespace, nsIAtom **aLocalName) { const PRUnichar* colon; nsresult rv = nsContentUtils::CheckQName(aQName, true, &colon); NS_ENSURE_SUCCESS(rv, rv); if (colon) { const PRUnichar* end; aQName.EndReading(end); nsAutoString nameSpace; rv = aNamespaceResolver->LookupNamespaceURIInternal(Substring(aQName.get(), colon), nameSpace); NS_ENSURE_SUCCESS(rv, rv); *aNamespace = NameSpaceManager()->GetNameSpaceID(nameSpace); if (*aNamespace == kNameSpaceID_Unknown) return NS_ERROR_FAILURE; *aLocalName = NS_NewAtom(Substring(colon + 1, end)); } else { *aNamespace = kNameSpaceID_None; *aLocalName = NS_NewAtom(aQName); } NS_ENSURE_TRUE(aLocalName, NS_ERROR_OUT_OF_MEMORY); return NS_OK; } // static nsresult nsContentUtils::GetNodeInfoFromQName(const nsAString& aNamespaceURI, const nsAString& aQualifiedName, nsNodeInfoManager* aNodeInfoManager, uint16_t aNodeType, nsINodeInfo** aNodeInfo) { const nsAFlatString& qName = PromiseFlatString(aQualifiedName); const PRUnichar* colon; nsresult rv = nsContentUtils::CheckQName(qName, true, &colon); NS_ENSURE_SUCCESS(rv, rv); int32_t nsID; sNameSpaceManager->RegisterNameSpace(aNamespaceURI, nsID); if (colon) { const PRUnichar* end; qName.EndReading(end); nsCOMPtr<nsIAtom> prefix = do_GetAtom(Substring(qName.get(), colon)); rv = aNodeInfoManager->GetNodeInfo(Substring(colon + 1, end), prefix, nsID, aNodeType, aNodeInfo); } else { rv = aNodeInfoManager->GetNodeInfo(aQualifiedName, nullptr, nsID, aNodeType, aNodeInfo); } NS_ENSURE_SUCCESS(rv, rv); return nsContentUtils::IsValidNodeName((*aNodeInfo)->NameAtom(), (*aNodeInfo)->GetPrefixAtom(), (*aNodeInfo)->NamespaceID()) ? NS_OK : NS_ERROR_DOM_NAMESPACE_ERR; } // static void nsContentUtils::SplitExpatName(const PRUnichar *aExpatName, nsIAtom **aPrefix, nsIAtom **aLocalName, int32_t* aNameSpaceID) { /** * Expat can send the following: * localName * namespaceURI<separator>localName * namespaceURI<separator>localName<separator>prefix * * and we use 0xFFFF for the <separator>. * */ const PRUnichar *uriEnd = nullptr; const PRUnichar *nameEnd = nullptr; const PRUnichar *pos; for (pos = aExpatName; *pos; ++pos) { if (*pos == 0xFFFF) { if (uriEnd) { nameEnd = pos; } else { uriEnd = pos; } } } const PRUnichar *nameStart; if (uriEnd) { if (sNameSpaceManager) { sNameSpaceManager->RegisterNameSpace(nsDependentSubstring(aExpatName, uriEnd), *aNameSpaceID); } else { *aNameSpaceID = kNameSpaceID_Unknown; } nameStart = (uriEnd + 1); if (nameEnd) { const PRUnichar *prefixStart = nameEnd + 1; *aPrefix = NS_NewAtom(Substring(prefixStart, pos)); } else { nameEnd = pos; *aPrefix = nullptr; } } else { *aNameSpaceID = kNameSpaceID_None; nameStart = aExpatName; nameEnd = pos; *aPrefix = nullptr; } *aLocalName = NS_NewAtom(Substring(nameStart, nameEnd)); } // static nsPresContext* nsContentUtils::GetContextForContent(const nsIContent* aContent) { nsIDocument* doc = aContent->GetCurrentDoc(); if (doc) { nsIPresShell *presShell = doc->GetShell(); if (presShell) { return presShell->GetPresContext(); } } return nullptr; } // static bool nsContentUtils::CanLoadImage(nsIURI* aURI, nsISupports* aContext, nsIDocument* aLoadingDocument, nsIPrincipal* aLoadingPrincipal, int16_t* aImageBlockingStatus) { NS_PRECONDITION(aURI, "Must have a URI"); NS_PRECONDITION(aLoadingDocument, "Must have a document"); NS_PRECONDITION(aLoadingPrincipal, "Must have a loading principal"); nsresult rv; uint32_t appType = nsIDocShell::APP_TYPE_UNKNOWN; { nsCOMPtr<nsISupports> container = aLoadingDocument->GetContainer(); nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem = do_QueryInterface(container); if (docShellTreeItem) { nsCOMPtr<nsIDocShellTreeItem> root; docShellTreeItem->GetRootTreeItem(getter_AddRefs(root)); nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(root)); if (!docShell || NS_FAILED(docShell->GetAppType(&appType))) { appType = nsIDocShell::APP_TYPE_UNKNOWN; } } } if (appType != nsIDocShell::APP_TYPE_EDITOR) { // Editor apps get special treatment here, editors can load images // from anywhere. This allows editor to insert images from file:// // into documents that are being edited. rv = sSecurityManager-> CheckLoadURIWithPrincipal(aLoadingPrincipal, aURI, nsIScriptSecurityManager::ALLOW_CHROME); if (NS_FAILED(rv)) { if (aImageBlockingStatus) { // Reject the request itself, not all requests to the relevant // server... *aImageBlockingStatus = nsIContentPolicy::REJECT_REQUEST; } return false; } } int16_t decision = nsIContentPolicy::ACCEPT; rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_IMAGE, aURI, aLoadingPrincipal, aContext, EmptyCString(), //mime guess nullptr, //extra &decision, GetContentPolicy(), sSecurityManager); if (aImageBlockingStatus) { *aImageBlockingStatus = NS_FAILED(rv) ? nsIContentPolicy::REJECT_REQUEST : decision; } return NS_FAILED(rv) ? false : NS_CP_ACCEPTED(decision); } imgILoader* nsContentUtils::GetImgLoaderForDocument(nsIDocument* aDoc) { if (!sImgLoaderInitialized) InitImgLoader(); if (!aDoc) return sImgLoader; bool isPrivate = false; nsCOMPtr<nsILoadGroup> loadGroup = aDoc->GetDocumentLoadGroup(); nsCOMPtr<nsIInterfaceRequestor> callbacks; if (loadGroup) { loadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks)); if (callbacks) { nsCOMPtr<nsILoadContext> loadContext = do_GetInterface(callbacks); isPrivate = loadContext && loadContext->UsePrivateBrowsing(); } } else { nsCOMPtr<nsIChannel> channel = aDoc->GetChannel(); isPrivate = channel && NS_UsePrivateBrowsing(channel); } return isPrivate ? sPrivateImgLoader : sImgLoader; } // static imgILoader* nsContentUtils::GetImgLoaderForChannel(nsIChannel* aChannel) { if (!sImgLoaderInitialized) InitImgLoader(); if (!aChannel) return sImgLoader; nsCOMPtr<nsILoadContext> context; NS_QueryNotificationCallbacks(aChannel, context); return context && context->UsePrivateBrowsing() ? sPrivateImgLoader : sImgLoader; } // static bool nsContentUtils::IsImageInCache(nsIURI* aURI, nsIDocument* aDocument) { if (!sImgLoaderInitialized) InitImgLoader(); imgILoader* loader = GetImgLoaderForDocument(aDocument); nsCOMPtr<imgICache> cache = do_QueryInterface(loader); // If something unexpected happened we return false, otherwise if props // is set, the image is cached and we return true nsCOMPtr<nsIProperties> props; nsresult rv = cache->FindEntryProperties(aURI, getter_AddRefs(props)); return (NS_SUCCEEDED(rv) && props); } // static nsresult nsContentUtils::LoadImage(nsIURI* aURI, nsIDocument* aLoadingDocument, nsIPrincipal* aLoadingPrincipal, nsIURI* aReferrer, imgIDecoderObserver* aObserver, int32_t aLoadFlags, imgIRequest** aRequest) { NS_PRECONDITION(aURI, "Must have a URI"); NS_PRECONDITION(aLoadingDocument, "Must have a document"); NS_PRECONDITION(aLoadingPrincipal, "Must have a principal"); NS_PRECONDITION(aRequest, "Null out param"); imgILoader* imgLoader = GetImgLoaderForDocument(aLoadingDocument); if (!imgLoader) { // nothing we can do here return NS_OK; } nsCOMPtr<nsILoadGroup> loadGroup = aLoadingDocument->GetDocumentLoadGroup(); NS_ASSERTION(loadGroup, "Could not get loadgroup; onload may fire too early"); nsIURI *documentURI = aLoadingDocument->GetDocumentURI(); // check for a Content Security Policy to pass down to the channel that // will get created to load the image nsCOMPtr<nsIChannelPolicy> channelPolicy; nsCOMPtr<nsIContentSecurityPolicy> csp; if (aLoadingPrincipal) { nsresult rv = aLoadingPrincipal->GetCsp(getter_AddRefs(csp)); NS_ENSURE_SUCCESS(rv, rv); if (csp) { channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1"); channelPolicy->SetContentSecurityPolicy(csp); channelPolicy->SetLoadType(nsIContentPolicy::TYPE_IMAGE); } } // Make the URI immutable so people won't change it under us NS_TryToSetImmutable(aURI); // XXXbz using "documentURI" for the initialDocumentURI is not quite // right, but the best we can do here... return imgLoader->LoadImage(aURI, /* uri to load */ documentURI, /* initialDocumentURI */ aReferrer, /* referrer */ aLoadingPrincipal, /* loading principal */ loadGroup, /* loadgroup */ aObserver, /* imgIDecoderObserver */ aLoadingDocument, /* uniquification key */ aLoadFlags, /* load flags */ nullptr, /* cache key */ nullptr, /* existing request*/ channelPolicy, /* CSP info */ aRequest); } // static already_AddRefed<imgIContainer> nsContentUtils::GetImageFromContent(nsIImageLoadingContent* aContent, imgIRequest **aRequest) { if (aRequest) { *aRequest = nullptr; } NS_ENSURE_TRUE(aContent, nullptr); nsCOMPtr<imgIRequest> imgRequest; aContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST, getter_AddRefs(imgRequest)); if (!imgRequest) { return nullptr; } nsCOMPtr<imgIContainer> imgContainer; imgRequest->GetImage(getter_AddRefs(imgContainer)); if (!imgContainer) { return nullptr; } if (aRequest) { imgRequest.swap(*aRequest); } return imgContainer.forget(); } //static already_AddRefed<imgIRequest> nsContentUtils::GetStaticRequest(imgIRequest* aRequest) { NS_ENSURE_TRUE(aRequest, nullptr); nsCOMPtr<imgIRequest> retval; aRequest->GetStaticRequest(getter_AddRefs(retval)); return retval.forget(); } // static bool nsContentUtils::ContentIsDraggable(nsIContent* aContent) { nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(aContent); if (htmlElement) { bool draggable = false; htmlElement->GetDraggable(&draggable); if (draggable) return true; if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::draggable, nsGkAtoms::_false, eIgnoreCase)) return false; } // special handling for content area image and link dragging return IsDraggableImage(aContent) || IsDraggableLink(aContent); } // static bool nsContentUtils::IsDraggableImage(nsIContent* aContent) { NS_PRECONDITION(aContent, "Must have content node to test"); nsCOMPtr<nsIImageLoadingContent> imageContent(do_QueryInterface(aContent)); if (!imageContent) { return false; } nsCOMPtr<imgIRequest> imgRequest; imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST, getter_AddRefs(imgRequest)); // XXXbz It may be draggable even if the request resulted in an error. Why? // Not sure; that's what the old nsContentAreaDragDrop/nsFrame code did. return imgRequest != nullptr; } // static bool nsContentUtils::IsDraggableLink(const nsIContent* aContent) { nsCOMPtr<nsIURI> absURI; return aContent->IsLink(getter_AddRefs(absURI)); } static bool TestSitePerm(nsIPrincipal* aPrincipal, const char* aType, uint32_t aPerm, bool aExactHostMatch) { if (!aPrincipal) { // We always deny (i.e. don't allow) the permission if we don't have a // principal. return aPerm != nsIPermissionManager::ALLOW_ACTION; } nsCOMPtr<nsIPermissionManager> permMgr = do_GetService("@mozilla.org/permissionmanager;1"); NS_ENSURE_TRUE(permMgr, false); uint32_t perm; nsresult rv; if (aExactHostMatch) { rv = permMgr->TestExactPermissionFromPrincipal(aPrincipal, aType, &perm); } else { rv = permMgr->TestPermissionFromPrincipal(aPrincipal, aType, &perm); } NS_ENSURE_SUCCESS(rv, false); return perm == aPerm; } bool nsContentUtils::IsSitePermAllow(nsIPrincipal* aPrincipal, const char* aType) { return TestSitePerm(aPrincipal, aType, nsIPermissionManager::ALLOW_ACTION, false); } bool nsContentUtils::IsSitePermDeny(nsIPrincipal* aPrincipal, const char* aType) { return TestSitePerm(aPrincipal, aType, nsIPermissionManager::DENY_ACTION, false); } bool nsContentUtils::IsExactSitePermAllow(nsIPrincipal* aPrincipal, const char* aType) { return TestSitePerm(aPrincipal, aType, nsIPermissionManager::ALLOW_ACTION, true); } bool nsContentUtils::IsExactSitePermDeny(nsIPrincipal* aPrincipal, const char* aType) { return TestSitePerm(aPrincipal, aType, nsIPermissionManager::DENY_ACTION, true); } static const char *gEventNames[] = {"event"}; static const char *gSVGEventNames[] = {"evt"}; // for b/w compat, the first name to onerror is still 'event', even though it // is actually the error message. (pre this code, the other 2 were not avail.) // XXXmarkh - a quick lxr shows no affected code - should we correct this? static const char *gOnErrorNames[] = {"event", "source", "lineno"}; // static void nsContentUtils::GetEventArgNames(int32_t aNameSpaceID, nsIAtom *aEventName, uint32_t *aArgCount, const char*** aArgArray) { #define SET_EVENT_ARG_NAMES(names) \ *aArgCount = sizeof(names)/sizeof(names[0]); \ *aArgArray = names; // nsJSEventListener is what does the arg magic for onerror, and it does // not seem to take the namespace into account. So we let onerror in all // namespaces get the 3 arg names. if (aEventName == nsGkAtoms::onerror) { SET_EVENT_ARG_NAMES(gOnErrorNames); } else if (aNameSpaceID == kNameSpaceID_SVG) { SET_EVENT_ARG_NAMES(gSVGEventNames); } else { SET_EVENT_ARG_NAMES(gEventNames); } } nsCxPusher::nsCxPusher() : mScriptIsRunning(false), mPushedSomething(false) { } nsCxPusher::~nsCxPusher() { Pop(); } static bool IsContextOnStack(nsIJSContextStack *aStack, JSContext *aContext) { JSContext *ctx = nullptr; aStack->Peek(&ctx); if (!ctx) return false; if (ctx == aContext) return true; nsCOMPtr<nsIJSContextStackIterator> iterator(do_CreateInstance("@mozilla.org/js/xpc/ContextStackIterator;1")); NS_ENSURE_TRUE(iterator, false); nsresult rv = iterator->Reset(aStack); NS_ENSURE_SUCCESS(rv, false); bool done; while (NS_SUCCEEDED(iterator->Done(&done)) && !done) { rv = iterator->Prev(&ctx); NS_ASSERTION(NS_SUCCEEDED(rv), "Broken iterator implementation"); if (!ctx) { continue; } if (nsJSUtils::GetDynamicScriptContext(ctx) && ctx == aContext) return true; } return false; } bool nsCxPusher::Push(nsIDOMEventTarget *aCurrentTarget) { if (mPushedSomething) { NS_ERROR("Whaaa! No double pushing with nsCxPusher::Push()!"); return false; } NS_ENSURE_TRUE(aCurrentTarget, false); nsresult rv; nsIScriptContext* scx = aCurrentTarget->GetContextForEventHandlers(&rv); NS_ENSURE_SUCCESS(rv, false); if (!scx) { // The target may have a special JS context for event handlers. JSContext* cx = aCurrentTarget->GetJSContextForEventHandlers(); if (cx) { DoPush(cx); } // Nothing to do here, I guess. Have to return true so that event firing // will still work correctly even if there is no associated JSContext return true; } JSContext* cx = nullptr; if (scx) { cx = scx->GetNativeContext(); // Bad, no JSContext from script context! NS_ENSURE_TRUE(cx, false); } // If there's no native context in the script context it must be // in the process or being torn down. We don't want to notify the // script context about scripts having been evaluated in such a // case, calling with a null cx is fine in that case. return Push(cx); } bool nsCxPusher::RePush(nsIDOMEventTarget *aCurrentTarget) { if (!mPushedSomething) { return Push(aCurrentTarget); } if (aCurrentTarget) { nsresult rv; nsIScriptContext* scx = aCurrentTarget->GetContextForEventHandlers(&rv); if (NS_FAILED(rv)) { Pop(); return false; } // If we have the same script context and native context is still // alive, no need to Pop/Push. if (scx && scx == mScx && scx->GetNativeContext()) { return true; } } Pop(); return Push(aCurrentTarget); } bool nsCxPusher::Push(JSContext *cx, bool aRequiresScriptContext) { if (mPushedSomething) { NS_ERROR("Whaaa! No double pushing with nsCxPusher::Push()!"); return false; } if (!cx) { return false; } // Hold a strong ref to the nsIScriptContext, just in case // XXXbz do we really need to? If we don't get one of these in Pop(), is // that really a problem? Or do we need to do this to effectively root |cx|? mScx = GetScriptContextFromJSContext(cx); if (!mScx && aRequiresScriptContext) { // Should probably return false. See bug 416916. return true; } return DoPush(cx); } bool nsCxPusher::DoPush(JSContext* cx) { nsIThreadJSContextStack* stack = nsContentUtils::ThreadJSContextStack(); if (!stack) { return true; } if (cx && IsContextOnStack(stack, cx)) { // If the context is on the stack, that means that a script // is running at the moment in the context. mScriptIsRunning = true; } if (NS_FAILED(stack->Push(cx))) { mScriptIsRunning = false; mScx = nullptr; return false; } mPushedSomething = true; #ifdef DEBUG mPushedContext = cx; #endif return true; } bool nsCxPusher::PushNull() { return DoPush(nullptr); } void nsCxPusher::Pop() { nsIThreadJSContextStack* stack = nsContentUtils::ThreadJSContextStack(); if (!mPushedSomething || !stack) { mScx = nullptr; mPushedSomething = false; NS_ASSERTION(!mScriptIsRunning, "Huh, this can't be happening, " "mScriptIsRunning can't be set here!"); return; } JSContext *unused; stack->Pop(&unused); NS_ASSERTION(unused == mPushedContext, "Unexpected context popped"); if (!mScriptIsRunning && mScx) { // No JS is running in the context, but executing the event handler might have // caused some JS to run. Tell the script context that it's done. mScx->ScriptEvaluated(true); } mScx = nullptr; mScriptIsRunning = false; mPushedSomething = false; } static const char gPropertiesFiles[nsContentUtils::PropertiesFile_COUNT][56] = { // Must line up with the enum values in |PropertiesFile| enum. "chrome://global/locale/css.properties", "chrome://global/locale/xbl.properties", "chrome://global/locale/xul.properties", "chrome://global/locale/layout_errors.properties", "chrome://global/locale/layout/HtmlForm.properties", "chrome://global/locale/printing.properties", "chrome://global/locale/dom/dom.properties", "chrome://global/locale/layout/htmlparser.properties", "chrome://global/locale/svg/svg.properties", "chrome://branding/locale/brand.properties", "chrome://global/locale/commonDialogs.properties" }; /* static */ nsresult nsContentUtils::EnsureStringBundle(PropertiesFile aFile) { if (!sStringBundles[aFile]) { if (!sStringBundleService) { nsresult rv = CallGetService(NS_STRINGBUNDLE_CONTRACTID, &sStringBundleService); NS_ENSURE_SUCCESS(rv, rv); } nsIStringBundle *bundle; nsresult rv = sStringBundleService->CreateBundle(gPropertiesFiles[aFile], &bundle); NS_ENSURE_SUCCESS(rv, rv); sStringBundles[aFile] = bundle; // transfer ownership } return NS_OK; } /* static */ nsresult nsContentUtils::GetLocalizedString(PropertiesFile aFile, const char* aKey, nsXPIDLString& aResult) { nsresult rv = EnsureStringBundle(aFile); NS_ENSURE_SUCCESS(rv, rv); nsIStringBundle *bundle = sStringBundles[aFile]; return bundle->GetStringFromName(NS_ConvertASCIItoUTF16(aKey).get(), getter_Copies(aResult)); } /* static */ nsresult nsContentUtils::FormatLocalizedString(PropertiesFile aFile, const char* aKey, const PRUnichar **aParams, uint32_t aParamsLength, nsXPIDLString& aResult) { nsresult rv = EnsureStringBundle(aFile); NS_ENSURE_SUCCESS(rv, rv); nsIStringBundle *bundle = sStringBundles[aFile]; return bundle->FormatStringFromName(NS_ConvertASCIItoUTF16(aKey).get(), aParams, aParamsLength, getter_Copies(aResult)); } /* static */ nsresult nsContentUtils::ReportToConsole(uint32_t aErrorFlags, const char *aCategory, nsIDocument* aDocument, PropertiesFile aFile, const char *aMessageName, const PRUnichar **aParams, uint32_t aParamsLength, nsIURI* aURI, const nsAFlatString& aSourceLine, uint32_t aLineNumber, uint32_t aColumnNumber) { NS_ASSERTION((aParams && aParamsLength) || (!aParams && !aParamsLength), "Supply either both parameters and their number or no" "parameters and 0."); uint64_t innerWindowID = 0; if (aDocument) { if (!aURI) { aURI = aDocument->GetDocumentURI(); } innerWindowID = aDocument->InnerWindowID(); } nsresult rv; if (!sConsoleService) { // only need to bother null-checking here rv = CallGetService(NS_CONSOLESERVICE_CONTRACTID, &sConsoleService); NS_ENSURE_SUCCESS(rv, rv); } nsXPIDLString errorText; if (aParams) { rv = FormatLocalizedString(aFile, aMessageName, aParams, aParamsLength, errorText); } else { rv = GetLocalizedString(aFile, aMessageName, errorText); } NS_ENSURE_SUCCESS(rv, rv); nsAutoCString spec; if (!aLineNumber) { JSContext *cx = nullptr; sThreadJSContextStack->Peek(&cx); if (cx) { const char* filename; uint32_t lineno; if (nsJSUtils::GetCallingLocation(cx, &filename, &lineno)) { spec = filename; aLineNumber = lineno; } } } if (spec.IsEmpty() && aURI) aURI->GetSpec(spec); nsCOMPtr<nsIScriptError> errorObject = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = errorObject->InitWithWindowID(errorText, NS_ConvertUTF8toUTF16(spec), // file name aSourceLine, aLineNumber, aColumnNumber, aErrorFlags, aCategory, innerWindowID); NS_ENSURE_SUCCESS(rv, rv); return sConsoleService->LogMessage(errorObject); } bool nsContentUtils::IsChromeDoc(nsIDocument *aDocument) { if (!aDocument) { return false; } nsCOMPtr<nsIPrincipal> systemPrincipal; sSecurityManager->GetSystemPrincipal(getter_AddRefs(systemPrincipal)); return aDocument->NodePrincipal() == systemPrincipal; } bool nsContentUtils::IsChildOfSameType(nsIDocument* aDoc) { nsCOMPtr<nsISupports> container = aDoc->GetContainer(); nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(do_QueryInterface(container)); nsCOMPtr<nsIDocShellTreeItem> sameTypeParent; if (docShellAsItem) { docShellAsItem->GetSameTypeParent(getter_AddRefs(sameTypeParent)); } return sameTypeParent != nullptr; } bool nsContentUtils::GetWrapperSafeScriptFilename(nsIDocument *aDocument, nsIURI *aURI, nsACString& aScriptURI) { bool scriptFileNameModified = false; aURI->GetSpec(aScriptURI); if (IsChromeDoc(aDocument)) { nsCOMPtr<nsIChromeRegistry> chromeReg = mozilla::services::GetChromeRegistryService(); if (!chromeReg) { // If we're running w/o a chrome registry we won't modify any // script file names. return scriptFileNameModified; } bool docWrappersEnabled = chromeReg->WrappersEnabled(aDocument->GetDocumentURI()); bool uriWrappersEnabled = chromeReg->WrappersEnabled(aURI); nsIURI *docURI = aDocument->GetDocumentURI(); if (docURI && docWrappersEnabled && !uriWrappersEnabled) { // aURI is a script from a URL that doesn't get wrapper // automation. aDocument is a chrome document that does get // wrapper automation. Prepend the chrome document's URI // followed by the string " -> " to the URI of the script we're // loading here so that script in that URI gets the same wrapper // automation that the chrome document expects. nsAutoCString spec; docURI->GetSpec(spec); spec.AppendASCII(" -> "); spec.Append(aScriptURI); aScriptURI = spec; scriptFileNameModified = true; } } return scriptFileNameModified; } // static bool nsContentUtils::IsInChromeDocshell(nsIDocument *aDocument) { if (!aDocument) { return false; } if (aDocument->GetDisplayDocument()) { return IsInChromeDocshell(aDocument->GetDisplayDocument()); } nsCOMPtr<nsISupports> docContainer = aDocument->GetContainer(); nsCOMPtr<nsIDocShellTreeItem> docShell(do_QueryInterface(docContainer)); int32_t itemType = nsIDocShellTreeItem::typeContent; if (docShell) { docShell->GetItemType(&itemType); } return itemType == nsIDocShellTreeItem::typeChrome; } // static nsIContentPolicy* nsContentUtils::GetContentPolicy() { if (!sTriedToGetContentPolicy) { CallGetService(NS_CONTENTPOLICY_CONTRACTID, &sContentPolicyService); // It's OK to not have a content policy service sTriedToGetContentPolicy = true; } return sContentPolicyService; } // static bool nsContentUtils::IsEventAttributeName(nsIAtom* aName, int32_t aType) { const PRUnichar* name = aName->GetUTF16String(); if (name[0] != 'o' || name[1] != 'n') return false; EventNameMapping mapping; return (sAtomEventTable->Get(aName, &mapping) && mapping.mType & aType); } // static uint32_t nsContentUtils::GetEventId(nsIAtom* aName) { EventNameMapping mapping; if (sAtomEventTable->Get(aName, &mapping)) return mapping.mId; return NS_USER_DEFINED_EVENT; } // static uint32_t nsContentUtils::GetEventCategory(const nsAString& aName) { EventNameMapping mapping; if (sStringEventTable->Get(aName, &mapping)) return mapping.mStructType; return NS_EVENT; } nsIAtom* nsContentUtils::GetEventIdAndAtom(const nsAString& aName, uint32_t aEventStruct, uint32_t* aEventID) { EventNameMapping mapping; if (sStringEventTable->Get(aName, &mapping)) { *aEventID = mapping.mStructType == aEventStruct ? mapping.mId : NS_USER_DEFINED_EVENT; return mapping.mAtom; } // If we have cached lots of user defined event names, clear some of them. if (sUserDefinedEvents->Count() > 127) { while (sUserDefinedEvents->Count() > 64) { nsIAtom* first = sUserDefinedEvents->ObjectAt(0); sStringEventTable->Remove(Substring(nsDependentAtomString(first), 2)); sUserDefinedEvents->RemoveObjectAt(0); } } *aEventID = NS_USER_DEFINED_EVENT; nsCOMPtr<nsIAtom> atom = do_GetAtom(NS_LITERAL_STRING("on") + aName); sUserDefinedEvents->AppendObject(atom); mapping.mAtom = atom; mapping.mId = NS_USER_DEFINED_EVENT; mapping.mType = EventNameType_None; mapping.mStructType = NS_EVENT_NULL; sStringEventTable->Put(aName, mapping); return mapping.mAtom; } static nsresult GetEventAndTarget(nsIDocument* aDoc, nsISupports* aTarget, const nsAString& aEventName, bool aCanBubble, bool aCancelable, bool aTrusted, nsIDOMEvent** aEvent, nsIDOMEventTarget** aTargetOut) { nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(aDoc); nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(aTarget)); NS_ENSURE_TRUE(domDoc && target, NS_ERROR_INVALID_ARG); nsCOMPtr<nsIDOMEvent> event; nsresult rv = domDoc->CreateEvent(NS_LITERAL_STRING("Events"), getter_AddRefs(event)); NS_ENSURE_SUCCESS(rv, rv); rv = event->InitEvent(aEventName, aCanBubble, aCancelable); NS_ENSURE_SUCCESS(rv, rv); rv = event->SetTrusted(aTrusted); NS_ENSURE_SUCCESS(rv, rv); rv = event->SetTarget(target); NS_ENSURE_SUCCESS(rv, rv); event.forget(aEvent); target.forget(aTargetOut); return NS_OK; } // static nsresult nsContentUtils::DispatchTrustedEvent(nsIDocument* aDoc, nsISupports* aTarget, const nsAString& aEventName, bool aCanBubble, bool aCancelable, bool *aDefaultAction) { return DispatchEvent(aDoc, aTarget, aEventName, aCanBubble, aCancelable, true, aDefaultAction); } // static nsresult nsContentUtils::DispatchUntrustedEvent(nsIDocument* aDoc, nsISupports* aTarget, const nsAString& aEventName, bool aCanBubble, bool aCancelable, bool *aDefaultAction) { return DispatchEvent(aDoc, aTarget, aEventName, aCanBubble, aCancelable, false, aDefaultAction); } // static nsresult nsContentUtils::DispatchEvent(nsIDocument* aDoc, nsISupports* aTarget, const nsAString& aEventName, bool aCanBubble, bool aCancelable, bool aTrusted, bool *aDefaultAction) { nsCOMPtr<nsIDOMEvent> event; nsCOMPtr<nsIDOMEventTarget> target; nsresult rv = GetEventAndTarget(aDoc, aTarget, aEventName, aCanBubble, aCancelable, aTrusted, getter_AddRefs(event), getter_AddRefs(target)); NS_ENSURE_SUCCESS(rv, rv); bool dummy; return target->DispatchEvent(event, aDefaultAction ? aDefaultAction : &dummy); } nsresult nsContentUtils::DispatchChromeEvent(nsIDocument *aDoc, nsISupports *aTarget, const nsAString& aEventName, bool aCanBubble, bool aCancelable, bool *aDefaultAction) { nsCOMPtr<nsIDOMEvent> event; nsCOMPtr<nsIDOMEventTarget> target; nsresult rv = GetEventAndTarget(aDoc, aTarget, aEventName, aCanBubble, aCancelable, true, getter_AddRefs(event), getter_AddRefs(target)); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(aDoc, "GetEventAndTarget lied?"); if (!aDoc->GetWindow()) return NS_ERROR_INVALID_ARG; nsIDOMEventTarget* piTarget = aDoc->GetWindow()->GetParentTarget(); if (!piTarget) return NS_ERROR_INVALID_ARG; nsEventStatus status = nsEventStatus_eIgnore; rv = piTarget->DispatchDOMEvent(nullptr, event, nullptr, &status); if (aDefaultAction) { *aDefaultAction = (status != nsEventStatus_eConsumeNoDefault); } return rv; } /* static */ Element* nsContentUtils::MatchElementId(nsIContent *aContent, const nsIAtom* aId) { for (nsIContent* cur = aContent; cur; cur = cur->GetNextNode(aContent)) { if (aId == cur->GetID()) { return cur->AsElement(); } } return nullptr; } /* static */ Element * nsContentUtils::MatchElementId(nsIContent *aContent, const nsAString& aId) { NS_PRECONDITION(!aId.IsEmpty(), "Will match random elements"); // ID attrs are generally stored as atoms, so just atomize this up front nsCOMPtr<nsIAtom> id(do_GetAtom(aId)); if (!id) { // OOM, so just bail return nullptr; } return MatchElementId(aContent, id); } // Convert the string from the given charset to Unicode. /* static */ nsresult nsContentUtils::ConvertStringFromCharset(const nsACString& aCharset, const nsACString& aInput, nsAString& aOutput) { if (aCharset.IsEmpty()) { // Treat the string as UTF8 CopyUTF8toUTF16(aInput, aOutput); return NS_OK; } nsresult rv; nsCOMPtr<nsICharsetConverterManager> ccm = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIUnicodeDecoder> decoder; rv = ccm->GetUnicodeDecoder(PromiseFlatCString(aCharset).get(), getter_AddRefs(decoder)); if (NS_FAILED(rv)) return rv; nsPromiseFlatCString flatInput(aInput); int32_t length = flatInput.Length(); int32_t outLen; rv = decoder->GetMaxLength(flatInput.get(), length, &outLen); if (NS_FAILED(rv)) return rv; PRUnichar *ustr = (PRUnichar *)nsMemory::Alloc((outLen + 1) * sizeof(PRUnichar)); if (!ustr) return NS_ERROR_OUT_OF_MEMORY; const char* data = flatInput.get(); aOutput.Truncate(); for (;;) { int32_t srcLen = length; int32_t dstLen = outLen; rv = decoder->Convert(data, &srcLen, ustr, &dstLen); // Convert will convert the input partially even if the status // indicates a failure. ustr[dstLen] = 0; aOutput.Append(ustr, dstLen); if (rv != NS_ERROR_ILLEGAL_INPUT) { break; } // Emit a decode error manually because some decoders // do not support kOnError_Recover (bug 638379) if (srcLen == -1) { decoder->Reset(); } else { data += srcLen + 1; length -= srcLen + 1; aOutput.Append(static_cast<PRUnichar>(0xFFFD)); } } nsMemory::Free(ustr); return rv; } /* static */ bool nsContentUtils::CheckForBOM(const unsigned char* aBuffer, uint32_t aLength, nsACString& aCharset, bool *bigEndian) { bool found = true; aCharset.Truncate(); if (aLength >= 3 && aBuffer[0] == 0xEF && aBuffer[1] == 0xBB && aBuffer[2] == 0xBF) { aCharset = "UTF-8"; } else if (aLength >= 2 && aBuffer[0] == 0xFE && aBuffer[1] == 0xFF) { aCharset = "UTF-16"; if (bigEndian) *bigEndian = true; } else if (aLength >= 2 && aBuffer[0] == 0xFF && aBuffer[1] == 0xFE) { aCharset = "UTF-16"; if (bigEndian) *bigEndian = false; } else { found = false; } return found; } NS_IMPL_ISUPPORTS1(CharsetDetectionObserver, nsICharsetDetectionObserver) /* static */ nsresult nsContentUtils::GuessCharset(const char *aData, uint32_t aDataLen, nsACString &aCharset) { // First try the universal charset detector nsCOMPtr<nsICharsetDetector> detector = do_CreateInstance(NS_CHARSET_DETECTOR_CONTRACTID_BASE "universal_charset_detector"); if (!detector) { // No universal charset detector, try the default charset detector const nsAdoptingCString& detectorName = Preferences::GetLocalizedCString("intl.charset.detector"); if (!detectorName.IsEmpty()) { nsAutoCString detectorContractID; detectorContractID.AssignLiteral(NS_CHARSET_DETECTOR_CONTRACTID_BASE); detectorContractID += detectorName; detector = do_CreateInstance(detectorContractID.get()); } } nsresult rv; // The charset detector doesn't work for empty (null) aData. Testing // aDataLen instead of aData so that we catch potential errors. if (detector && aDataLen) { nsRefPtr<CharsetDetectionObserver> observer = new CharsetDetectionObserver(); rv = detector->Init(observer); NS_ENSURE_SUCCESS(rv, rv); bool dummy; rv = detector->DoIt(aData, aDataLen, &dummy); NS_ENSURE_SUCCESS(rv, rv); rv = detector->Done(); NS_ENSURE_SUCCESS(rv, rv); aCharset = observer->GetResult(); } else { // no charset detector available, check the BOM unsigned char sniffBuf[3]; uint32_t numRead = (aDataLen >= sizeof(sniffBuf) ? sizeof(sniffBuf) : aDataLen); memcpy(sniffBuf, aData, numRead); bool bigEndian; if (CheckForBOM(sniffBuf, numRead, aCharset, &bigEndian) && aCharset.EqualsLiteral("UTF-16")) { if (bigEndian) { aCharset.AppendLiteral("BE"); } else { aCharset.AppendLiteral("LE"); } } } if (aCharset.IsEmpty()) { // no charset detected, default to the system charset nsCOMPtr<nsIPlatformCharset> platformCharset = do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &rv); if (NS_SUCCEEDED(rv)) { rv = platformCharset->GetCharset(kPlatformCharsetSel_PlainTextInFile, aCharset); if (NS_FAILED(rv)) { NS_WARNING("Failed to get the system charset!"); } } } if (aCharset.IsEmpty()) { // no sniffed or default charset, assume UTF-8 aCharset.AssignLiteral("UTF-8"); } return NS_OK; } /* static */ void nsContentUtils::RegisterShutdownObserver(nsIObserver* aObserver) { nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService(); if (observerService) { observerService->AddObserver(aObserver, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false); } } /* static */ void nsContentUtils::UnregisterShutdownObserver(nsIObserver* aObserver) { nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService(); if (observerService) { observerService->RemoveObserver(aObserver, NS_XPCOM_SHUTDOWN_OBSERVER_ID); } } /* static */ bool nsContentUtils::HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID, nsIAtom* aName) { static nsIContent::AttrValuesArray strings[] = {&nsGkAtoms::_empty, nullptr}; return aContent->FindAttrValueIn(aNameSpaceID, aName, strings, eCaseMatters) == nsIContent::ATTR_VALUE_NO_MATCH; } /* static */ bool nsContentUtils::HasMutationListeners(nsINode* aNode, uint32_t aType, nsINode* aTargetForSubtreeModified) { nsIDocument* doc = aNode->OwnerDoc(); // global object will be null for documents that don't have windows. nsPIDOMWindow* window = doc->GetInnerWindow(); // This relies on nsEventListenerManager::AddEventListener, which sets // all mutation bits when there is a listener for DOMSubtreeModified event. if (window && !window->HasMutationListeners(aType)) { return false; } if (aNode->IsNodeOfType(nsINode::eCONTENT) && static_cast<nsIContent*>(aNode)->ChromeOnlyAccess()) { return false; } doc->MayDispatchMutationEvent(aTargetForSubtreeModified); // If we have a window, we can check it for mutation listeners now. if (aNode->IsInDoc()) { nsCOMPtr<nsIDOMEventTarget> piTarget(do_QueryInterface(window)); if (piTarget) { nsEventListenerManager* manager = piTarget->GetListenerManager(false); if (manager && manager->HasMutationListeners()) { return true; } } } // If we have a window, we know a mutation listener is registered, but it // might not be in our chain. If we don't have a window, we might have a // mutation listener. Check quickly to see. while (aNode) { nsEventListenerManager* manager = aNode->GetListenerManager(false); if (manager && manager->HasMutationListeners()) { return true; } if (aNode->IsNodeOfType(nsINode::eCONTENT)) { nsIContent* content = static_cast<nsIContent*>(aNode); nsIContent* insertionParent = doc->BindingManager()->GetInsertionParent(content); if (insertionParent) { aNode = insertionParent; continue; } } aNode = aNode->GetNodeParent(); } return false; } /* static */ bool nsContentUtils::HasMutationListeners(nsIDocument* aDocument, uint32_t aType) { nsPIDOMWindow* window = aDocument ? aDocument->GetInnerWindow() : nullptr; // This relies on nsEventListenerManager::AddEventListener, which sets // all mutation bits when there is a listener for DOMSubtreeModified event. return !window || window->HasMutationListeners(aType); } void nsContentUtils::MaybeFireNodeRemoved(nsINode* aChild, nsINode* aParent, nsIDocument* aOwnerDoc) { NS_PRECONDITION(aChild, "Missing child"); NS_PRECONDITION(aChild->GetNodeParent() == aParent, "Wrong parent"); NS_PRECONDITION(aChild->OwnerDoc() == aOwnerDoc, "Wrong owner-doc"); // This checks that IsSafeToRunScript is true since we don't want to fire // events when that is false. We can't rely on nsEventDispatcher to assert // this in this situation since most of the time there are no mutation // event listeners, in which case we won't even attempt to dispatch events. // However this also allows for two exceptions. First off, we don't assert // if the mutation happens to native anonymous content since we never fire // mutation events on such content anyway. // Second, we don't assert if sDOMNodeRemovedSuppressCount is true since // that is a know case when we'd normally fire a mutation event, but can't // make that safe and so we suppress it at this time. Ideally this should // go away eventually. NS_ASSERTION((aChild->IsNodeOfType(nsINode::eCONTENT) && static_cast<nsIContent*>(aChild)-> IsInNativeAnonymousSubtree()) || IsSafeToRunScript() || sDOMNodeRemovedSuppressCount, "Want to fire DOMNodeRemoved event, but it's not safe"); // Having an explicit check here since it's an easy mistake to fall into, // and there might be existing code with problems. We'd rather be safe // than fire DOMNodeRemoved in all corner cases. We also rely on it for // nsAutoScriptBlockerSuppressNodeRemoved. if (!IsSafeToRunScript()) { return; } if (HasMutationListeners(aChild, NS_EVENT_BITS_MUTATION_NODEREMOVED, aParent)) { nsMutationEvent mutation(true, NS_MUTATION_NODEREMOVED); mutation.mRelatedNode = do_QueryInterface(aParent); mozAutoSubtreeModified subtree(aOwnerDoc, aParent); nsEventDispatcher::Dispatch(aChild, nullptr, &mutation); } } PLDHashOperator ListenerEnumerator(PLDHashTable* aTable, PLDHashEntryHdr* aEntry, uint32_t aNumber, void* aArg) { EventListenerManagerMapEntry* entry = static_cast<EventListenerManagerMapEntry*>(aEntry); if (entry) { nsINode* n = static_cast<nsINode*>(entry->mListenerManager->GetTarget()); if (n && n->IsInDoc() && nsCCUncollectableMarker::InGeneration(n->OwnerDoc()->GetMarkedCCGeneration())) { entry->mListenerManager->UnmarkGrayJSListeners(); } } return PL_DHASH_NEXT; } void nsContentUtils::UnmarkGrayJSListenersInCCGenerationDocuments(uint32_t aGeneration) { if (sEventListenerManagersHash.ops) { PL_DHashTableEnumerate(&sEventListenerManagersHash, ListenerEnumerator, &aGeneration); } } /* static */ void nsContentUtils::TraverseListenerManager(nsINode *aNode, nsCycleCollectionTraversalCallback &cb) { if (!sEventListenerManagersHash.ops) { // We're already shut down, just return. return; } EventListenerManagerMapEntry *entry = static_cast<EventListenerManagerMapEntry *> (PL_DHashTableOperate(&sEventListenerManagersHash, aNode, PL_DHASH_LOOKUP)); if (PL_DHASH_ENTRY_IS_BUSY(entry)) { NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NATIVE_PTR(entry->mListenerManager, nsEventListenerManager, "[via hash] mListenerManager") } } nsEventListenerManager* nsContentUtils::GetListenerManager(nsINode *aNode, bool aCreateIfNotFound) { if (!aCreateIfNotFound && !aNode->HasFlag(NODE_HAS_LISTENERMANAGER)) { return nullptr; } if (!sEventListenerManagersHash.ops) { // We're already shut down, don't bother creating an event listener // manager. return nullptr; } if (!aCreateIfNotFound) { EventListenerManagerMapEntry *entry = static_cast<EventListenerManagerMapEntry *> (PL_DHashTableOperate(&sEventListenerManagersHash, aNode, PL_DHASH_LOOKUP)); if (PL_DHASH_ENTRY_IS_BUSY(entry)) { return entry->mListenerManager; } return nullptr; } EventListenerManagerMapEntry *entry = static_cast<EventListenerManagerMapEntry *> (PL_DHashTableOperate(&sEventListenerManagersHash, aNode, PL_DHASH_ADD)); if (!entry) { return nullptr; } if (!entry->mListenerManager) { entry->mListenerManager = new nsEventListenerManager(aNode); aNode->SetFlags(NODE_HAS_LISTENERMANAGER); } return entry->mListenerManager; } /* static */ void nsContentUtils::RemoveListenerManager(nsINode *aNode) { if (sEventListenerManagersHash.ops) { EventListenerManagerMapEntry *entry = static_cast<EventListenerManagerMapEntry *> (PL_DHashTableOperate(&sEventListenerManagersHash, aNode, PL_DHASH_LOOKUP)); if (PL_DHASH_ENTRY_IS_BUSY(entry)) { nsRefPtr<nsEventListenerManager> listenerManager; listenerManager.swap(entry->mListenerManager); // Remove the entry and *then* do operations that could cause further // modification of sEventListenerManagersHash. See bug 334177. PL_DHashTableRawRemove(&sEventListenerManagersHash, entry); if (listenerManager) { listenerManager->Disconnect(); } } } } /* static */ bool nsContentUtils::IsValidNodeName(nsIAtom *aLocalName, nsIAtom *aPrefix, int32_t aNamespaceID) { if (aNamespaceID == kNameSpaceID_Unknown) { return false; } if (!aPrefix) { // If the prefix is null, then either the QName must be xmlns or the // namespace must not be XMLNS. return (aLocalName == nsGkAtoms::xmlns) == (aNamespaceID == kNameSpaceID_XMLNS); } // If the prefix is non-null then the namespace must not be null. if (aNamespaceID == kNameSpaceID_None) { return false; } // If the namespace is the XMLNS namespace then the prefix must be xmlns, // but the localname must not be xmlns. if (aNamespaceID == kNameSpaceID_XMLNS) { return aPrefix == nsGkAtoms::xmlns && aLocalName != nsGkAtoms::xmlns; } // If the namespace is not the XMLNS namespace then the prefix must not be // xmlns. // If the namespace is the XML namespace then the prefix can be anything. // If the namespace is not the XML namespace then the prefix must not be xml. return aPrefix != nsGkAtoms::xmlns && (aNamespaceID == kNameSpaceID_XML || aPrefix != nsGkAtoms::xml); } /* static */ nsresult nsContentUtils::CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment, bool aPreventScriptExecution, nsIDOMDocumentFragment** aReturn) { *aReturn = nullptr; NS_ENSURE_ARG(aContextNode); // If we don't have a document here, we can't get the right security context // for compiling event handlers... so just bail out. nsCOMPtr<nsIDocument> document = aContextNode->OwnerDoc(); bool isHTML = document->IsHTML(); #ifdef DEBUG nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(document); NS_ASSERTION(!isHTML || htmlDoc, "Should have HTMLDocument here!"); #endif if (isHTML) { nsCOMPtr<nsIDOMDocumentFragment> frag; NS_NewDocumentFragment(getter_AddRefs(frag), document->NodeInfoManager()); nsCOMPtr<nsIContent> contextAsContent = do_QueryInterface(aContextNode); if (contextAsContent && !contextAsContent->IsElement()) { contextAsContent = contextAsContent->GetParent(); if (contextAsContent && !contextAsContent->IsElement()) { // can this even happen? contextAsContent = nullptr; } } nsresult rv; nsCOMPtr<nsIContent> fragment = do_QueryInterface(frag); if (contextAsContent && !contextAsContent->IsHTML(nsGkAtoms::html)) { rv = ParseFragmentHTML(aFragment, fragment, contextAsContent->Tag(), contextAsContent->GetNameSpaceID(), (document->GetCompatibilityMode() == eCompatibility_NavQuirks), aPreventScriptExecution); } else { rv = ParseFragmentHTML(aFragment, fragment, nsGkAtoms::body, kNameSpaceID_XHTML, (document->GetCompatibilityMode() == eCompatibility_NavQuirks), aPreventScriptExecution); } frag.forget(aReturn); return rv; } nsAutoTArray<nsString, 32> tagStack; nsAutoString uriStr, nameStr; nsCOMPtr<nsIContent> content = do_QueryInterface(aContextNode); // just in case we have a text node if (content && !content->IsElement()) content = content->GetParent(); while (content && content->IsElement()) { nsString& tagName = *tagStack.AppendElement(); NS_ENSURE_TRUE(&tagName, NS_ERROR_OUT_OF_MEMORY); tagName = content->NodeInfo()->QualifiedName(); // see if we need to add xmlns declarations uint32_t count = content->GetAttrCount(); bool setDefaultNamespace = false; if (count > 0) { uint32_t index; for (index = 0; index < count; index++) { const nsAttrName* name = content->GetAttrNameAt(index); if (name->NamespaceEquals(kNameSpaceID_XMLNS)) { content->GetAttr(kNameSpaceID_XMLNS, name->LocalName(), uriStr); // really want something like nsXMLContentSerializer::SerializeAttr tagName.Append(NS_LITERAL_STRING(" xmlns")); // space important if (name->GetPrefix()) { tagName.Append(PRUnichar(':')); name->LocalName()->ToString(nameStr); tagName.Append(nameStr); } else { setDefaultNamespace = true; } tagName.Append(NS_LITERAL_STRING("=\"") + uriStr + NS_LITERAL_STRING("\"")); } } } if (!setDefaultNamespace) { nsINodeInfo* info = content->NodeInfo(); if (!info->GetPrefixAtom() && info->NamespaceID() != kNameSpaceID_None) { // We have no namespace prefix, but have a namespace ID. Push // default namespace attr in, so that our kids will be in our // namespace. info->GetNamespaceURI(uriStr); tagName.Append(NS_LITERAL_STRING(" xmlns=\"") + uriStr + NS_LITERAL_STRING("\"")); } } content = content->GetParent(); } return ParseFragmentXML(aFragment, document, tagStack, aPreventScriptExecution, aReturn); } /* static */ void nsContentUtils::DropFragmentParsers() { NS_IF_RELEASE(sHTMLFragmentParser); NS_IF_RELEASE(sXMLFragmentParser); NS_IF_RELEASE(sXMLFragmentSink); } /* static */ void nsContentUtils::XPCOMShutdown() { nsContentUtils::DropFragmentParsers(); } /* static */ nsresult nsContentUtils::ParseFragmentHTML(const nsAString& aSourceBuffer, nsIContent* aTargetNode, nsIAtom* aContextLocalName, int32_t aContextNamespace, bool aQuirks, bool aPreventScriptExecution) { if (nsContentUtils::sFragmentParsingActive) { NS_NOTREACHED("Re-entrant fragment parsing attempted."); return NS_ERROR_DOM_INVALID_STATE_ERR; } mozilla::AutoRestore<bool> guard(nsContentUtils::sFragmentParsingActive); nsContentUtils::sFragmentParsingActive = true; if (!sHTMLFragmentParser) { NS_ADDREF(sHTMLFragmentParser = new nsHtml5StringParser()); // Now sHTMLFragmentParser owns the object } nsresult rv = sHTMLFragmentParser->ParseFragment(aSourceBuffer, aTargetNode, aContextLocalName, aContextNamespace, aQuirks, aPreventScriptExecution); return rv; } /* static */ nsresult nsContentUtils::ParseDocumentHTML(const nsAString& aSourceBuffer, nsIDocument* aTargetDocument, bool aScriptingEnabledForNoscriptParsing) { if (nsContentUtils::sFragmentParsingActive) { NS_NOTREACHED("Re-entrant fragment parsing attempted."); return NS_ERROR_DOM_INVALID_STATE_ERR; } mozilla::AutoRestore<bool> guard(nsContentUtils::sFragmentParsingActive); nsContentUtils::sFragmentParsingActive = true; if (!sHTMLFragmentParser) { NS_ADDREF(sHTMLFragmentParser = new nsHtml5StringParser()); // Now sHTMLFragmentParser owns the object } nsresult rv = sHTMLFragmentParser->ParseDocument(aSourceBuffer, aTargetDocument, aScriptingEnabledForNoscriptParsing); return rv; } /* static */ nsresult nsContentUtils::ParseFragmentXML(const nsAString& aSourceBuffer, nsIDocument* aDocument, nsTArray<nsString>& aTagStack, bool aPreventScriptExecution, nsIDOMDocumentFragment** aReturn) { if (nsContentUtils::sFragmentParsingActive) { NS_NOTREACHED("Re-entrant fragment parsing attempted."); return NS_ERROR_DOM_INVALID_STATE_ERR; } mozilla::AutoRestore<bool> guard(nsContentUtils::sFragmentParsingActive); nsContentUtils::sFragmentParsingActive = true; if (!sXMLFragmentParser) { nsCOMPtr<nsIParser> parser = do_CreateInstance(kCParserCID); parser.forget(&sXMLFragmentParser); // sXMLFragmentParser now owns the parser } if (!sXMLFragmentSink) { NS_NewXMLFragmentContentSink(&sXMLFragmentSink); // sXMLFragmentSink now owns the sink } nsCOMPtr<nsIContentSink> contentsink = do_QueryInterface(sXMLFragmentSink); NS_ABORT_IF_FALSE(contentsink, "Sink doesn't QI to nsIContentSink!"); sXMLFragmentParser->SetContentSink(contentsink); sXMLFragmentSink->SetTargetDocument(aDocument); sXMLFragmentSink->SetPreventScriptExecution(aPreventScriptExecution); nsresult rv = sXMLFragmentParser->ParseFragment(aSourceBuffer, aTagStack); if (NS_FAILED(rv)) { // Drop the fragment parser and sink that might be in an inconsistent state NS_IF_RELEASE(sXMLFragmentParser); NS_IF_RELEASE(sXMLFragmentSink); return rv; } rv = sXMLFragmentSink->FinishFragmentParsing(aReturn); sXMLFragmentParser->Reset(); return rv; } /* static */ nsresult nsContentUtils::ConvertToPlainText(const nsAString& aSourceBuffer, nsAString& aResultBuffer, uint32_t aFlags, uint32_t aWrapCol) { nsCOMPtr<nsIURI> uri; NS_NewURI(getter_AddRefs(uri), "about:blank"); nsCOMPtr<nsIPrincipal> principal = do_CreateInstance(NS_NULLPRINCIPAL_CONTRACTID); nsCOMPtr<nsIDOMDocument> domDocument; nsresult rv = nsContentUtils::CreateDocument(EmptyString(), EmptyString(), nullptr, uri, uri, principal, nullptr, DocumentFlavorHTML, getter_AddRefs(domDocument)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDocument> document = do_QueryInterface(domDocument); rv = nsContentUtils::ParseDocumentHTML(aSourceBuffer, document, !(aFlags & nsIDocumentEncoder::OutputNoScriptContent)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDocumentEncoder> encoder = do_CreateInstance( "@mozilla.org/layout/documentEncoder;1?type=text/plain"); rv = encoder->Init(domDocument, NS_LITERAL_STRING("text/plain"), aFlags); NS_ENSURE_SUCCESS(rv, rv); encoder->SetWrapColumn(aWrapCol); return encoder->EncodeToString(aResultBuffer); } /* static */ nsresult nsContentUtils::CreateDocument(const nsAString& aNamespaceURI, const nsAString& aQualifiedName, nsIDOMDocumentType* aDoctype, nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal, nsIScriptGlobalObject* aEventObject, DocumentFlavor aFlavor, nsIDOMDocument** aResult) { return NS_NewDOMDocument(aResult, aNamespaceURI, aQualifiedName, aDoctype, aDocumentURI, aBaseURI, aPrincipal, true, aEventObject, aFlavor); } /* static */ nsresult nsContentUtils::SetNodeTextContent(nsIContent* aContent, const nsAString& aValue, bool aTryReuse) { // Fire DOMNodeRemoved mutation events before we do anything else. nsCOMPtr<nsIContent> owningContent; // Batch possible DOMSubtreeModified events. mozAutoSubtreeModified subtree(nullptr, nullptr); // Scope firing mutation events so that we don't carry any state that // might be stale { // We're relying on mozAutoSubtreeModified to keep a strong reference if // needed. nsIDocument* doc = aContent->OwnerDoc(); // Optimize the common case of there being no observers if (HasMutationListeners(doc, NS_EVENT_BITS_MUTATION_NODEREMOVED)) { subtree.UpdateTarget(doc, nullptr); owningContent = aContent; nsCOMPtr<nsINode> child; bool skipFirst = aTryReuse; for (child = aContent->GetFirstChild(); child && child->GetNodeParent() == aContent; child = child->GetNextSibling()) { if (skipFirst && child->IsNodeOfType(nsINode::eTEXT)) { skipFirst = false; continue; } nsContentUtils::MaybeFireNodeRemoved(child, aContent, doc); } } } // Might as well stick a batch around this since we're performing several // mutations. mozAutoDocUpdate updateBatch(aContent->GetCurrentDoc(), UPDATE_CONTENT_MODEL, true); nsAutoMutationBatch mb; uint32_t childCount = aContent->GetChildCount(); if (aTryReuse && !aValue.IsEmpty()) { uint32_t removeIndex = 0; for (uint32_t i = 0; i < childCount; ++i) { nsIContent* child = aContent->GetChildAt(removeIndex); if (removeIndex == 0 && child && child->IsNodeOfType(nsINode::eTEXT)) { nsresult rv = child->SetText(aValue, true); NS_ENSURE_SUCCESS(rv, rv); removeIndex = 1; } else { aContent->RemoveChildAt(removeIndex, true); } } if (removeIndex == 1) { return NS_OK; } } else { mb.Init(aContent, true, false); for (uint32_t i = 0; i < childCount; ++i) { aContent->RemoveChildAt(0, true); } } mb.RemovalDone(); if (aValue.IsEmpty()) { return NS_OK; } nsCOMPtr<nsIContent> textContent; nsresult rv = NS_NewTextNode(getter_AddRefs(textContent), aContent->NodeInfo()->NodeInfoManager()); NS_ENSURE_SUCCESS(rv, rv); textContent->SetText(aValue, true); rv = aContent->AppendChildTo(textContent, true); mb.NodesAdded(); return rv; } static void AppendNodeTextContentsRecurse(nsINode* aNode, nsAString& aResult) { for (nsIContent* child = aNode->GetFirstChild(); child; child = child->GetNextSibling()) { if (child->IsElement()) { AppendNodeTextContentsRecurse(child, aResult); } else if (child->IsNodeOfType(nsINode::eTEXT)) { child->AppendTextTo(aResult); } } } /* static */ void nsContentUtils::AppendNodeTextContent(nsINode* aNode, bool aDeep, nsAString& aResult) { if (aNode->IsNodeOfType(nsINode::eTEXT)) { static_cast<nsIContent*>(aNode)->AppendTextTo(aResult); } else if (aDeep) { AppendNodeTextContentsRecurse(aNode, aResult); } else { for (nsIContent* child = aNode->GetFirstChild(); child; child = child->GetNextSibling()) { if (child->IsNodeOfType(nsINode::eTEXT)) { child->AppendTextTo(aResult); } } } } bool nsContentUtils::HasNonEmptyTextContent(nsINode* aNode) { for (nsIContent* child = aNode->GetFirstChild(); child; child = child->GetNextSibling()) { if (child->IsNodeOfType(nsINode::eTEXT) && child->TextLength() > 0) { return true; } } return false; } /* static */ bool nsContentUtils::IsInSameAnonymousTree(const nsINode* aNode, const nsIContent* aContent) { NS_PRECONDITION(aNode, "Must have a node to work with"); NS_PRECONDITION(aContent, "Must have a content to work with"); if (!aNode->IsNodeOfType(nsINode::eCONTENT)) { /** * The root isn't an nsIContent, so it's a document or attribute. The only * nodes in the same anonymous subtree as it will have a null * bindingParent. * * XXXbz strictly speaking, that's not true for attribute nodes. */ return aContent->GetBindingParent() == nullptr; } return static_cast<const nsIContent*>(aNode)->GetBindingParent() == aContent->GetBindingParent(); } class AnonymousContentDestroyer : public nsRunnable { public: AnonymousContentDestroyer(nsCOMPtr<nsIContent>* aContent) { mContent.swap(*aContent); mParent = mContent->GetParent(); mDoc = mContent->OwnerDoc(); } NS_IMETHOD Run() { mContent->UnbindFromTree(); return NS_OK; } private: nsCOMPtr<nsIContent> mContent; // Hold strong refs to the parent content and document so that they // don't die unexpectedly nsCOMPtr<nsIDocument> mDoc; nsCOMPtr<nsIContent> mParent; }; /* static */ void nsContentUtils::DestroyAnonymousContent(nsCOMPtr<nsIContent>* aContent) { if (*aContent) { AddScriptRunner(new AnonymousContentDestroyer(aContent)); } } /* static */ nsresult nsContentUtils::HoldJSObjects(void* aScriptObjectHolder, nsScriptObjectTracer* aTracer) { NS_ENSURE_TRUE(sXPConnect, NS_ERROR_UNEXPECTED); return sXPConnect->AddJSHolder(aScriptObjectHolder, aTracer); } /* static */ nsresult nsContentUtils::DropJSObjects(void* aScriptObjectHolder) { if (!sXPConnect) { return NS_OK; } return sXPConnect->RemoveJSHolder(aScriptObjectHolder); } #ifdef DEBUG /* static */ bool nsContentUtils::AreJSObjectsHeld(void* aScriptHolder) { bool isHeld = false; sXPConnect->TestJSHolder(aScriptHolder, &isHeld); return isHeld; } #endif /* static */ void nsContentUtils::NotifyInstalledMenuKeyboardListener(bool aInstalling) { nsIMEStateManager::OnInstalledMenuKeyboardListener(aInstalling); } static bool SchemeIs(nsIURI* aURI, const char* aScheme) { nsCOMPtr<nsIURI> baseURI = NS_GetInnermostURI(aURI); NS_ENSURE_TRUE(baseURI, false); bool isScheme = false; return NS_SUCCEEDED(baseURI->SchemeIs(aScheme, &isScheme)) && isScheme; } /* static */ nsresult nsContentUtils::CheckSecurityBeforeLoad(nsIURI* aURIToLoad, nsIPrincipal* aLoadingPrincipal, uint32_t aCheckLoadFlags, bool aAllowData, uint32_t aContentPolicyType, nsISupports* aContext, const nsACString& aMimeGuess, nsISupports* aExtra) { NS_PRECONDITION(aLoadingPrincipal, "Must have a loading principal here"); bool isSystemPrin = false; if (NS_SUCCEEDED(sSecurityManager->IsSystemPrincipal(aLoadingPrincipal, &isSystemPrin)) && isSystemPrin) { return NS_OK; } // XXXbz do we want to fast-path skin stylesheets loading XBL here somehow? // CheckLoadURIWithPrincipal nsresult rv = sSecurityManager-> CheckLoadURIWithPrincipal(aLoadingPrincipal, aURIToLoad, aCheckLoadFlags); NS_ENSURE_SUCCESS(rv, rv); // Content Policy int16_t shouldLoad = nsIContentPolicy::ACCEPT; rv = NS_CheckContentLoadPolicy(aContentPolicyType, aURIToLoad, aLoadingPrincipal, aContext, aMimeGuess, aExtra, &shouldLoad, GetContentPolicy(), sSecurityManager); NS_ENSURE_SUCCESS(rv, rv); if (NS_CP_REJECTED(shouldLoad)) { return NS_ERROR_CONTENT_BLOCKED; } // Same Origin if ((aAllowData && SchemeIs(aURIToLoad, "data")) || ((aCheckLoadFlags & nsIScriptSecurityManager::ALLOW_CHROME) && SchemeIs(aURIToLoad, "chrome"))) { return NS_OK; } return aLoadingPrincipal->CheckMayLoad(aURIToLoad, true, false); } bool nsContentUtils::IsSystemPrincipal(nsIPrincipal* aPrincipal) { bool isSystem; nsresult rv = sSecurityManager->IsSystemPrincipal(aPrincipal, &isSystem); return NS_SUCCEEDED(rv) && isSystem; } bool nsContentUtils::CombineResourcePrincipals(nsCOMPtr<nsIPrincipal>* aResourcePrincipal, nsIPrincipal* aExtraPrincipal) { if (!aExtraPrincipal) { return false; } if (!*aResourcePrincipal) { *aResourcePrincipal = aExtraPrincipal; return true; } if (*aResourcePrincipal == aExtraPrincipal) { return false; } bool subsumes; if (NS_SUCCEEDED((*aResourcePrincipal)->Subsumes(aExtraPrincipal, &subsumes)) && subsumes) { return false; } sSecurityManager->GetSystemPrincipal(getter_AddRefs(*aResourcePrincipal)); return true; } /* static */ void nsContentUtils::TriggerLink(nsIContent *aContent, nsPresContext *aPresContext, nsIURI *aLinkURI, const nsString &aTargetSpec, bool aClick, bool aIsUserTriggered, bool aIsTrusted) { NS_ASSERTION(aPresContext, "Need a nsPresContext"); NS_PRECONDITION(aLinkURI, "No link URI"); if (aContent->IsEditable()) { return; } nsILinkHandler *handler = aPresContext->GetLinkHandler(); if (!handler) { return; } if (!aClick) { handler->OnOverLink(aContent, aLinkURI, aTargetSpec.get()); return; } // Check that this page is allowed to load this URI. nsresult proceed = NS_OK; if (sSecurityManager) { uint32_t flag = aIsUserTriggered ? (uint32_t)nsIScriptSecurityManager::STANDARD : (uint32_t)nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT; proceed = sSecurityManager->CheckLoadURIWithPrincipal(aContent->NodePrincipal(), aLinkURI, flag); } // Only pass off the click event if the script security manager says it's ok. if (NS_SUCCEEDED(proceed)) { handler->OnLinkClick(aContent, aLinkURI, aTargetSpec.get(), nullptr, nullptr, aIsTrusted); } } /* static */ void nsContentUtils::GetLinkLocation(Element* aElement, nsString& aLocationString) { nsCOMPtr<nsIURI> hrefURI = aElement->GetHrefURI(); if (hrefURI) { nsAutoCString specUTF8; nsresult rv = hrefURI->GetSpec(specUTF8); if (NS_SUCCEEDED(rv)) CopyUTF8toUTF16(specUTF8, aLocationString); } } /* static */ nsIWidget* nsContentUtils::GetTopLevelWidget(nsIWidget* aWidget) { if (!aWidget) return nullptr; return aWidget->GetTopLevelWidget(); } /* static */ const nsDependentString nsContentUtils::GetLocalizedEllipsis() { static PRUnichar sBuf[4] = { 0, 0, 0, 0 }; if (!sBuf[0]) { nsAdoptingString tmp = Preferences::GetLocalizedString("intl.ellipsis"); uint32_t len = NS_MIN(uint32_t(tmp.Length()), uint32_t(ArrayLength(sBuf) - 1)); CopyUnicodeTo(tmp, 0, sBuf, len); if (!sBuf[0]) sBuf[0] = PRUnichar(0x2026); } return nsDependentString(sBuf); } //static nsEvent* nsContentUtils::GetNativeEvent(nsIDOMEvent* aDOMEvent) { return aDOMEvent ? aDOMEvent->GetInternalNSEvent() : nullptr; } //static bool nsContentUtils::DOMEventToNativeKeyEvent(nsIDOMKeyEvent* aKeyEvent, nsNativeKeyEvent* aNativeEvent, bool aGetCharCode) { bool defaultPrevented; aKeyEvent->GetPreventDefault(&defaultPrevented); if (defaultPrevented) return false; bool trusted = false; aKeyEvent->GetIsTrusted(&trusted); if (!trusted) return false; if (aGetCharCode) { aKeyEvent->GetCharCode(&aNativeEvent->charCode); } else { aNativeEvent->charCode = 0; } aKeyEvent->GetKeyCode(&aNativeEvent->keyCode); aKeyEvent->GetAltKey(&aNativeEvent->altKey); aKeyEvent->GetCtrlKey(&aNativeEvent->ctrlKey); aKeyEvent->GetShiftKey(&aNativeEvent->shiftKey); aKeyEvent->GetMetaKey(&aNativeEvent->metaKey); aNativeEvent->nativeEvent = GetNativeEvent(aKeyEvent); return true; } static bool HasASCIIDigit(const nsTArray<nsShortcutCandidate>& aCandidates) { for (uint32_t i = 0; i < aCandidates.Length(); ++i) { uint32_t ch = aCandidates[i].mCharCode; if (ch >= '0' && ch <= '9') return true; } return false; } static bool CharsCaseInsensitiveEqual(uint32_t aChar1, uint32_t aChar2) { return aChar1 == aChar2 || (IS_IN_BMP(aChar1) && IS_IN_BMP(aChar2) && ToLowerCase(PRUnichar(aChar1)) == ToLowerCase(PRUnichar(aChar2))); } static bool IsCaseChangeableChar(uint32_t aChar) { return IS_IN_BMP(aChar) && ToLowerCase(PRUnichar(aChar)) != ToUpperCase(PRUnichar(aChar)); } /* static */ void nsContentUtils::GetAccelKeyCandidates(nsIDOMKeyEvent* aDOMKeyEvent, nsTArray<nsShortcutCandidate>& aCandidates) { NS_PRECONDITION(aCandidates.IsEmpty(), "aCandidates must be empty"); nsAutoString eventType; aDOMKeyEvent->GetType(eventType); // Don't process if aDOMKeyEvent is not a keypress event. if (!eventType.EqualsLiteral("keypress")) return; nsKeyEvent* nativeKeyEvent = static_cast<nsKeyEvent*>(GetNativeEvent(aDOMKeyEvent)); if (nativeKeyEvent) { NS_ASSERTION(nativeKeyEvent->eventStructType == NS_KEY_EVENT, "wrong type of native event"); // nsShortcutCandidate::mCharCode is a candidate charCode. // nsShoftcutCandidate::mIgnoreShift means the mCharCode should be tried to // execute a command with/without shift key state. If this is TRUE, the // shifted key state should be ignored. Otherwise, don't ignore the state. // the priority of the charCodes are (shift key is not pressed): // 0: charCode/false, // 1: unshiftedCharCodes[0]/false, 2: unshiftedCharCodes[1]/false... // the priority of the charCodes are (shift key is pressed): // 0: charCode/false, // 1: shiftedCharCodes[0]/false, 2: shiftedCharCodes[0]/true, // 3: shiftedCharCodes[1]/false, 4: shiftedCharCodes[1]/true... if (nativeKeyEvent->charCode) { nsShortcutCandidate key(nativeKeyEvent->charCode, false); aCandidates.AppendElement(key); } uint32_t len = nativeKeyEvent->alternativeCharCodes.Length(); if (!nativeKeyEvent->IsShift()) { for (uint32_t i = 0; i < len; ++i) { uint32_t ch = nativeKeyEvent->alternativeCharCodes[i].mUnshiftedCharCode; if (!ch || ch == nativeKeyEvent->charCode) continue; nsShortcutCandidate key(ch, false); aCandidates.AppendElement(key); } // If unshiftedCharCodes doesn't have numeric but shiftedCharCode has it, // this keyboard layout is AZERTY or similar layout, probably. // In this case, Accel+[0-9] should be accessible without shift key. // However, the priority should be lowest. if (!HasASCIIDigit(aCandidates)) { for (uint32_t i = 0; i < len; ++i) { uint32_t ch = nativeKeyEvent->alternativeCharCodes[i].mShiftedCharCode; if (ch >= '0' && ch <= '9') { nsShortcutCandidate key(ch, false); aCandidates.AppendElement(key); break; } } } } else { for (uint32_t i = 0; i < len; ++i) { uint32_t ch = nativeKeyEvent->alternativeCharCodes[i].mShiftedCharCode; if (!ch) continue; if (ch != nativeKeyEvent->charCode) { nsShortcutCandidate key(ch, false); aCandidates.AppendElement(key); } // If the char is an alphabet, the shift key state should not be // ignored. E.g., Ctrl+Shift+C should not execute Ctrl+C. // And checking the charCode is same as unshiftedCharCode too. // E.g., for Ctrl+Shift+(Plus of Numpad) should not run Ctrl+Plus. uint32_t unshiftCh = nativeKeyEvent->alternativeCharCodes[i].mUnshiftedCharCode; if (CharsCaseInsensitiveEqual(ch, unshiftCh)) continue; // On the Hebrew keyboard layout on Windows, the unshifted char is a // localized character but the shifted char is a Latin alphabet, // then, we should not execute without the shift state. See bug 433192. if (IsCaseChangeableChar(ch)) continue; // Setting the alternative charCode candidates for retry without shift // key state only when the shift key is pressed. nsShortcutCandidate key(ch, true); aCandidates.AppendElement(key); } } } else { uint32_t charCode; aDOMKeyEvent->GetCharCode(&charCode); if (charCode) { nsShortcutCandidate key(charCode, false); aCandidates.AppendElement(key); } } } /* static */ void nsContentUtils::GetAccessKeyCandidates(nsKeyEvent* aNativeKeyEvent, nsTArray<uint32_t>& aCandidates) { NS_PRECONDITION(aCandidates.IsEmpty(), "aCandidates must be empty"); // return the lower cased charCode candidates for access keys. // the priority of the charCodes are: // 0: charCode, 1: unshiftedCharCodes[0], 2: shiftedCharCodes[0] // 3: unshiftedCharCodes[1], 4: shiftedCharCodes[1],... if (aNativeKeyEvent->charCode) { uint32_t ch = aNativeKeyEvent->charCode; if (IS_IN_BMP(ch)) ch = ToLowerCase(PRUnichar(ch)); aCandidates.AppendElement(ch); } for (uint32_t i = 0; i < aNativeKeyEvent->alternativeCharCodes.Length(); ++i) { uint32_t ch[2] = { aNativeKeyEvent->alternativeCharCodes[i].mUnshiftedCharCode, aNativeKeyEvent->alternativeCharCodes[i].mShiftedCharCode }; for (uint32_t j = 0; j < 2; ++j) { if (!ch[j]) continue; if (IS_IN_BMP(ch[j])) ch[j] = ToLowerCase(PRUnichar(ch[j])); // Don't append the charCode that was already appended. if (aCandidates.IndexOf(ch[j]) == aCandidates.NoIndex) aCandidates.AppendElement(ch[j]); } } return; } /* static */ void nsContentUtils::AddScriptBlocker() { if (!sScriptBlockerCount) { NS_ASSERTION(sRunnersCountAtFirstBlocker == 0, "Should not already have a count"); sRunnersCountAtFirstBlocker = sBlockedScriptRunners->Length(); } ++sScriptBlockerCount; } #ifdef DEBUG static bool sRemovingScriptBlockers = false; #endif /* static */ void nsContentUtils::RemoveScriptBlocker() { MOZ_ASSERT(!sRemovingScriptBlockers); NS_ASSERTION(sScriptBlockerCount != 0, "Negative script blockers"); --sScriptBlockerCount; if (sScriptBlockerCount) { return; } uint32_t firstBlocker = sRunnersCountAtFirstBlocker; uint32_t lastBlocker = sBlockedScriptRunners->Length(); uint32_t originalFirstBlocker = firstBlocker; uint32_t blockersCount = lastBlocker - firstBlocker; sRunnersCountAtFirstBlocker = 0; NS_ASSERTION(firstBlocker <= lastBlocker, "bad sRunnersCountAtFirstBlocker"); while (firstBlocker < lastBlocker) { nsCOMPtr<nsIRunnable> runnable; runnable.swap((*sBlockedScriptRunners)[firstBlocker]); ++firstBlocker; // Calling the runnable can reenter us runnable->Run(); // So can dropping the reference to the runnable runnable = nullptr; NS_ASSERTION(sRunnersCountAtFirstBlocker == 0, "Bad count"); NS_ASSERTION(!sScriptBlockerCount, "This is really bad"); } #ifdef DEBUG AutoRestore<bool> removingScriptBlockers(sRemovingScriptBlockers); sRemovingScriptBlockers = true; #endif sBlockedScriptRunners->RemoveElementsAt(originalFirstBlocker, blockersCount); } /* static */ bool nsContentUtils::AddScriptRunner(nsIRunnable* aRunnable) { if (!aRunnable) { return false; } if (sScriptBlockerCount) { return sBlockedScriptRunners->AppendElement(aRunnable) != nullptr; } nsCOMPtr<nsIRunnable> run = aRunnable; run->Run(); return true; } void nsContentUtils::LeaveMicroTask() { if (--sMicroTaskLevel == 0) { nsDOMMutationObserver::HandleMutations(); } } /* * Helper function for nsContentUtils::ProcessViewportInfo. * * Handles a single key=value pair. If it corresponds to a valid viewport * attribute, add it to the document header data. No validation is done on the * value itself (this is done at display time). */ static void ProcessViewportToken(nsIDocument *aDocument, const nsAString &token) { /* Iterators. */ nsAString::const_iterator tip, tail, end; token.BeginReading(tip); tail = tip; token.EndReading(end); /* Move tip to the '='. */ while ((tip != end) && (*tip != '=')) ++tip; /* If we didn't find an '=', punt. */ if (tip == end) return; /* Extract the key and value. */ const nsAString &key = nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(Substring(tail, tip), true); const nsAString &value = nsContentUtils::TrimWhitespace<nsCRT::IsAsciiSpace>(Substring(++tip, end), true); /* Check for known keys. If we find a match, insert the appropriate * information into the document header. */ nsCOMPtr<nsIAtom> key_atom = do_GetAtom(key); if (key_atom == nsGkAtoms::height) aDocument->SetHeaderData(nsGkAtoms::viewport_height, value); else if (key_atom == nsGkAtoms::width) aDocument->SetHeaderData(nsGkAtoms::viewport_width, value); else if (key_atom == nsGkAtoms::initial_scale) aDocument->SetHeaderData(nsGkAtoms::viewport_initial_scale, value); else if (key_atom == nsGkAtoms::minimum_scale) aDocument->SetHeaderData(nsGkAtoms::viewport_minimum_scale, value); else if (key_atom == nsGkAtoms::maximum_scale) aDocument->SetHeaderData(nsGkAtoms::viewport_maximum_scale, value); else if (key_atom == nsGkAtoms::user_scalable) aDocument->SetHeaderData(nsGkAtoms::viewport_user_scalable, value); } #define IS_SEPARATOR(c) ((c == '=') || (c == ',') || (c == ';') || \ (c == '\t') || (c == '\n') || (c == '\r')) /* static */ nsViewportInfo nsContentUtils::GetViewportInfo(nsIDocument *aDocument, uint32_t aDisplayWidth, uint32_t aDisplayHeight) { nsAutoString viewport; aDocument->GetHeaderData(nsGkAtoms::viewport, viewport); if (viewport.IsEmpty()) { // If the docType specifies that we are on a site optimized for mobile, // then we want to return specially crafted defaults for the viewport info. nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(aDocument)); nsCOMPtr<nsIDOMDocumentType> docType; nsresult rv = domDoc->GetDoctype(getter_AddRefs(docType)); if (NS_SUCCEEDED(rv) && docType) { nsAutoString docId; rv = docType->GetPublicId(docId); if (NS_SUCCEEDED(rv)) { if ((docId.Find("WAP") != -1) || (docId.Find("Mobile") != -1) || (docId.Find("WML") != -1)) { nsViewportInfo ret(aDisplayWidth, aDisplayHeight); return ret; } } } nsAutoString handheldFriendly; aDocument->GetHeaderData(nsGkAtoms::handheldFriendly, handheldFriendly); if (handheldFriendly.EqualsLiteral("true")) { nsViewportInfo ret(aDisplayWidth, aDisplayHeight); return ret; } } nsAutoString minScaleStr; aDocument->GetHeaderData(nsGkAtoms::viewport_minimum_scale, minScaleStr); nsresult errorCode; float scaleMinFloat = minScaleStr.ToFloat(&errorCode); if (NS_FAILED(errorCode)) { scaleMinFloat = kViewportMinScale; } scaleMinFloat = NS_MIN((double)scaleMinFloat, kViewportMaxScale); scaleMinFloat = NS_MAX((double)scaleMinFloat, kViewportMinScale); nsAutoString maxScaleStr; aDocument->GetHeaderData(nsGkAtoms::viewport_maximum_scale, maxScaleStr); // We define a special error code variable for the scale and max scale, // because they are used later (see the width calculations). nsresult scaleMaxErrorCode; float scaleMaxFloat = maxScaleStr.ToFloat(&scaleMaxErrorCode); if (NS_FAILED(scaleMaxErrorCode)) { scaleMaxFloat = kViewportMaxScale; } scaleMaxFloat = NS_MIN((double)scaleMaxFloat, kViewportMaxScale); scaleMaxFloat = NS_MAX((double)scaleMaxFloat, kViewportMinScale); nsAutoString scaleStr; aDocument->GetHeaderData(nsGkAtoms::viewport_initial_scale, scaleStr); nsresult scaleErrorCode; float scaleFloat = scaleStr.ToFloat(&scaleErrorCode); nsAutoString widthStr, heightStr; aDocument->GetHeaderData(nsGkAtoms::viewport_height, heightStr); aDocument->GetHeaderData(nsGkAtoms::viewport_width, widthStr); bool autoSize = false; if (widthStr.EqualsLiteral("device-width")) { autoSize = true; } if (widthStr.IsEmpty() && (heightStr.EqualsLiteral("device-height") || scaleFloat == 1.0)) { autoSize = true; } // Now convert the scale into device pixels per CSS pixel. nsIWidget *widget = WidgetForDocument(aDocument); #ifdef MOZ_WIDGET_ANDROID // Temporarily use special Android code until bug 803207 is fixed double pixelRatio = widget ? GetDevicePixelsPerMetaViewportPixel(widget) : 1.0; #else double pixelRatio = widget ? widget->GetDefaultScale() : 1.0; #endif scaleFloat *= pixelRatio; scaleMinFloat *= pixelRatio; scaleMaxFloat *= pixelRatio; uint32_t width, height; if (autoSize) { // aDisplayWidth and aDisplayHeight are in device pixels; convert them to // CSS pixels for the viewport size. width = aDisplayWidth / pixelRatio; height = aDisplayHeight / pixelRatio; } else { nsresult widthErrorCode, heightErrorCode; width = widthStr.ToInteger(&widthErrorCode); height = heightStr.ToInteger(&heightErrorCode); // If width or height has not been set to a valid number by this point, // fall back to a default value. bool validWidth = (!widthStr.IsEmpty() && NS_SUCCEEDED(widthErrorCode) && width > 0); bool validHeight = (!heightStr.IsEmpty() && NS_SUCCEEDED(heightErrorCode) && height > 0); if (!validWidth) { if (validHeight && aDisplayWidth > 0 && aDisplayHeight > 0) { width = uint32_t((height * aDisplayWidth) / aDisplayHeight); } else { width = Preferences::GetInt("browser.viewport.desktopWidth", kViewportDefaultScreenWidth); } } if (!validHeight) { if (aDisplayWidth > 0 && aDisplayHeight > 0) { height = uint32_t((width * aDisplayHeight) / aDisplayWidth); } else { height = width; } } } width = NS_MIN(width, kViewportMaxWidth); width = NS_MAX(width, kViewportMinWidth); // Also recalculate the default zoom, if it wasn't specified in the metadata, // and the width is specified. if (scaleStr.IsEmpty() && !widthStr.IsEmpty()) { scaleFloat = NS_MAX(scaleFloat, float(aDisplayWidth) / float(width)); } height = NS_MIN(height, kViewportMaxHeight); height = NS_MAX(height, kViewportMinHeight); // We need to perform a conversion, but only if the initial or maximum // scale were set explicitly by the user. if (!scaleStr.IsEmpty() && NS_SUCCEEDED(scaleErrorCode)) { width = NS_MAX(width, (uint32_t)(aDisplayWidth / scaleFloat)); height = NS_MAX(height, (uint32_t)(aDisplayHeight / scaleFloat)); } else if (!maxScaleStr.IsEmpty() && NS_SUCCEEDED(scaleMaxErrorCode)) { width = NS_MAX(width, (uint32_t)(aDisplayWidth / scaleMaxFloat)); height = NS_MAX(height, (uint32_t)(aDisplayHeight / scaleMaxFloat)); } bool allowZoom = true; nsAutoString userScalable; aDocument->GetHeaderData(nsGkAtoms::viewport_user_scalable, userScalable); if ((userScalable.EqualsLiteral("0")) || (userScalable.EqualsLiteral("no")) || (userScalable.EqualsLiteral("false"))) { allowZoom = false; } nsViewportInfo ret(scaleFloat, scaleMinFloat, scaleMaxFloat, width, height, autoSize, allowZoom); return ret; } #ifdef MOZ_WIDGET_ANDROID /* static */ double nsContentUtils::GetDevicePixelsPerMetaViewportPixel(nsIWidget* aWidget) { int32_t prefValue = Preferences::GetInt("browser.viewport.scaleRatio", 0); if (prefValue > 0) { return double(prefValue) / 100.0; } float dpi = aWidget->GetDPI(); if (dpi < 200.0) { // Includes desktop displays, LDPI and MDPI Android devices return 1.0; } if (dpi < 300.0) { // Includes Nokia N900, and HDPI Android devices return 1.5; } // For very high-density displays like the iPhone 4, use an integer ratio. return floor(dpi / 150.0); } #endif /* static */ nsresult nsContentUtils::ProcessViewportInfo(nsIDocument *aDocument, const nsAString &viewportInfo) { /* We never fail. */ nsresult rv = NS_OK; aDocument->SetHeaderData(nsGkAtoms::viewport, viewportInfo); /* Iterators. */ nsAString::const_iterator tip, tail, end; viewportInfo.BeginReading(tip); tail = tip; viewportInfo.EndReading(end); /* Read the tip to the first non-separator character. */ while ((tip != end) && (IS_SEPARATOR(*tip) || nsCRT::IsAsciiSpace(*tip))) ++tip; /* Read through and find tokens separated by separators. */ while (tip != end) { /* Synchronize tip and tail. */ tail = tip; /* Advance tip past non-separator characters. */ while ((tip != end) && !IS_SEPARATOR(*tip)) ++tip; /* Allow white spaces that surround the '=' character */ if ((tip != end) && (*tip == '=')) { ++tip; while ((tip != end) && nsCRT::IsAsciiSpace(*tip)) ++tip; while ((tip != end) && !(IS_SEPARATOR(*tip) || nsCRT::IsAsciiSpace(*tip))) ++tip; } /* Our token consists of the characters between tail and tip. */ ProcessViewportToken(aDocument, Substring(tail, tip)); /* Skip separators. */ while ((tip != end) && (IS_SEPARATOR(*tip) || nsCRT::IsAsciiSpace(*tip))) ++tip; } return rv; } #undef IS_SEPARATOR /* static */ void nsContentUtils::HidePopupsInDocument(nsIDocument* aDocument) { #ifdef MOZ_XUL nsXULPopupManager* pm = nsXULPopupManager::GetInstance(); if (pm && aDocument) { nsCOMPtr<nsISupports> container = aDocument->GetContainer(); nsCOMPtr<nsIDocShellTreeItem> docShellToHide = do_QueryInterface(container); if (docShellToHide) pm->HidePopupsInDocShell(docShellToHide); } #endif } /* static */ already_AddRefed<nsIDragSession> nsContentUtils::GetDragSession() { nsIDragSession* dragSession = nullptr; nsCOMPtr<nsIDragService> dragService = do_GetService("@mozilla.org/widget/dragservice;1"); if (dragService) dragService->GetCurrentSession(&dragSession); return dragSession; } /* static */ nsresult nsContentUtils::SetDataTransferInEvent(nsDragEvent* aDragEvent) { if (aDragEvent->dataTransfer || !NS_IS_TRUSTED_EVENT(aDragEvent)) return NS_OK; // For draggesture and dragstart events, the data transfer object is // created before the event fires, so it should already be set. For other // drag events, get the object from the drag session. NS_ASSERTION(aDragEvent->message != NS_DRAGDROP_GESTURE && aDragEvent->message != NS_DRAGDROP_START, "draggesture event created without a dataTransfer"); nsCOMPtr<nsIDragSession> dragSession = GetDragSession(); NS_ENSURE_TRUE(dragSession, NS_OK); // no drag in progress nsCOMPtr<nsIDOMDataTransfer> initialDataTransfer; dragSession->GetDataTransfer(getter_AddRefs(initialDataTransfer)); if (!initialDataTransfer) { // A dataTransfer won't exist when a drag was started by some other // means, for instance calling the drag service directly, or a drag // from another application. In either case, a new dataTransfer should // be created that reflects the data. initialDataTransfer = new nsDOMDataTransfer(aDragEvent->message); NS_ENSURE_TRUE(initialDataTransfer, NS_ERROR_OUT_OF_MEMORY); // now set it in the drag session so we don't need to create it again dragSession->SetDataTransfer(initialDataTransfer); } bool isCrossDomainSubFrameDrop = false; if (aDragEvent->message == NS_DRAGDROP_DROP || aDragEvent->message == NS_DRAGDROP_DRAGDROP) { isCrossDomainSubFrameDrop = CheckForSubFrameDrop(dragSession, aDragEvent); } // each event should use a clone of the original dataTransfer. initialDataTransfer->Clone(aDragEvent->message, aDragEvent->userCancelled, isCrossDomainSubFrameDrop, getter_AddRefs(aDragEvent->dataTransfer)); NS_ENSURE_TRUE(aDragEvent->dataTransfer, NS_ERROR_OUT_OF_MEMORY); // for the dragenter and dragover events, initialize the drop effect // from the drop action, which platform specific widget code sets before // the event is fired based on the keyboard state. if (aDragEvent->message == NS_DRAGDROP_ENTER || aDragEvent->message == NS_DRAGDROP_OVER) { uint32_t action, effectAllowed; dragSession->GetDragAction(&action); aDragEvent->dataTransfer->GetEffectAllowedInt(&effectAllowed); aDragEvent->dataTransfer->SetDropEffectInt(FilterDropEffect(action, effectAllowed)); } else if (aDragEvent->message == NS_DRAGDROP_DROP || aDragEvent->message == NS_DRAGDROP_DRAGDROP || aDragEvent->message == NS_DRAGDROP_END) { // For the drop and dragend events, set the drop effect based on the // last value that the dropEffect had. This will have been set in // nsEventStateManager::PostHandleEvent for the last dragenter or // dragover event. uint32_t dropEffect; initialDataTransfer->GetDropEffectInt(&dropEffect); aDragEvent->dataTransfer->SetDropEffectInt(dropEffect); } return NS_OK; } /* static */ uint32_t nsContentUtils::FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed) { // It is possible for the drag action to include more than one action, but // the widget code which sets the action from the keyboard state should only // be including one. If multiple actions were set, we just consider them in // the following order: // copy, link, move if (aAction & nsIDragService::DRAGDROP_ACTION_COPY) aAction = nsIDragService::DRAGDROP_ACTION_COPY; else if (aAction & nsIDragService::DRAGDROP_ACTION_LINK) aAction = nsIDragService::DRAGDROP_ACTION_LINK; else if (aAction & nsIDragService::DRAGDROP_ACTION_MOVE) aAction = nsIDragService::DRAGDROP_ACTION_MOVE; // Filter the action based on the effectAllowed. If the effectAllowed // doesn't include the action, then that action cannot be done, so adjust // the action to something that is allowed. For a copy, adjust to move or // link. For a move, adjust to copy or link. For a link, adjust to move or // link. Otherwise, use none. if (aAction & aEffectAllowed || aEffectAllowed == nsIDragService::DRAGDROP_ACTION_UNINITIALIZED) return aAction; if (aEffectAllowed & nsIDragService::DRAGDROP_ACTION_MOVE) return nsIDragService::DRAGDROP_ACTION_MOVE; if (aEffectAllowed & nsIDragService::DRAGDROP_ACTION_COPY) return nsIDragService::DRAGDROP_ACTION_COPY; if (aEffectAllowed & nsIDragService::DRAGDROP_ACTION_LINK) return nsIDragService::DRAGDROP_ACTION_LINK; return nsIDragService::DRAGDROP_ACTION_NONE; } /* static */ bool nsContentUtils::CheckForSubFrameDrop(nsIDragSession* aDragSession, nsDragEvent* aDropEvent) { nsCOMPtr<nsIContent> target = do_QueryInterface(aDropEvent->originalTarget); if (!target && !target->OwnerDoc()) { return true; } nsIDocument* targetDoc = target->OwnerDoc(); nsCOMPtr<nsIWebNavigation> twebnav = do_GetInterface(targetDoc->GetWindow()); nsCOMPtr<nsIDocShellTreeItem> tdsti = do_QueryInterface(twebnav); if (!tdsti) { return true; } int32_t type = -1; if (NS_FAILED(tdsti->GetItemType(&type))) { return true; } // Always allow dropping onto chrome shells. if (type == nsIDocShellTreeItem::typeChrome) { return false; } // If there is no source node, then this is a drag from another // application, which should be allowed. nsCOMPtr<nsIDOMDocument> sourceDocument; aDragSession->GetSourceDocument(getter_AddRefs(sourceDocument)); nsCOMPtr<nsIDocument> doc = do_QueryInterface(sourceDocument); if (doc) { // Get each successive parent of the source document and compare it to // the drop document. If they match, then this is a drag from a child frame. do { doc = doc->GetParentDocument(); if (doc == targetDoc) { // The drag is from a child frame. return true; } } while (doc); } return false; } /* static */ bool nsContentUtils::URIIsLocalFile(nsIURI *aURI) { bool isFile; nsCOMPtr<nsINetUtil> util = do_QueryInterface(sIOService); // Important: we do NOT test the entire URI chain here! return util && NS_SUCCEEDED(util->ProtocolHasFlags(aURI, nsIProtocolHandler::URI_IS_LOCAL_FILE, &isFile)) && isFile; } nsresult nsContentUtils::SplitURIAtHash(nsIURI *aURI, nsACString &aBeforeHash, nsACString &aAfterHash) { // See bug 225910 for why we can't do this using nsIURL. aBeforeHash.Truncate(); aAfterHash.Truncate(); NS_ENSURE_ARG_POINTER(aURI); nsAutoCString spec; nsresult rv = aURI->GetSpec(spec); NS_ENSURE_SUCCESS(rv, rv); int32_t index = spec.FindChar('#'); if (index == -1) { index = spec.Length(); } aBeforeHash.Assign(Substring(spec, 0, index)); aAfterHash.Assign(Substring(spec, index)); return NS_OK; } /* static */ nsIScriptContext* nsContentUtils::GetContextForEventHandlers(nsINode* aNode, nsresult* aRv) { *aRv = NS_OK; bool hasHadScriptObject = true; nsIScriptGlobalObject* sgo = aNode->OwnerDoc()->GetScriptHandlingObject(hasHadScriptObject); // It is bad if the document doesn't have event handling context, // but it used to have one. if (!sgo && hasHadScriptObject) { *aRv = NS_ERROR_UNEXPECTED; return nullptr; } if (sgo) { nsIScriptContext* scx = sgo->GetContext(); // Bad, no context from script global object! if (!scx) { *aRv = NS_ERROR_UNEXPECTED; return nullptr; } return scx; } return nullptr; } /* static */ JSContext * nsContentUtils::GetCurrentJSContext() { JSContext *cx = nullptr; sThreadJSContextStack->Peek(&cx); return cx; } /* static */ JSContext * nsContentUtils::GetSafeJSContext() { return sThreadJSContextStack->GetSafeJSContext(); } /* static */ nsresult nsContentUtils::ASCIIToLower(nsAString& aStr) { PRUnichar* iter = aStr.BeginWriting(); PRUnichar* end = aStr.EndWriting(); if (NS_UNLIKELY(!iter || !end)) { return NS_ERROR_OUT_OF_MEMORY; } while (iter != end) { PRUnichar c = *iter; if (c >= 'A' && c <= 'Z') { *iter = c + ('a' - 'A'); } ++iter; } return NS_OK; } /* static */ nsresult nsContentUtils::ASCIIToLower(const nsAString& aSource, nsAString& aDest) { uint32_t len = aSource.Length(); aDest.SetLength(len); if (aDest.Length() == len) { PRUnichar* dest = aDest.BeginWriting(); if (NS_UNLIKELY(!dest)) { return NS_ERROR_OUT_OF_MEMORY; } const PRUnichar* iter = aSource.BeginReading(); const PRUnichar* end = aSource.EndReading(); while (iter != end) { PRUnichar c = *iter; *dest = (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; ++iter; ++dest; } return NS_OK; } return NS_ERROR_OUT_OF_MEMORY; } /* static */ nsresult nsContentUtils::ASCIIToUpper(nsAString& aStr) { PRUnichar* iter = aStr.BeginWriting(); PRUnichar* end = aStr.EndWriting(); if (NS_UNLIKELY(!iter || !end)) { return NS_ERROR_OUT_OF_MEMORY; } while (iter != end) { PRUnichar c = *iter; if (c >= 'a' && c <= 'z') { *iter = c + ('A' - 'a'); } ++iter; } return NS_OK; } /* static */ nsresult nsContentUtils::ASCIIToUpper(const nsAString& aSource, nsAString& aDest) { uint32_t len = aSource.Length(); aDest.SetLength(len); if (aDest.Length() == len) { PRUnichar* dest = aDest.BeginWriting(); if (NS_UNLIKELY(!dest)) { return NS_ERROR_OUT_OF_MEMORY; } const PRUnichar* iter = aSource.BeginReading(); const PRUnichar* end = aSource.EndReading(); while (iter != end) { PRUnichar c = *iter; *dest = (c >= 'a' && c <= 'z') ? c + ('A' - 'a') : c; ++iter; ++dest; } return NS_OK; } return NS_ERROR_OUT_OF_MEMORY; } /* static */ bool nsContentUtils::EqualsIgnoreASCIICase(const nsAString& aStr1, const nsAString& aStr2) { uint32_t len = aStr1.Length(); if (len != aStr2.Length()) { return false; } const PRUnichar* str1 = aStr1.BeginReading(); const PRUnichar* str2 = aStr2.BeginReading(); const PRUnichar* end = str1 + len; while (str1 < end) { PRUnichar c1 = *str1++; PRUnichar c2 = *str2++; // First check if any bits other than the 0x0020 differs if ((c1 ^ c2) & 0xffdf) { return false; } // We know they can only differ in the 0x0020 bit. // Likely the two chars are the same, so check that first if (c1 != c2) { // They do differ, but since it's only in the 0x0020 bit, check if it's // the same ascii char, but just differing in case PRUnichar c1Upper = c1 & 0xffdf; if (!('A' <= c1Upper && c1Upper <= 'Z')) { return false; } } } return true; } /* static */ bool nsContentUtils::EqualsLiteralIgnoreASCIICase(const nsAString& aStr1, const char* aStr2, const uint32_t len) { if (aStr1.Length() != len) { return false; } const PRUnichar* str1 = aStr1.BeginReading(); const char* str2 = aStr2; const PRUnichar* end = str1 + len; while (str1 < end) { PRUnichar c1 = *str1++; PRUnichar c2 = *str2++; // First check if any bits other than the 0x0020 differs if ((c1 ^ c2) & 0xffdf) { return false; } // We know they can only differ in the 0x0020 bit. // Likely the two chars are the same, so check that first if (c1 != c2) { // They do differ, but since it's only in the 0x0020 bit, check if it's // the same ascii char, but just differing in case PRUnichar c1Upper = c1 & 0xffdf; if (!('A' <= c1Upper && c1Upper <= 'Z')) { return false; } } } return true; } /* static */ bool nsContentUtils::StringContainsASCIIUpper(const nsAString& aStr) { const PRUnichar* iter = aStr.BeginReading(); const PRUnichar* end = aStr.EndReading(); while (iter != end) { PRUnichar c = *iter; if (c >= 'A' && c <= 'Z') { return true; } ++iter; } return false; } /* static */ nsIInterfaceRequestor* nsContentUtils::GetSameOriginChecker() { if (!sSameOriginChecker) { sSameOriginChecker = new SameOriginChecker(); NS_IF_ADDREF(sSameOriginChecker); } return sSameOriginChecker; } /* static */ nsresult nsContentUtils::CheckSameOrigin(nsIChannel *aOldChannel, nsIChannel *aNewChannel) { if (!nsContentUtils::GetSecurityManager()) return NS_ERROR_NOT_AVAILABLE; nsCOMPtr<nsIPrincipal> oldPrincipal; nsContentUtils::GetSecurityManager()-> GetChannelPrincipal(aOldChannel, getter_AddRefs(oldPrincipal)); nsCOMPtr<nsIURI> newURI; aNewChannel->GetURI(getter_AddRefs(newURI)); nsCOMPtr<nsIURI> newOriginalURI; aNewChannel->GetOriginalURI(getter_AddRefs(newOriginalURI)); NS_ENSURE_STATE(oldPrincipal && newURI && newOriginalURI); nsresult rv = oldPrincipal->CheckMayLoad(newURI, false, false); if (NS_SUCCEEDED(rv) && newOriginalURI != newURI) { rv = oldPrincipal->CheckMayLoad(newOriginalURI, false, false); } return rv; } NS_IMPL_ISUPPORTS2(SameOriginChecker, nsIChannelEventSink, nsIInterfaceRequestor) NS_IMETHODIMP SameOriginChecker::AsyncOnChannelRedirect(nsIChannel *aOldChannel, nsIChannel *aNewChannel, uint32_t aFlags, nsIAsyncVerifyRedirectCallback *cb) { NS_PRECONDITION(aNewChannel, "Redirecting to null channel?"); nsresult rv = nsContentUtils::CheckSameOrigin(aOldChannel, aNewChannel); if (NS_SUCCEEDED(rv)) { cb->OnRedirectVerifyCallback(NS_OK); } return rv; } NS_IMETHODIMP SameOriginChecker::GetInterface(const nsIID & aIID, void **aResult) { return QueryInterface(aIID, aResult); } /* static */ nsresult nsContentUtils::GetASCIIOrigin(nsIPrincipal* aPrincipal, nsCString& aOrigin) { NS_PRECONDITION(aPrincipal, "missing principal"); aOrigin.Truncate(); nsCOMPtr<nsIURI> uri; nsresult rv = aPrincipal->GetURI(getter_AddRefs(uri)); NS_ENSURE_SUCCESS(rv, rv); if (uri) { return GetASCIIOrigin(uri, aOrigin); } aOrigin.AssignLiteral("null"); return NS_OK; } /* static */ nsresult nsContentUtils::GetASCIIOrigin(nsIURI* aURI, nsCString& aOrigin) { NS_PRECONDITION(aURI, "missing uri"); aOrigin.Truncate(); nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI); NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED); nsCString host; nsresult rv = uri->GetAsciiHost(host); if (NS_SUCCEEDED(rv) && !host.IsEmpty()) { nsCString scheme; rv = uri->GetScheme(scheme); NS_ENSURE_SUCCESS(rv, rv); int32_t port = -1; uri->GetPort(&port); if (port != -1 && port == NS_GetDefaultPort(scheme.get())) port = -1; nsCString hostPort; rv = NS_GenerateHostPort(host, port, hostPort); NS_ENSURE_SUCCESS(rv, rv); aOrigin = scheme + NS_LITERAL_CSTRING("://") + hostPort; } else { aOrigin.AssignLiteral("null"); } return NS_OK; } /* static */ nsresult nsContentUtils::GetUTFOrigin(nsIPrincipal* aPrincipal, nsString& aOrigin) { NS_PRECONDITION(aPrincipal, "missing principal"); aOrigin.Truncate(); nsCOMPtr<nsIURI> uri; nsresult rv = aPrincipal->GetURI(getter_AddRefs(uri)); NS_ENSURE_SUCCESS(rv, rv); if (uri) { return GetUTFOrigin(uri, aOrigin); } aOrigin.AssignLiteral("null"); return NS_OK; } /* static */ nsresult nsContentUtils::GetUTFOrigin(nsIURI* aURI, nsString& aOrigin) { NS_PRECONDITION(aURI, "missing uri"); aOrigin.Truncate(); nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI); NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED); nsCString host; nsresult rv = uri->GetHost(host); if (NS_SUCCEEDED(rv) && !host.IsEmpty()) { nsCString scheme; rv = uri->GetScheme(scheme); NS_ENSURE_SUCCESS(rv, rv); int32_t port = -1; uri->GetPort(&port); if (port != -1 && port == NS_GetDefaultPort(scheme.get())) port = -1; nsCString hostPort; rv = NS_GenerateHostPort(host, port, hostPort); NS_ENSURE_SUCCESS(rv, rv); aOrigin = NS_ConvertUTF8toUTF16( scheme + NS_LITERAL_CSTRING("://") + hostPort); } else { aOrigin.AssignLiteral("null"); } return NS_OK; } /* static */ already_AddRefed<nsIDocument> nsContentUtils::GetDocumentFromScriptContext(nsIScriptContext *aScriptContext) { if (!aScriptContext) return nullptr; nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(aScriptContext->GetGlobalObject()); nsIDocument *doc = nullptr; if (window) { nsCOMPtr<nsIDOMDocument> domdoc; window->GetDocument(getter_AddRefs(domdoc)); if (domdoc) { CallQueryInterface(domdoc, &doc); } } return doc; } /* static */ bool nsContentUtils::CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel, bool aAllowIfInheritsPrincipal) { nsCOMPtr<nsIURI> channelURI; nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI)); NS_ENSURE_SUCCESS(rv, false); return NS_SUCCEEDED(aPrincipal->CheckMayLoad(channelURI, false, aAllowIfInheritsPrincipal)); } nsContentTypeParser::nsContentTypeParser(const nsAString& aString) : mString(aString), mService(nullptr) { CallGetService("@mozilla.org/network/mime-hdrparam;1", &mService); } nsContentTypeParser::~nsContentTypeParser() { NS_IF_RELEASE(mService); } nsresult nsContentTypeParser::GetParameter(const char* aParameterName, nsAString& aResult) { NS_ENSURE_TRUE(mService, NS_ERROR_FAILURE); return mService->GetParameter(mString, aParameterName, EmptyCString(), false, nullptr, aResult); } /* static */ // If you change this code, change also AllowedToAct() in // XPCSystemOnlyWrapper.cpp! bool nsContentUtils::CanAccessNativeAnon() { JSContext* cx = nullptr; sThreadJSContextStack->Peek(&cx); if (!cx) { return true; } JSStackFrame* fp; nsIPrincipal* principal = sSecurityManager->GetCxSubjectPrincipalAndFrame(cx, &fp); NS_ENSURE_TRUE(principal, false); JSScript *script = nullptr; if (fp) { script = JS_GetFrameScript(cx, fp); } else { if (!JS_DescribeScriptedCaller(cx, &script, nullptr)) { // No code at all is running. So we must be arriving here as the result // of C++ code asking us to do something. Allow access. return true; } } if (IsCallerChrome()) { return true; } // XXX HACK EWW! Allow chrome://global/ access to these things, even // if they've been cloned into less privileged contexts. static const char prefix[] = "chrome://global/"; const char *filename; if (script && (filename = JS_GetScriptFilename(cx, script)) && !strncmp(filename, prefix, ArrayLength(prefix) - 1)) { return true; } return false; } /* static */ nsresult nsContentUtils::DispatchXULCommand(nsIContent* aTarget, bool aTrusted, nsIDOMEvent* aSourceEvent, nsIPresShell* aShell, bool aCtrl, bool aAlt, bool aShift, bool aMeta) { NS_ENSURE_STATE(aTarget); nsIDocument* doc = aTarget->OwnerDoc(); nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(doc); NS_ENSURE_STATE(domDoc); nsCOMPtr<nsIDOMEvent> event; domDoc->CreateEvent(NS_LITERAL_STRING("xulcommandevent"), getter_AddRefs(event)); nsCOMPtr<nsIDOMXULCommandEvent> xulCommand = do_QueryInterface(event); nsresult rv = xulCommand->InitCommandEvent(NS_LITERAL_STRING("command"), true, true, doc->GetWindow(), 0, aCtrl, aAlt, aShift, aMeta, aSourceEvent); NS_ENSURE_SUCCESS(rv, rv); if (aShell) { nsEventStatus status = nsEventStatus_eIgnore; nsCOMPtr<nsIPresShell> kungFuDeathGrip = aShell; return aShell->HandleDOMEventWithTarget(aTarget, event, &status); } nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(aTarget); NS_ENSURE_STATE(target); bool dummy; return target->DispatchEvent(event, &dummy); } // static nsresult nsContentUtils::WrapNative(JSContext *cx, JSObject *scope, nsISupports *native, nsWrapperCache *cache, const nsIID* aIID, jsval *vp, nsIXPConnectJSObjectHolder **aHolder, bool aAllowWrapping) { if (!native) { NS_ASSERTION(!aHolder || !*aHolder, "*aHolder should be null!"); *vp = JSVAL_NULL; return NS_OK; } JSObject *wrapper = xpc_FastGetCachedWrapper(cache, scope, vp); if (wrapper) { return NS_OK; } NS_ENSURE_TRUE(sXPConnect && sThreadJSContextStack, NS_ERROR_UNEXPECTED); // Keep sXPConnect and sThreadJSContextStack alive. If we're on the main // thread then this can be done simply and cheaply by adding a reference to // nsLayoutStatics. If we're not on the main thread then we need to add a // more expensive reference sXPConnect directly. We have to use manual // AddRef and Release calls so don't early-exit from this function after we've // added the reference! bool isMainThread = NS_IsMainThread(); if (isMainThread) { nsLayoutStatics::AddRef(); } else { sXPConnect->AddRef(); } JSContext *topJSContext; nsresult rv = sThreadJSContextStack->Peek(&topJSContext); if (NS_SUCCEEDED(rv)) { bool push = topJSContext != cx; if (push) { rv = sThreadJSContextStack->Push(cx); } if (NS_SUCCEEDED(rv)) { rv = sXPConnect->WrapNativeToJSVal(cx, scope, native, cache, aIID, aAllowWrapping, vp, aHolder); if (push) { sThreadJSContextStack->Pop(nullptr); } } } if (isMainThread) { nsLayoutStatics::Release(); } else { sXPConnect->Release(); } return rv; } nsresult nsContentUtils::CreateArrayBuffer(JSContext *aCx, const nsACString& aData, JSObject** aResult) { if (!aCx) { return NS_ERROR_FAILURE; } int32_t dataLen = aData.Length(); *aResult = JS_NewArrayBuffer(aCx, dataLen); if (!*aResult) { return NS_ERROR_FAILURE; } if (dataLen > 0) { NS_ASSERTION(JS_IsArrayBufferObject(*aResult, aCx), "What happened?"); memcpy(JS_GetArrayBufferData(*aResult, aCx), aData.BeginReading(), dataLen); } return NS_OK; } // Initial implementation: only stores to RAM, not file // TODO: bug 704447: large file support nsresult nsContentUtils::CreateBlobBuffer(JSContext* aCx, const nsACString& aData, jsval& aBlob) { uint32_t blobLen = aData.Length(); void* blobData = PR_Malloc(blobLen); nsCOMPtr<nsIDOMBlob> blob; if (blobData) { memcpy(blobData, aData.BeginReading(), blobLen); blob = new nsDOMMemoryFile(blobData, blobLen, EmptyString()); } else { return NS_ERROR_OUT_OF_MEMORY; } JSObject* scope = JS_GetGlobalForScopeChain(aCx); return nsContentUtils::WrapNative(aCx, scope, blob, &aBlob, nullptr, true); } void nsContentUtils::StripNullChars(const nsAString& aInStr, nsAString& aOutStr) { // In common cases where we don't have nulls in the // string we can simple simply bypass the checking code. int32_t firstNullPos = aInStr.FindChar('\0'); if (firstNullPos == kNotFound) { aOutStr.Assign(aInStr); return; } aOutStr.SetCapacity(aInStr.Length() - 1); nsAString::const_iterator start, end; aInStr.BeginReading(start); aInStr.EndReading(end); while (start != end) { if (*start != '\0') aOutStr.Append(*start); ++start; } } struct ClassMatchingInfo { nsAttrValue::AtomArray mClasses; nsCaseTreatment mCaseTreatment; }; static bool MatchClassNames(nsIContent* aContent, int32_t aNamespaceID, nsIAtom* aAtom, void* aData) { // We can't match if there are no class names const nsAttrValue* classAttr = aContent->GetClasses(); if (!classAttr) { return false; } // need to match *all* of the classes ClassMatchingInfo* info = static_cast<ClassMatchingInfo*>(aData); uint32_t length = info->mClasses.Length(); if (!length) { // If we actually had no classes, don't match. return false; } uint32_t i; for (i = 0; i < length; ++i) { if (!classAttr->Contains(info->mClasses[i], info->mCaseTreatment)) { return false; } } return true; } static void DestroyClassNameArray(void* aData) { ClassMatchingInfo* info = static_cast<ClassMatchingInfo*>(aData); delete info; } static void* AllocClassMatchingInfo(nsINode* aRootNode, const nsString* aClasses) { nsAttrValue attrValue; attrValue.ParseAtomArray(*aClasses); // nsAttrValue::Equals is sensitive to order, so we'll send an array ClassMatchingInfo* info = new ClassMatchingInfo; NS_ENSURE_TRUE(info, nullptr); if (attrValue.Type() == nsAttrValue::eAtomArray) { info->mClasses.SwapElements(*(attrValue.GetAtomArrayValue())); } else if (attrValue.Type() == nsAttrValue::eAtom) { info->mClasses.AppendElement(attrValue.GetAtomValue()); } info->mCaseTreatment = aRootNode->OwnerDoc()->GetCompatibilityMode() == eCompatibility_NavQuirks ? eIgnoreCase : eCaseMatters; return info; } // static nsresult nsContentUtils::GetElementsByClassName(nsINode* aRootNode, const nsAString& aClasses, nsIDOMNodeList** aReturn) { NS_PRECONDITION(aRootNode, "Must have root node"); nsContentList* elements = NS_GetFuncStringHTMLCollection(aRootNode, MatchClassNames, DestroyClassNameArray, AllocClassMatchingInfo, aClasses).get(); NS_ENSURE_TRUE(elements, NS_ERROR_OUT_OF_MEMORY); // Transfer ownership *aReturn = elements; return NS_OK; } #ifdef DEBUG class DebugWrapperTraversalCallback : public nsCycleCollectionTraversalCallback { public: DebugWrapperTraversalCallback(void* aWrapper) : mFound(false), mWrapper(aWrapper) { mFlags = WANT_ALL_TRACES; } NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt refCount, const char *objName) { } NS_IMETHOD_(void) DescribeGCedNode(bool isMarked, const char *objName) { } NS_IMETHOD_(void) NoteXPCOMRoot(nsISupports *root) { } NS_IMETHOD_(void) NoteJSRoot(void* root) { } NS_IMETHOD_(void) NoteNativeRoot(void* root, nsCycleCollectionParticipant* helper) { } NS_IMETHOD_(void) NoteJSChild(void* child) { if (child == mWrapper) { mFound = true; } } NS_IMETHOD_(void) NoteXPCOMChild(nsISupports *child) { } NS_IMETHOD_(void) NoteNativeChild(void* child, nsCycleCollectionParticipant* helper) { } NS_IMETHOD_(void) NoteNextEdgeName(const char* name) { } NS_IMETHOD_(void) NoteWeakMapping(void* map, void* key, void* kdelegate, void* val) { } bool mFound; private: void* mWrapper; }; static void DebugWrapperTraceCallback(void *p, const char *name, void *closure) { DebugWrapperTraversalCallback* callback = static_cast<DebugWrapperTraversalCallback*>(closure); callback->NoteJSChild(p); } // static void nsContentUtils::CheckCCWrapperTraversal(nsISupports* aScriptObjectHolder, nsWrapperCache* aCache) { JSObject* wrapper = aCache->GetWrapper(); if (!wrapper) { return; } nsXPCOMCycleCollectionParticipant* participant; CallQueryInterface(aScriptObjectHolder, &participant); DebugWrapperTraversalCallback callback(wrapper); participant->Traverse(aScriptObjectHolder, callback); NS_ASSERTION(callback.mFound, "Cycle collection participant didn't traverse to preserved " "wrapper! This will probably crash."); callback.mFound = false; participant->Trace(aScriptObjectHolder, DebugWrapperTraceCallback, &callback); NS_ASSERTION(callback.mFound, "Cycle collection participant didn't trace preserved wrapper! " "This will probably crash."); } #endif // static bool nsContentUtils::IsFocusedContent(const nsIContent* aContent) { nsFocusManager* fm = nsFocusManager::GetFocusManager(); return fm && fm->GetFocusedContent() == aContent; } bool nsContentUtils::IsSubDocumentTabbable(nsIContent* aContent) { nsIDocument* doc = aContent->GetCurrentDoc(); if (!doc) { return false; } // If the subdocument lives in another process, the frame is // tabbable. if (nsEventStateManager::IsRemoteTarget(aContent)) { return true; } // XXXbz should this use OwnerDoc() for GetSubDocumentFor? // sXBL/XBL2 issue! nsIDocument* subDoc = doc->GetSubDocumentFor(aContent); if (!subDoc) { return false; } nsCOMPtr<nsISupports> container = subDoc->GetContainer(); nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(container); if (!docShell) { return false; } nsCOMPtr<nsIContentViewer> contentViewer; docShell->GetContentViewer(getter_AddRefs(contentViewer)); if (!contentViewer) { return false; } nsCOMPtr<nsIContentViewer> zombieViewer; contentViewer->GetPreviousViewer(getter_AddRefs(zombieViewer)); // If there are 2 viewers for the current docshell, that // means the current document is a zombie document. // Only navigate into the subdocument if it's not a zombie. return !zombieViewer; } void nsContentUtils::FlushLayoutForTree(nsIDOMWindow* aWindow) { nsCOMPtr<nsPIDOMWindow> piWin = do_QueryInterface(aWindow); if (!piWin) return; // Note that because FlushPendingNotifications flushes parents, this // is O(N^2) in docshell tree depth. However, the docshell tree is // usually pretty shallow. nsCOMPtr<nsIDOMDocument> domDoc; aWindow->GetDocument(getter_AddRefs(domDoc)); nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc); if (doc) { doc->FlushPendingNotifications(Flush_Layout); } nsCOMPtr<nsIDocShellTreeNode> node = do_QueryInterface(piWin->GetDocShell()); if (node) { int32_t i = 0, i_end; node->GetChildCount(&i_end); for (; i < i_end; ++i) { nsCOMPtr<nsIDocShellTreeItem> item; node->GetChildAt(i, getter_AddRefs(item)); nsCOMPtr<nsIDOMWindow> win = do_GetInterface(item); if (win) { FlushLayoutForTree(win); } } } } void nsContentUtils::RemoveNewlines(nsString &aString) { // strip CR/LF and null static const char badChars[] = {'\r', '\n', 0}; aString.StripChars(badChars); } void nsContentUtils::PlatformToDOMLineBreaks(nsString &aString) { if (aString.FindChar(PRUnichar('\r')) != -1) { // Windows linebreaks: Map CRLF to LF: aString.ReplaceSubstring(NS_LITERAL_STRING("\r\n").get(), NS_LITERAL_STRING("\n").get()); // Mac linebreaks: Map any remaining CR to LF: aString.ReplaceSubstring(NS_LITERAL_STRING("\r").get(), NS_LITERAL_STRING("\n").get()); } } nsIWidget * nsContentUtils::WidgetForDocument(nsIDocument *aDoc) { nsIDocument* doc = aDoc; nsIDocument* displayDoc = doc->GetDisplayDocument(); if (displayDoc) { doc = displayDoc; } nsIPresShell* shell = doc->GetShell(); nsCOMPtr<nsISupports> container = doc->GetContainer(); nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem = do_QueryInterface(container); while (!shell && docShellTreeItem) { // We may be in a display:none subdocument, or we may not have a presshell // created yet. // Walk the docshell tree to find the nearest container that has a presshell, // and find the root widget from that. nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(docShellTreeItem); nsCOMPtr<nsIPresShell> presShell; docShell->GetPresShell(getter_AddRefs(presShell)); if (presShell) { shell = presShell; } else { nsCOMPtr<nsIDocShellTreeItem> parent; docShellTreeItem->GetParent(getter_AddRefs(parent)); docShellTreeItem = parent; } } if (shell) { nsIViewManager* VM = shell->GetViewManager(); if (VM) { nsIView* rootView = VM->GetRootView(); if (rootView) { nsIView* displayRoot = nsIViewManager::GetDisplayRootFor(rootView); if (displayRoot) { return displayRoot->GetNearestWidget(nullptr); } } } } return nullptr; } static already_AddRefed<LayerManager> LayerManagerForDocumentInternal(nsIDocument *aDoc, bool aRequirePersistent, bool* aAllowRetaining) { nsIWidget *widget = nsContentUtils::WidgetForDocument(aDoc); if (widget) { nsRefPtr<LayerManager> manager = widget->GetLayerManager(aRequirePersistent ? nsIWidget::LAYER_MANAGER_PERSISTENT : nsIWidget::LAYER_MANAGER_CURRENT, aAllowRetaining); return manager.forget(); } return nullptr; } already_AddRefed<LayerManager> nsContentUtils::LayerManagerForDocument(nsIDocument *aDoc, bool *aAllowRetaining) { return LayerManagerForDocumentInternal(aDoc, false, aAllowRetaining); } already_AddRefed<LayerManager> nsContentUtils::PersistentLayerManagerForDocument(nsIDocument *aDoc, bool *aAllowRetaining) { return LayerManagerForDocumentInternal(aDoc, true, aAllowRetaining); } bool nsContentUtils::AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal) { if (IsSystemPrincipal(aPrincipal)) { return true; } nsCOMPtr<nsIURI> princURI; aPrincipal->GetURI(getter_AddRefs(princURI)); return princURI && ((sAllowXULXBL_for_file && SchemeIs(princURI, "file")) || IsSitePermAllow(aPrincipal, "allowXULXBL")); } already_AddRefed<nsIDocumentLoaderFactory> nsContentUtils::FindInternalContentViewer(const char* aType, ContentViewerType* aLoaderType) { if (aLoaderType) { *aLoaderType = TYPE_UNSUPPORTED; } // one helper factory, please nsCOMPtr<nsICategoryManager> catMan(do_GetService(NS_CATEGORYMANAGER_CONTRACTID)); if (!catMan) return NULL; nsCOMPtr<nsIDocumentLoaderFactory> docFactory; nsXPIDLCString contractID; nsresult rv = catMan->GetCategoryEntry("Gecko-Content-Viewers", aType, getter_Copies(contractID)); if (NS_SUCCEEDED(rv)) { docFactory = do_GetService(contractID); if (docFactory && aLoaderType) { if (contractID.EqualsLiteral(CONTENT_DLF_CONTRACTID)) *aLoaderType = TYPE_CONTENT; else if (contractID.EqualsLiteral(PLUGIN_DLF_CONTRACTID)) *aLoaderType = TYPE_PLUGIN; else *aLoaderType = TYPE_UNKNOWN; } return docFactory.forget(); } #ifdef MOZ_MEDIA #ifdef MOZ_OGG if (nsHTMLMediaElement::IsOggEnabled()) { for (unsigned int i = 0; i < ArrayLength(nsHTMLMediaElement::gOggTypes); ++i) { const char* type = nsHTMLMediaElement::gOggTypes[i]; if (!strcmp(aType, type)) { docFactory = do_GetService("@mozilla.org/content/document-loader-factory;1"); if (docFactory && aLoaderType) { *aLoaderType = TYPE_CONTENT; } return docFactory.forget(); } } } #endif #ifdef MOZ_WIDGET_GONK if (nsHTMLMediaElement::IsOmxSupportedType(nsDependentCString(aType)) && !nsDependentCString(aType).EqualsASCII("audio/amr")) { docFactory = do_GetService("@mozilla.org/content/document-loader-factory;1"); if (docFactory && aLoaderType) { *aLoaderType = TYPE_CONTENT; } return docFactory.forget(); } #endif #ifdef MOZ_WEBM if (nsHTMLMediaElement::IsWebMEnabled()) { for (unsigned int i = 0; i < ArrayLength(nsHTMLMediaElement::gWebMTypes); ++i) { const char* type = nsHTMLMediaElement::gWebMTypes[i]; if (!strcmp(aType, type)) { docFactory = do_GetService("@mozilla.org/content/document-loader-factory;1"); if (docFactory && aLoaderType) { *aLoaderType = TYPE_CONTENT; } return docFactory.forget(); } } } #endif #ifdef MOZ_GSTREAMER if (nsHTMLMediaElement::IsH264Enabled()) { for (unsigned int i = 0; i < ArrayLength(nsHTMLMediaElement::gH264Types); ++i) { const char* type = nsHTMLMediaElement::gH264Types[i]; if (!strcmp(aType, type)) { docFactory = do_GetService("@mozilla.org/content/document-loader-factory;1"); if (docFactory && aLoaderType) { *aLoaderType = TYPE_CONTENT; } return docFactory.forget(); } } } #endif #ifdef MOZ_MEDIA_PLUGINS if (nsHTMLMediaElement::IsMediaPluginsEnabled() && nsHTMLMediaElement::IsMediaPluginsType(nsDependentCString(aType))) { docFactory = do_GetService("@mozilla.org/content/document-loader-factory;1"); if (docFactory && aLoaderType) { *aLoaderType = TYPE_CONTENT; } return docFactory.forget(); } #endif // MOZ_MEDIA_PLUGINS #endif // MOZ_MEDIA return NULL; } // static bool nsContentUtils::IsPatternMatching(nsAString& aValue, nsAString& aPattern, nsIDocument* aDocument) { NS_ASSERTION(aDocument, "aDocument should be a valid pointer (not null)"); NS_ENSURE_TRUE(aDocument->GetScriptGlobalObject(), true); JSContext* ctx = (JSContext*) aDocument->GetScriptGlobalObject()-> GetContext()->GetNativeContext(); NS_ENSURE_TRUE(ctx, true); JSAutoRequest ar(ctx); // The pattern has to match the entire value. aPattern.Insert(NS_LITERAL_STRING("^(?:"), 0); aPattern.Append(NS_LITERAL_STRING(")$")); JSObject* re = JS_NewUCRegExpObjectNoStatics(ctx, reinterpret_cast<jschar*> (aPattern.BeginWriting()), aPattern.Length(), 0); NS_ENSURE_TRUE(re, true); jsval rval = JSVAL_NULL; size_t idx = 0; JSBool res; res = JS_ExecuteRegExpNoStatics(ctx, re, reinterpret_cast<jschar*> (aValue.BeginWriting()), aValue.Length(), &idx, JS_TRUE, &rval); return res == JS_FALSE || rval != JSVAL_NULL; } // static nsresult nsContentUtils::URIInheritsSecurityContext(nsIURI *aURI, bool *aResult) { // Note: about:blank URIs do NOT inherit the security context from the // current document, which is what this function tests for... return NS_URIChainHasFlags(aURI, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT, aResult); } // static bool nsContentUtils::SetUpChannelOwner(nsIPrincipal* aLoadingPrincipal, nsIChannel* aChannel, nsIURI* aURI, bool aSetUpForAboutBlank, bool aForceOwner) { // // Set the owner of the channel, but only for channels that can't // provide their own security context. // // XXX: It seems wrong that the owner is ignored - even if one is // supplied) unless the URI is javascript or data or about:blank. // XXX: If this is ever changed, check all callers for what owners // they're passing in. In particular, see the code and // comments in nsDocShell::LoadURI where we fall back on // inheriting the owner if called from chrome. That would be // very wrong if this code changed anything but channels that // can't provide their own security context! // // (Currently chrome URIs set the owner when they are created! // So setting a NULL owner would be bad!) // // If aForceOwner is true, the owner will be set, even for a channel that // can provide its own security context. This is used for the HTML5 IFRAME // sandbox attribute, so we can force the channel (and its document) to // explicitly have a null principal. bool inherit; // We expect URIInheritsSecurityContext to return success for an // about:blank URI, so don't call NS_IsAboutBlank() if this call fails. // This condition needs to match the one in nsDocShell::InternalLoad where // we're checking for things that will use the owner. if (aForceOwner || ((NS_SUCCEEDED(URIInheritsSecurityContext(aURI, &inherit)) && (inherit || (aSetUpForAboutBlank && NS_IsAboutBlank(aURI)))))) { #ifdef DEBUG // Assert that aForceOwner is only set for null principals if (aForceOwner) { nsCOMPtr<nsIURI> ownerURI; nsresult rv = aLoadingPrincipal->GetURI(getter_AddRefs(ownerURI)); MOZ_ASSERT(NS_SUCCEEDED(rv) && SchemeIs(ownerURI, NS_NULLPRINCIPAL_SCHEME)); } #endif aChannel->SetOwner(aLoadingPrincipal); return true; } // // file: uri special-casing // // If this is a file: load opened from another file: then it may need // to inherit the owner from the referrer so they can script each other. // If we don't set the owner explicitly then each file: gets an owner // based on its own codebase later. // if (URIIsLocalFile(aURI) && aLoadingPrincipal && NS_SUCCEEDED(aLoadingPrincipal->CheckMayLoad(aURI, false, false)) && // One more check here. CheckMayLoad will always return true for the // system principal, but we do NOT want to inherit in that case. !IsSystemPrincipal(aLoadingPrincipal)) { aChannel->SetOwner(aLoadingPrincipal); return true; } return false; } bool nsContentUtils::IsFullScreenApiEnabled() { return sIsFullScreenApiEnabled; } bool nsContentUtils::IsRequestFullScreenAllowed() { return !sTrustedFullScreenOnly || nsEventStateManager::IsHandlingUserInput() || IsCallerChrome(); } /* static */ bool nsContentUtils::HaveEqualPrincipals(nsIDocument* aDoc1, nsIDocument* aDoc2) { if (!aDoc1 || !aDoc2) { return false; } bool principalsEqual = false; aDoc1->NodePrincipal()->Equals(aDoc2->NodePrincipal(), &principalsEqual); return principalsEqual; } static void CheckForWindowedPlugins(nsIContent* aContent, void* aResult) { if (!aContent->IsInDoc()) { return; } nsCOMPtr<nsIObjectLoadingContent> olc(do_QueryInterface(aContent)); if (!olc) { return; } nsRefPtr<nsNPAPIPluginInstance> plugin; olc->GetPluginInstance(getter_AddRefs(plugin)); if (!plugin) { return; } bool isWindowless = false; nsresult res = plugin->IsWindowless(&isWindowless); if (NS_SUCCEEDED(res) && !isWindowless) { *static_cast<bool*>(aResult) = true; } } static bool DocTreeContainsWindowedPlugins(nsIDocument* aDoc, void* aResult) { if (!nsContentUtils::IsChromeDoc(aDoc)) { aDoc->EnumerateFreezableElements(CheckForWindowedPlugins, aResult); } if (*static_cast<bool*>(aResult)) { // Return false to stop iteration, we found a windowed plugin. return false; } aDoc->EnumerateSubDocuments(DocTreeContainsWindowedPlugins, aResult); // Return false to stop iteration if we found a windowed plugin in // the sub documents. return !*static_cast<bool*>(aResult); } /* static */ bool nsContentUtils::HasPluginWithUncontrolledEventDispatch(nsIDocument* aDoc) { #ifdef XP_MACOSX // We control dispatch to all mac plugins. return false; #endif bool result = false; // Find the top of the document's branch, the child of the chrome document. nsIDocument* doc = aDoc; nsIDocument* parent = nullptr; while (doc && (parent = doc->GetParentDocument()) && !IsChromeDoc(parent)) { doc = parent; } DocTreeContainsWindowedPlugins(doc, &result); return result; } /* static */ bool nsContentUtils::HasPluginWithUncontrolledEventDispatch(nsIContent* aContent) { #ifdef XP_MACOSX // We control dispatch to all mac plugins. return false; #endif bool result = false; CheckForWindowedPlugins(aContent, &result); return result; } /* static */ nsIDocument* nsContentUtils::GetRootDocument(nsIDocument* aDoc) { if (!aDoc) { return nullptr; } nsIDocument* doc = aDoc; while (doc->GetParentDocument()) { doc = doc->GetParentDocument(); } return doc; } // static void nsContentUtils::ReleaseWrapper(nsISupports* aScriptObjectHolder, nsWrapperCache* aCache) { if (aCache->PreservingWrapper()) { // PreserveWrapper puts new DOM bindings in the JS holders hash, but they // can also be in the DOM expando hash, so we need to try to remove them // from both here. JSObject* obj = aCache->GetWrapperPreserveColor(); if (aCache->IsDOMBinding() && obj) { xpc::CompartmentPrivate *priv = xpc::GetCompartmentPrivate(obj); priv->RemoveDOMExpandoObject(obj); } aCache->SetPreservingWrapper(false); DropJSObjects(aScriptObjectHolder); } } // static void nsContentUtils::TraceWrapper(nsWrapperCache* aCache, TraceCallback aCallback, void *aClosure) { if (aCache->PreservingWrapper()) { JSObject *wrapper = aCache->GetWrapperPreserveColor(); if (wrapper) { aCallback(wrapper, "Preserved wrapper", aClosure); } } } nsresult nsContentUtils::JSArrayToAtomArray(JSContext* aCx, const JS::Value& aJSArray, nsCOMArray<nsIAtom>& aRetVal) { JSAutoRequest ar(aCx); if (!aJSArray.isObject()) { return NS_ERROR_ILLEGAL_VALUE; } JSObject* obj = &aJSArray.toObject(); JSAutoCompartment ac(aCx, obj); uint32_t length; if (!JS_IsArrayObject(aCx, obj) || !JS_GetArrayLength(aCx, obj, &length)) { return NS_ERROR_ILLEGAL_VALUE; } JSString* str = nullptr; JS::Anchor<JSString *> deleteProtector(str); for (uint32_t i = 0; i < length; ++i) { jsval v; if (!JS_GetElement(aCx, obj, i, &v) || !(str = JS_ValueToString(aCx, v))) { return NS_ERROR_ILLEGAL_VALUE; } nsDependentJSString depStr; if (!depStr.init(aCx, str)) { return NS_ERROR_OUT_OF_MEMORY; } nsCOMPtr<nsIAtom> a = do_GetAtom(depStr); if (!a) { return NS_ERROR_OUT_OF_MEMORY; } aRetVal.AppendObject(a); } return NS_OK; } /* static */ bool nsContentUtils::PaintSVGGlyph(Element *aElement, gfxContext *aContext, gfxFont::DrawMode aDrawMode, gfxTextObjectPaint *aObjectPaint) { nsIFrame *frame = aElement->GetPrimaryFrame(); if (!frame) { NS_WARNING("No frame for SVG glyph"); return false; } nsISVGChildFrame *displayFrame = do_QueryFrame(frame); if (!displayFrame) { NS_WARNING("Non SVG frame for SVG glyph"); return false; } nsRenderingContext context; context.Init(frame->PresContext()->DeviceContext(), aContext); context.AddUserData(&gfxTextObjectPaint::sUserDataKey, aObjectPaint, nullptr); nsresult rv = displayFrame->PaintSVG(&context, nullptr); NS_ENSURE_SUCCESS(rv, false); return true; } /* static */ bool nsContentUtils::GetSVGGlyphExtents(Element *aElement, const gfxMatrix& aSVGToAppSpace, gfxRect *aResult) { nsIFrame *frame = aElement->GetPrimaryFrame(); if (!frame) { NS_WARNING("No frame for SVG glyph"); return false; } nsISVGChildFrame *displayFrame = do_QueryFrame(frame); if (!displayFrame) { NS_WARNING("Non SVG frame for SVG glyph"); return false; } *aResult = displayFrame->GetBBoxContribution(aSVGToAppSpace, nsSVGUtils::eBBoxIncludeFill | nsSVGUtils::eBBoxIncludeFillGeometry | nsSVGUtils::eBBoxIncludeStroke | nsSVGUtils::eBBoxIncludeStrokeGeometry | nsSVGUtils::eBBoxIncludeMarkers); return true; } // static void nsContentUtils::GetSelectionInTextControl(Selection* aSelection, Element* aRoot, int32_t& aOutStartOffset, int32_t& aOutEndOffset) { MOZ_ASSERT(aSelection && aRoot); if (!aSelection->GetRangeCount()) { // Nothing selected aOutStartOffset = aOutEndOffset = 0; return; } nsCOMPtr<nsINode> anchorNode = aSelection->GetAnchorNode(); int32_t anchorOffset = aSelection->GetAnchorOffset(); nsCOMPtr<nsINode> focusNode = aSelection->GetFocusNode(); int32_t focusOffset = aSelection->GetFocusOffset(); // We have at most two children, consisting of an optional text node followed // by an optional <br>. NS_ASSERTION(aRoot->GetChildCount() <= 2, "Unexpected children"); nsCOMPtr<nsIContent> firstChild = aRoot->GetFirstChild(); #ifdef DEBUG nsCOMPtr<nsIContent> lastChild = aRoot->GetLastChild(); NS_ASSERTION(anchorNode == aRoot || anchorNode == firstChild || anchorNode == lastChild, "Unexpected anchorNode"); NS_ASSERTION(focusNode == aRoot || focusNode == firstChild || focusNode == lastChild, "Unexpected focusNode"); #endif if (!firstChild || !firstChild->IsNodeOfType(nsINode::eTEXT)) { // No text node, so everything is 0 anchorOffset = focusOffset = 0; } else { // First child is text. If the anchor/focus is already in the text node, // or the start of the root node, no change needed. If it's in the root // node but not the start, or in the trailing <br>, we need to set the // offset to the end. if ((anchorNode == aRoot && anchorOffset != 0) || (anchorNode != aRoot && anchorNode != firstChild)) { anchorOffset = firstChild->Length(); } if ((focusNode == aRoot && focusOffset != 0) || (focusNode != aRoot && focusNode != firstChild)) { focusOffset = firstChild->Length(); } } // Make sure aOutStartOffset <= aOutEndOffset. aOutStartOffset = NS_MIN(anchorOffset, focusOffset); aOutEndOffset = NS_MAX(anchorOffset, focusOffset); } nsIEditor* nsContentUtils::GetHTMLEditor(nsPresContext* aPresContext) { nsCOMPtr<nsISupports> container = aPresContext->GetContainer(); nsCOMPtr<nsIEditorDocShell> editorDocShell(do_QueryInterface(container)); bool isEditable; if (!editorDocShell || NS_FAILED(editorDocShell->GetEditable(&isEditable)) || !isEditable) return nullptr; nsCOMPtr<nsIEditor> editor; editorDocShell->GetEditor(getter_AddRefs(editor)); return editor; }
29.607483
150
0.662953
[ "object", "model" ]
38c5eb9a5a5cd9975f411533449974998f8b6fa5
1,810
cpp
C++
src/ConvexHullGraphix.cpp
dub-basu/convex-hull
6e5ba71d540315c4aea4f419d058c6f9ca3a5987
[ "MIT" ]
null
null
null
src/ConvexHullGraphix.cpp
dub-basu/convex-hull
6e5ba71d540315c4aea4f419d058c6f9ca3a5987
[ "MIT" ]
null
null
null
src/ConvexHullGraphix.cpp
dub-basu/convex-hull
6e5ba71d540315c4aea4f419d058c6f9ca3a5987
[ "MIT" ]
null
null
null
#include<algorithm> #include "ConvexHullGraphix.h" ConvexHullGraphix::ConvexHullGraphix(std::mutex& mtx):Graphix(mtx){ Point start(-WIN_BREADTH / 2, WIN_HEIGHT); Point end(WIN_BREADTH / 2, WIN_HEIGHT); pivot_point = NAN_POINT; } void ConvexHullGraphix::init_points(std::vector<Point> points){ this -> input_points = points; draw_init_points(); } void ConvexHullGraphix::draw_init_points(){ for(auto i: input_points){ draw_point(i, POINT_COLOR); } } void ConvexHullGraphix::update_pivot_point(Point& pt){ this -> pivot_point = pt; update_scene(); } void ConvexHullGraphix::update_scene(){ clear(); draw_init_points(); if(!(this -> pivot_point).is_nan()){ draw_point(this -> pivot_point, PIVOT_COLOR); draw_spokes(); } draw_edges(); } void ConvexHullGraphix::add_edge(LineSegment ln){ edges.push_back(ln); update_scene(); } void ConvexHullGraphix::add_edge(Point pt1, Point pt2){ LineSegment ln(pt1, pt2); add_edge(ln); } void ConvexHullGraphix::remove_edge(LineSegment& ln){ edges.erase(std::remove(edges.begin(), edges.end(), ln), edges.end()); update_scene(); } void ConvexHullGraphix::remove_edge(Point pt1, Point pt2){ LineSegment ln(pt1, pt2); remove_edge(ln); } void ConvexHullGraphix::draw_edges(){ for(auto edge: this -> edges){ draw_line(edge, EDGE_COLOR); } } void ConvexHullGraphix::draw_spokes(){ for(auto pt: this -> input_points){ LineSegment ln(pivot_point, pt); draw_dashed_line(ln, SPOKE_COLOR); } } void ConvexHullGraphix::draw_point(Point pt, GLfloat red, GLfloat green, GLfloat blue){ glBegin(GL_POINTS); glColor3f(red, green, blue); glVertex2f(pt.x,pt.y); glColor3f(DEFAULT_COLOR); glEnd(); }
24.133333
87
0.674586
[ "vector" ]
38c9ee224f4c8c278aad23c062168085a59189cd
1,060
cpp
C++
leetcode/maximal-square/MaximalSquare.cpp
giwankim/algo
8dd1cf8aed6e89db54e753c7ce5821019628c47f
[ "MIT" ]
null
null
null
leetcode/maximal-square/MaximalSquare.cpp
giwankim/algo
8dd1cf8aed6e89db54e753c7ce5821019628c47f
[ "MIT" ]
null
null
null
leetcode/maximal-square/MaximalSquare.cpp
giwankim/algo
8dd1cf8aed6e89db54e753c7ce5821019628c47f
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" using namespace std; typedef vector<int> vi; typedef vector<vector<int>> vvi; int maximalSquare(vector<vector<char>>& matrix) { if (matrix.empty()) return 0; int n = (int)matrix.size(), m = (int)matrix[0].size(); vvi T(n, vi(m)); for (int i = 0; i < n; ++i) T[i][0] = matrix[i][0]-'0'; for (int j = 0; j < m; ++j) T[0][j] = matrix[0][j]-'0'; for (int i = 1; i < n; ++i) { for (int j = 1; j < m; ++j) { if (matrix[i][j] == '1'){ T[i][j] = min({T[i-1][j], T[i][j-1], T[i-1][j-1]}) + 1; } } } int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { ans = max(ans, T[i][j]); } } return ans * ans; } int main(int argc, char const *argv[]) { /* code */ vector<vector<char>> matrix = { {'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'}, }; cout << maximalSquare(matrix) << "\n"; return 0; }
25.853659
71
0.40566
[ "vector" ]
38dc35182be7f9651d6ecc0d46d5ab24fb430cad
737
hpp
C++
jni/Game.hpp
kaitokidi/androidSpaceTongue
0c839dd92fe6393fa095735b08cb8966c771c36a
[ "MIT" ]
null
null
null
jni/Game.hpp
kaitokidi/androidSpaceTongue
0c839dd92fe6393fa095735b08cb8966c771c36a
[ "MIT" ]
null
null
null
jni/Game.hpp
kaitokidi/androidSpaceTongue
0c839dd92fe6393fa095735b08cb8966c771c36a
[ "MIT" ]
null
null
null
#ifndef GAME_H #define GAME_H #include "utils.hpp" class Game { public: virtual bool update(float deltaTime) = 0; virtual void draw() = 0; virtual void processEvents() = 0; Game(sf::RenderWindow *w) { window = w; goToMenu = false; } virtual ~Game() {} bool run() { sf::Clock c; srand(time(0)); while(window->isOpen()) { float deltaTime = c.restart().asSeconds(); processEvents(); if (goToMenu) return false; if (update(deltaTime)) return true; render(); } return false; } protected: sf::RenderWindow *window; bool goToMenu; private: void render() { window->clear(); draw(); window->display(); } }; #endif // GAME_H
15.680851
50
0.576662
[ "render" ]
38dcc3b79836aa3f2f9b2517158f9f6eb75b8820
13,782
cpp
C++
src/sim/graphics/base/pipeline/descriptors.cpp
wumo/SimGraphicsNative
f46153b20b1131930b07c9ebb44640978481e319
[ "MIT" ]
null
null
null
src/sim/graphics/base/pipeline/descriptors.cpp
wumo/SimGraphicsNative
f46153b20b1131930b07c9ebb44640978481e319
[ "MIT" ]
null
null
null
src/sim/graphics/base/pipeline/descriptors.cpp
wumo/SimGraphicsNative
f46153b20b1131930b07c9ebb44640978481e319
[ "MIT" ]
null
null
null
#include "descriptors.h" #include "sim/util/syntactic_sugar.h" #include <algorithm> namespace sim::graphics { using descriptor = vk::DescriptorType; auto DescriptorSetLayoutMaker::vertexShader() -> DescriptorSetLayoutMaker & { currentStage = vk::ShaderStageFlagBits::eVertex; return *this; } auto DescriptorSetLayoutMaker::fragmentShader() -> DescriptorSetLayoutMaker & { currentStage = vk::ShaderStageFlagBits::eFragment; return *this; } auto DescriptorSetLayoutMaker::computeShader() -> DescriptorSetLayoutMaker & { currentStage = vk::ShaderStageFlagBits::eCompute; return *this; } auto DescriptorSetLayoutMaker::shaderStage(vk::ShaderStageFlags stage) -> DescriptorSetLayoutMaker & { currentStage = stage; return *this; } auto DescriptorSetLayoutMaker::descriptor( uint32_t binding, vk::DescriptorType descriptorType, vk::ShaderStageFlags stageFlags, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { _bindings.emplace_back(binding, descriptorType, descriptorCount, stageFlags, nullptr); flags.push_back(bindingFlags); useDescriptorIndexing = bool(bindingFlags); if(bindingFlags & vk::DescriptorBindingFlagBitsEXT::eUpdateAfterBind) updateAfterBindPool = true; if(bindingFlags & vk::DescriptorBindingFlagBitsEXT::eVariableDescriptorCount) variableDescriptorBinding = binding; return *this; } auto DescriptorSetLayoutMaker::uniform( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eUniformBuffer, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::uniformDynamic( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eUniformBufferDynamic, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::buffer( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eStorageBuffer, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::sampler2D( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eCombinedImageSampler, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::input( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eInputAttachment, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::storageImage( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eStorageImage, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::accelerationStructure( uint32_t binding, uint32_t descriptorCount, vk::DescriptorBindingFlagsEXT bindingFlags) -> DescriptorSetLayoutMaker & { return descriptor( binding, descriptor::eAccelerationStructureNV, currentStage, descriptorCount, bindingFlags); } auto DescriptorSetLayoutMaker::createUnique(const vk::Device &device) const -> vk::UniqueDescriptorSetLayout { vk::DescriptorSetLayoutCreateInfo layoutInfo; layoutInfo.bindingCount = uint32_t(_bindings.size()); layoutInfo.pBindings = _bindings.data(); vk::DescriptorSetLayoutBindingFlagsCreateInfoEXT bindingFlags; if(useDescriptorIndexing) { bindingFlags.bindingCount = uint32_t(flags.size()); bindingFlags.pBindingFlags = flags.data(); layoutInfo.pNext = &bindingFlags; if(updateAfterBindPool) layoutInfo.flags = vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPoolEXT; } errorIf( variableDescriptorBinding != -1 && variableDescriptorBinding != std::max_element( _bindings.begin(), _bindings.end(), [](const auto &a, const auto &b) { return a.binding < b.binding; }) ->binding, "varialbe descriptor should only be the last binding!"); return device.createDescriptorSetLayoutUnique(layoutInfo); } auto DescriptorSetLayoutMaker::getVariableDescriptorBinding() const -> int { return variableDescriptorBinding; } auto DescriptorSetLayoutMaker::getVariableDescriptorCount() const -> uint32_t { return variableDescriptorBinding == -1 ? 0 : _bindings[variableDescriptorBinding].descriptorCount; } auto DescriptorSetLayoutMaker::bindings() const -> const std::vector<vk::DescriptorSetLayoutBinding> & { return _bindings; } auto DescriptorSetMaker::layout(vk::DescriptorSetLayout layout) -> DescriptorSetMaker & { layouts.push_back(layout); variableDescriptorCounts.push_back(0); return *this; } auto DescriptorSetMaker::layout( vk::DescriptorSetLayout layout, uint32_t variableDescriptorCount) -> DescriptorSetMaker & { layouts.push_back(layout); variableDescriptorCounts.push_back(variableDescriptorCount); useVariableCounts = useVariableCounts || variableDescriptorCount > 0; return *this; } auto DescriptorSetMaker::create( const vk::Device &device, vk::DescriptorPool descriptorPool) const -> std::vector<vk::DescriptorSet> { vk::DescriptorSetAllocateInfo allocateInfo; allocateInfo.descriptorPool = descriptorPool; allocateInfo.descriptorSetCount = uint32_t(layouts.size()); allocateInfo.pSetLayouts = layouts.data(); vk::DescriptorSetVariableDescriptorCountAllocateInfoEXT info; if(useVariableCounts) { info.descriptorSetCount = uint32_t(variableDescriptorCounts.size()); info.pDescriptorCounts = variableDescriptorCounts.data(); allocateInfo.pNext = &info; } return device.allocateDescriptorSets(allocateInfo); } auto DescriptorSetMaker::createUnique( const vk::Device &device, vk::DescriptorPool descriptorPool) const -> std::vector<vk::UniqueDescriptorSet> { vk::DescriptorSetAllocateInfo allocateInfo; allocateInfo.descriptorPool = descriptorPool; allocateInfo.descriptorSetCount = uint32_t(layouts.size()); allocateInfo.pSetLayouts = layouts.data(); return device.allocateDescriptorSetsUnique(allocateInfo); } /** * \brief * \param updater * \param index */ DescriptorSetUpdater::BufferUpdater::BufferUpdater( DescriptorSetUpdater &updater, uint32_t index) : updater{updater}, index{index} {} auto DescriptorSetUpdater::BufferUpdater::buffer( vk::Buffer buffer, vk::DeviceSize offset, vk::DeviceSize range) -> BufferUpdater & { if(updater.numBuffers < updater.bufferInfo.size()) { updater.descriptorWrites[index].descriptorCount++; updater.bufferInfo[updater.numBuffers++] = vk::DescriptorBufferInfo{buffer, offset, range}; } else error("exceeding max number of buffers!"); return *this; } DescriptorSetUpdater::ImageUpdater::ImageUpdater( DescriptorSetUpdater &updater, uint32_t index) : updater{updater}, index{index} {} auto DescriptorSetUpdater::ImageUpdater::image( vk::Sampler sampler, vk::ImageView imageView, vk::ImageLayout imageLayout) -> ImageUpdater & { if(updater.numImages < updater.imageInfo.size()) { updater.descriptorWrites[index].descriptorCount++; updater.imageInfo[updater.numImages++] = vk::DescriptorImageInfo{sampler, imageView, imageLayout}; } else error("exceeding max number of images!"); return *this; } DescriptorSetUpdater::AccelerationStructureUpdater::AccelerationStructureUpdater( DescriptorSetUpdater &updater, uint32_t index) : updater{updater}, index{index} {} auto DescriptorSetUpdater::AccelerationStructureUpdater::accelerationStructure( const vk::AccelerationStructureNV &as) -> AccelerationStructureUpdater & { if(updater.numAccelerationStructures < updater.accelerationStructureInfo.size()) { updater.descriptorWrites[index].descriptorCount++; updater.descriptorWrites[index].pNext = updater.accelerationStructureInfo.data() + updater.numAccelerationStructures; updater.accelerationStructureInfo[updater.numAccelerationStructures++] = {1, &as}; } else error("exceeding max number of Acceleration Structures!"); return *this; } DescriptorSetUpdater::DescriptorSetUpdater( size_t maxBuffers, size_t maxImages, size_t maxBufferViews, size_t maxAccelerationStructures) { bufferInfo.resize(maxBuffers); imageInfo.resize(maxImages); bufferViews.resize(maxBufferViews); accelerationStructureInfo.resize(maxAccelerationStructures); } auto DescriptorSetUpdater::beginImages( uint32_t dstBinding, uint32_t dstArrayElement, vk::DescriptorType descriptorType) -> ImageUpdater { vk::WriteDescriptorSet writeDescriptorSet{ {}, dstBinding, dstArrayElement, 0, descriptorType, imageInfo.data() + numImages}; descriptorWrites.push_back(writeDescriptorSet); return ImageUpdater(*this, uint32_t(descriptorWrites.size() - 1)); } auto DescriptorSetUpdater::images( uint32_t dstBinding, uint32_t dstArrayElement, vk::DescriptorType descriptorType, uint32_t descriptorCount, vk::DescriptorImageInfo *pImageInfo) -> DescriptorSetUpdater & { vk::WriteDescriptorSet writeDescriptorSet{ {}, dstBinding, dstArrayElement, descriptorCount, descriptorType, pImageInfo}; descriptorWrites.push_back(writeDescriptorSet); return *this; } auto DescriptorSetUpdater::sampler2D( uint32_t dstBinding, uint32_t dstArrayElement, uint32_t descriptorCount, vk::DescriptorImageInfo *pImageInfo) -> DescriptorSetUpdater & { return images( dstBinding, dstArrayElement, descriptor::eCombinedImageSampler, descriptorCount, pImageInfo); } auto DescriptorSetUpdater::image( uint32_t dstBinding, uint32_t dstArrayElement, vk::DescriptorType descriptorType, vk::Sampler sampler, vk::ImageView imageView, vk::ImageLayout imageLayout) -> DescriptorSetUpdater & { beginImages(dstBinding, dstArrayElement, descriptorType) .image(sampler, imageView, imageLayout); return *this; } auto DescriptorSetUpdater::input(uint32_t dstBinding, vk::ImageView imageView) -> DescriptorSetUpdater & { return image( dstBinding, 0, descriptor::eInputAttachment, {}, imageView, vk::ImageLayout::eShaderReadOnlyOptimal); } auto DescriptorSetUpdater::storageImage(uint32_t dstBinding, vk::ImageView imageView) -> DescriptorSetUpdater & { return image( dstBinding, 0, descriptor::eStorageImage, {}, imageView, vk::ImageLayout::eGeneral); } auto DescriptorSetUpdater::beginBuffers( uint32_t dstBinding, uint32_t dstArrayElement, vk::DescriptorType descriptorType) -> BufferUpdater { vk::WriteDescriptorSet writeDescriptorSet{{}, dstBinding, dstArrayElement, 0, descriptorType, nullptr, bufferInfo.data() + numBuffers}; descriptorWrites.push_back(writeDescriptorSet); return BufferUpdater(*this, uint32_t(descriptorWrites.size() - 1)); } auto DescriptorSetUpdater::buffer( uint32_t dstBinding, uint32_t dstArrayElement, uint32_t descriptorCount, vk::DescriptorBufferInfo *pBufferInfo) -> DescriptorSetUpdater & { vk::WriteDescriptorSet writeDescriptorSet{ {}, dstBinding, dstArrayElement, descriptorCount, descriptor::eStorageBuffer, nullptr, pBufferInfo}; descriptorWrites.push_back(writeDescriptorSet); return *this; } auto DescriptorSetUpdater::buffer( uint32_t dstBinding, uint32_t dstArrayElement, vk::DescriptorType descriptorType, vk::Buffer buffer, vk::DeviceSize offset, vk::DeviceSize range) -> DescriptorSetUpdater & { beginBuffers(dstBinding, dstArrayElement, descriptorType).buffer(buffer, offset, range); return *this; } auto DescriptorSetUpdater::uniform(uint32_t dstBinding, vk::Buffer buffer) -> DescriptorSetUpdater & { return this->buffer( dstBinding, 0, descriptor::eUniformBuffer, buffer, 0, VK_WHOLE_SIZE); } auto DescriptorSetUpdater::uniformDynamic(uint32_t dstBinding, vk::Buffer buffer) -> DescriptorSetUpdater & { return this->buffer( dstBinding, 0, descriptor::eUniformBufferDynamic, buffer, 0, VK_WHOLE_SIZE); } auto DescriptorSetUpdater::buffer(uint32_t dstBinding, vk::Buffer buffer) -> DescriptorSetUpdater & { return this->buffer( dstBinding, 0, descriptor::eStorageBuffer, buffer, 0, VK_WHOLE_SIZE); } auto DescriptorSetUpdater::beginAccelerationStructures( uint32_t dstBinding, uint32_t dstArrayElement) -> AccelerationStructureUpdater { vk::WriteDescriptorSet writeDescriptorSet{ {}, dstBinding, dstArrayElement, 0, descriptor::eAccelerationStructureNV}; descriptorWrites.push_back(writeDescriptorSet); return AccelerationStructureUpdater(*this, uint32_t(descriptorWrites.size() - 1)); } auto DescriptorSetUpdater::accelerationStructure( uint32_t dstBinding, const vk::AccelerationStructureNV &as) -> DescriptorSetUpdater & { beginAccelerationStructures(dstBinding, 0).accelerationStructure(as); return *this; } auto DescriptorSetUpdater::update( const vk::Device &device, const vk::DescriptorSet &descriptorSet) -> void { for(auto &write: descriptorWrites) write.dstSet = descriptorSet; for(auto &copy: descriptorCopies) copy.dstSet = descriptorSet; device.updateDescriptorSets(descriptorWrites, descriptorCopies); } auto DescriptorSetUpdater::reset() -> void { descriptorWrites.clear(); descriptorCopies.clear(); numBuffers = 0; numImages = 0; numBufferViews = 0; numAccelerationStructures = 0; } }
37.655738
90
0.764403
[ "vector" ]
38e1132ac7a30b836b19bbb0a5864bd652e94aaa
12,803
cpp
C++
src/csaltTester/src/TestOptCtrl/src/Shell/ShellDriver.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
src/csaltTester/src/TestOptCtrl/src/Shell/ShellDriver.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
src/csaltTester/src/TestOptCtrl/src/Shell/ShellDriver.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ // ShellDriver //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2020 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under Purchase // Order NNG16LD52P // // Author: Claire R. Conway, Thinking Systems, Inc. // Created: Mar 13, 2017 /** * INSTRUCTIONS: * - Find & replace "Shell" with the actual name for your driver. * - Follow the comments in "Run" to customize it. * - Check that the path and point .cpp and .hpp files are in the * TestOptCtrl/src/pointpath directory. * - Add "src/ShellDriver.o" to the Driver list in the Makefile. * - Add the following lines to the Objects list in the Makefile, below the * existing path and point objects: * $(TEST_ROOT)/TestOptCtrl/src/pointpath/ShellPathObject.o \ * $(TEST_ROOT)/TestOptCtrl/src/pointpath/ShellPointObject.o \ * */ //------------------------------------------------------------------------------ #include "ShellDriver.hpp" //#define DEBUG_SHOWRESULTS static const Real INF = std::numeric_limits<Real>::infinity(); using namespace std; using namespace GmatMathConstants; ShellDriver::ShellDriver() { // TODO Auto-generated constructor stub } ShellDriver::~ShellDriver() { // TODO Auto-generated destructor stub } Real ShellDriver::GetMaxError(const Rvector &vec) { Real max = -999.99; for (Integer ii = 0; ii < vec.GetSize(); ii++) if (vec(ii) > max) max = vec(ii); return max; } Real ShellDriver::GetMaxError(const Rmatrix &mat) { Real max = -999.99; Integer r, c; mat.GetSize(r,c); for (Integer ii = 0; ii < r; ii++) for (Integer jj = 0; jj < c; jj++) if (mat(ii,jj) > max) max = mat(ii,jj); return max; } int ShellDriver::Run() { std::string outFormat = "%16.9f "; //If this test uses ImplicitRungeKutta phases, set this to false. bool useRadau = true; ConsoleMessageReceiver *consoleMsg = ConsoleMessageReceiver::Instance(); MessageInterface::SetMessageReceiver(consoleMsg); std::string outPath = "./"; MessageInterface::SetLogFile(outPath + "GmatLog.txt"); MessageInterface::ShowMessage("%s\n", GmatTimeUtil::FormatCurrentTime().c_str()); // Set global format setting GmatGlobal *global = GmatGlobal::Instance(); global->SetActualFormat(false, false, 16, 1, false); char *buffer = NULL; buffer = getenv("OS"); if (buffer != NULL) { MessageInterface::ShowMessage("Current OS is %s\n", buffer); } else { MessageInterface::ShowMessage("The Operating System was not detected\n"); } MessageInterface::ShowMessage("*** START TEST ***\n"); MessageInterface::ShowMessage("*** TESTing Shell optimization problem ***\n"); try { // --------------------------------------------------------------------- // ========================================================================== // ===== Define Properties for the Trajectory // Create trajectory and configure user function names MessageInterface::ShowMessage("*** TEST *** Creating & configuring trajectory\n"); ShellPathObject *pathFunctionObject = new ShellPathObject(); ShellPointObject *pointFunctionObject = new ShellPointObject(); //Adjust these values based on your test problem. Real costLowerBound = -INF; Real costUpperBound = INF; Integer maxMeshRefinementCount = 8; Trajectory *traj = new Trajectory(); traj->SetUserPathFunction(pathFunctionObject); traj->SetUserPointFunction(pointFunctionObject); traj->SetCostLowerBound(costLowerBound); traj->SetCostUpperBound(costUpperBound); traj->SetMaxMeshRefinementCount(maxMeshRefinementCount); //PHASE 1 MessageInterface::ShowMessage("*** Creating the first phase\n"); MessageInterface::ShowMessage("*** TEST *** Setting Phase 1 mesh properties\n"); //Set mesh properties Rvector meshIntervalFractions; IntegerArray meshIntervalNumPoints; Phase *phase1; //Uncomment and modify as needed for multiphase problems. //Phase *phase2, *phase3; if (useRadau) { //If using Radau, adjust these values based on your test problem. phase1 = new RadauPhase(); meshIntervalFractions.SetSize(9); meshIntervalFractions[0] = -1.0; meshIntervalFractions[1] = -0.75; meshIntervalFractions[2] = -0.5; meshIntervalFractions[3] = -0.25; meshIntervalFractions[4] = 0.0; meshIntervalFractions[5] = 0.25; meshIntervalFractions[6] = 0.5; meshIntervalFractions[7] = 0.75; meshIntervalFractions[8] = 1.0; meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); meshIntervalNumPoints.push_back(4); } else { //If using ImplicitRungeKutta, adjust these values based on your test problem. ImplicitRKPhase *rkphase = new ImplicitRKPhase(); rkphase->SetTranscription("RungeKutta8"); phase1 = rkphase; meshIntervalFractions.SetSize(2); meshIntervalFractions[0] = 0.0; meshIntervalFractions[1] = 1.0; meshIntervalNumPoints.push_back(5); } //Adjust this value based on your test problem. std::string initialGuessMode = "LinearUnityControl"; //Adjust these values based on your test problem. MessageInterface::ShowMessage("*** TEST *** Setting Phase 1 time properties\n"); //Set time properties Real timeLowerBound = 0.0; Real timeUpperBound = 0.0; Real initialGuessTime = 0.0; Real finalGuessTime = 0.0; //Adjust these values based on your test problem. MessageInterface::ShowMessage("*** TEST *** Setting Phase 1 state properties\n"); //Set state properties Integer numStateVars = 1; Rvector stateLowerBound(1, 0.0); Rvector initialGuessState(1, 0.0); Rvector finalGuessState(1, 0.0); Rvector stateUpperBound(1, 0.0); //Adjust these values based on your test problem. MessageInterface::ShowMessage("*** TEST *** Setting Phase 1 control properties\n"); //Set control properties Integer numControlVars = 1; Rvector controlUpperBound(1, 0.0); Rvector controlLowerBound(1, 0.0); phase1->SetInitialGuessMode(initialGuessMode); phase1->SetNumStateVars(numStateVars); phase1->SetNumControlVars(numControlVars); phase1->SetMeshIntervalFractions(meshIntervalFractions); phase1->SetMeshIntervalNumPoints(meshIntervalNumPoints); phase1->SetStateLowerBound(stateLowerBound); phase1->SetStateUpperBound(stateUpperBound); phase1->SetStateInitialGuess(initialGuessState); phase1->SetStateFinalGuess(finalGuessState); phase1->SetTimeLowerBound(timeLowerBound); phase1->SetTimeUpperBound(timeUpperBound); phase1->SetTimeInitialGuess(initialGuessTime); phase1->SetTimeFinalGuess(finalGuessTime); phase1->SetControlLowerBound(controlLowerBound); phase1->SetControlUpperBound(controlUpperBound); //If your problem has more than 1 phase, uncomment the following block and adjust //the variables to create the second phase. Make and adjust a copy for each //additional phase. /* //PHASE 2 MessageInterface::ShowMessage("*** Creating the second phase\n"); MessageInterface::ShowMessage("*** TEST *** Setting Phase 2 mesh properties\n"); //Set mesh properties if (useRadau) { phase2 = new RadauPhase(); } else { ImplicitRKPhase *rkphase = new ImplicitRKPhase(); rkphase->SetTranscription("RungeKutta8"); phase2 = rkphase; } MessageInterface::ShowMessage("*** TEST *** Setting Phase 2 time properties\n"); //Set time properties timeLowerBound = 0.0; timeUpperBound = 0.0; initialGuessTime = 0.0; finalGuessTime = 0.0; MessageInterface::ShowMessage("*** TEST *** Setting Phase 2 state properties\n"); //Set state properties numStateVars = 1; Rvector stateLowerBound2(1, 0.0); Rvector initialGuessState2(1, 0.0); Rvector finalGuessState2(1, 0.0); Rvector stateUpperBound2(1, 0.0); MessageInterface::ShowMessage("*** TEST *** Setting Phase 2 control properties\n"); //Set control properties Rvector controlUpperBound2(1, 0.0); Rvector controlLowerBound2(1, 0.0); phase2->SetInitialGuessMode(initialGuessMode); phase2->SetNumStateVars(numStateVars); phase2->SetNumControlVars(numControlVars); phase2->SetMeshIntervalFractions(meshIntervalFractions); phase2->SetMeshIntervalNumPoints(meshIntervalNumPoints); phase2->SetStateLowerBound(stateLowerBound2); phase2->SetStateUpperBound(stateUpperBound2); phase2->SetStateInitialGuess(initialGuessState2); phase2->SetStateFinalGuess(finalGuessState2); phase2->SetTimeLowerBound(timeLowerBound); phase2->SetTimeUpperBound(timeUpperBound); phase2->SetTimeInitialGuess(initialGuessTime); phase2->SetTimeFinalGuess(finalGuessTime); phase2->SetControlLowerBound(controlLowerBound2); phase2->SetControlUpperBound(controlUpperBound2); */ std::vector<Phase*> pList; pList.push_back(phase1); //If there are multiple phases, push each one. //pList.push_back(phase2); MessageInterface::ShowMessage("Setting phase list\n"); traj->SetPhaseList(pList); //Nothing below this point typically needs to be customized. MessageInterface::ShowMessage("*** TEST *** initializing the Trajectory\n"); // Initialize the Trajectory traj->Initialize(); MessageInterface::ShowMessage("*** TEST *** setting up the call to Optimize!!\n"); Rvector dv2 = traj->GetDecisionVector(); Rvector C = traj->GetCostConstraintFunctions(); // nonDim); RSMatrix conSp = phase1->GetConSparsityPattern(); // ------------------ Optimizing ----------------------------------------------- // TRY it first without optimizing Rvector z = dv2; Rvector F(C.GetSize()); Rvector xmul(dv2.GetSize()); Rvector Fmul(C.GetSize()); MessageInterface::ShowMessage("*** TEST *** Optimizing!!\n"); traj->Optimize(z, F, xmul, Fmul); } catch (LowThrustException &ex) { MessageInterface::ShowMessage("%s\n", ex.GetDetails().c_str()); } #ifdef DEBUG_SHOWRESULTS MessageInterface::ShowMessage("*** TEST *** z:\n%s\n", z.ToString(12).c_str()); MessageInterface::ShowMessage("*** TEST *** F:\n%s\n", F.ToString(12).c_str()); MessageInterface::ShowMessage("*** TEST *** xmul:\n%s\n", xmul.ToString(12).c_str()); MessageInterface::ShowMessage("*** TEST *** Fmul:\n%s\n", Fmul.ToString(12).c_str()); MessageInterface::ShowMessage("*** TEST *** Optimization complete!!\n"); // ------------------ Optimizing ----------------------------------------------- Rvector dvP1 = phase1->GetDecVector(); MessageInterface::ShowMessage("*** TEST *** dvP1:\n%s\n", dvP1.ToString(12).c_str()); // Interpolate solution Rvector timeVector = phase1->GetTimeVector(); DecisionVector *dv = phase1->GetDecisionVector(); Rmatrix stateSol = dv->GetStateArray(); Rmatrix controlSol = dv->GetControlArray(); #endif MessageInterface::ShowMessage("*** END Shell TEST ***\n"); return 0; }
37.110145
89
0.633211
[ "mesh", "vector" ]
38e155f11195ca1df2130307e64cd67034bb2ad1
26,389
cpp
C++
src/wasmer.cpp
bxq2011hust/hera
2b033dafbb8553bcf83d382f81c54e756a316ab2
[ "Apache-2.0" ]
null
null
null
src/wasmer.cpp
bxq2011hust/hera
2b033dafbb8553bcf83d382f81c54e756a316ab2
[ "Apache-2.0" ]
null
null
null
src/wasmer.cpp
bxq2011hust/hera
2b033dafbb8553bcf83d382f81c54e756a316ab2
[ "Apache-2.0" ]
null
null
null
/* 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 "wasmer.h" #include "runtime-c-api/wasmer.hh" #include <cstdio> #include <vector> #include <memory> #include "debugging.h" #include <functional> #include <iostream> #include <set> using namespace std; namespace hera { class WasmerEthereumInterface : public EthereumInterface { public: explicit WasmerEthereumInterface(evmc::HostContext &_context, bytes_view _code, evmc_message const &_msg, ExecutionResult &_result, bool _meterGas) : EthereumInterface(_context, _code, _msg, _result, _meterGas) { } void setWasmMemory(const wasmer_memory_t *_wasmMemory) { m_wasmMemory = _wasmMemory; } private: // These assume that m_wasmMemory was set prior to execution. size_t memorySize() const override { return wasmer_memory_data_length(m_wasmMemory); } void memorySet(size_t offset, uint8_t value) override { auto data = wasmer_memory_data(m_wasmMemory); data[offset] = value; } uint8_t memoryGet(size_t offset) override { auto data = wasmer_memory_data(m_wasmMemory); return data[offset]; } uint8_t *memoryPointer(size_t offset, size_t length) override { ensureCondition(memorySize() >= (offset + length), InvalidMemoryAccess, "Memory is shorter than requested segment"); auto data = wasmer_memory_data(m_wasmMemory); return data + offset; } const wasmer_memory_t *m_wasmMemory; }; unique_ptr<WasmEngine> WasmerEngine::create() { return unique_ptr<WasmEngine>{new WasmerEngine}; } namespace { wasmer_value_tag i32[] = {wasmer_value_tag::WASM_I32}; wasmer_value_tag i64[] = {wasmer_value_tag::WASM_I64}; wasmer_value_tag i64_i32[] = {wasmer_value_tag::WASM_I64, wasmer_value_tag::WASM_I32}; wasmer_value_tag i32_2[] = {wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32}; wasmer_value_tag i32_3[] = {wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32}; wasmer_value_tag i32_4[] = {wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32}; wasmer_value_tag i32_7[] = {wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32, wasmer_value_tag::WASM_I32}; // Function to print the most recent error string from Wasmer if we have them string getWasmerErrorString() { int error_len = wasmer_last_error_length(); char *error_str = new char[(uint64_t)error_len]; wasmer_last_error_message(error_str, error_len); string error(error_str, (unsigned long)error_len); delete[] error_str; return error; } wasmer_byte_array getNameArray(const char *name) { return wasmer_byte_array{(const uint8_t *)name, (uint32_t)strlen(name)}; } WasmerEthereumInterface *getInterfaceFromVontext(wasmer_instance_context_t *ctx) { return (WasmerEthereumInterface *)wasmer_instance_context_data_get(ctx); } void eeiUseGas(wasmer_instance_context_t *ctx, int64_t gas) { auto interface = getInterfaceFromVontext(ctx); interface->eeiUseGas(gas); } int64_t eeiGetGasLeft(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetGasLeft(); } void eeiGetAddress(wasmer_instance_context_t *ctx, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetAddress(resultOffset); } void eeiGetExternalBalance(wasmer_instance_context_t *ctx, uint32_t addressOffset, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetExternalBalance(addressOffset, resultOffset); } uint32_t eeiGetBlockHash(wasmer_instance_context_t *ctx, uint64_t number, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetBlockHash(number, resultOffset); } uint32_t eeiGetCallDataSize(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetCallDataSize(); } void eeiCallDataCopy(wasmer_instance_context_t *ctx, uint32_t resultOffset, uint32_t dataOffset, uint32_t length) { auto interface = getInterfaceFromVontext(ctx); interface->eeiCallDataCopy(resultOffset, dataOffset, length); } void eeiGetCaller(wasmer_instance_context_t *ctx, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetCaller(resultOffset); } void eeiGetCallValue(wasmer_instance_context_t *ctx, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetCallValue(resultOffset); } void eeiCodeCopy(wasmer_instance_context_t *ctx, uint32_t resultOffset, uint32_t codeOffset, uint32_t length) { auto interface = getInterfaceFromVontext(ctx); interface->eeiCodeCopy(resultOffset, codeOffset, length); } uint32_t eeiGetCodeSize(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetCodeSize(); } void eeiExternalCodeCopy(wasmer_instance_context_t *ctx, uint32_t addressOffset, uint32_t resultOffset, uint32_t codeOffset, uint32_t length) { auto interface = getInterfaceFromVontext(ctx); interface->eeiExternalCodeCopy(addressOffset, resultOffset, codeOffset, length); } uint32_t eeiGetExternalCodeSize(wasmer_instance_context_t *ctx, uint32_t addressOffset) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetExternalCodeSize(addressOffset); } void eeiGetBlockCoinbase(wasmer_instance_context_t *ctx, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetBlockCoinbase(resultOffset); } void eeiGetBlockDifficulty(wasmer_instance_context_t *ctx, uint32_t offset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetBlockDifficulty(offset); } int64_t eeiGetBlockGasLimit(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetBlockGasLimit(); } void eeiGetTxGasPrice(wasmer_instance_context_t *ctx, uint32_t valueOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetTxGasPrice(valueOffset); } void eeiLog(wasmer_instance_context_t *ctx, uint32_t dataOffset, uint32_t length, uint32_t numberOfTopics, uint32_t topic1, uint32_t topic2, uint32_t topic3, uint32_t topic4) { auto interface = getInterfaceFromVontext(ctx); interface->eeiLog(dataOffset, length, numberOfTopics, topic1, topic2, topic3, topic4); } int64_t eeiGetBlockNumber(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetBlockNumber(); } int64_t eeiGetBlockTimestamp(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetBlockTimestamp(); } void eeiGetTxOrigin(wasmer_instance_context_t *ctx, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiGetTxOrigin(resultOffset); } void eeiStorageStore(wasmer_instance_context_t *ctx, uint32_t pathOffset, uint32_t valueOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiStorageStore(pathOffset, valueOffset); } void eeiStorageLoad(wasmer_instance_context_t *ctx, uint32_t pathOffset, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiStorageLoad(pathOffset, resultOffset); } void eeiFinish(wasmer_instance_context_t *ctx, uint32_t offset, uint32_t size) { auto interface = getInterfaceFromVontext(ctx); interface->eeiFinish(offset, size); } void eeiRevert(wasmer_instance_context_t *ctx, uint32_t offset, uint32_t size) { auto interface = getInterfaceFromVontext(ctx); interface->eeiRevert(offset, size); } uint32_t eeiGetReturnDataSize(wasmer_instance_context_t *ctx) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiGetReturnDataSize(); } void eeiReturnDataCopy(wasmer_instance_context_t *ctx, uint32_t dataOffset, uint32_t offset, uint32_t size) { auto interface = getInterfaceFromVontext(ctx); interface->eeiReturnDataCopy(dataOffset, offset, size); } uint32_t eeiCreate(wasmer_instance_context_t *ctx, uint32_t valueOffset, uint32_t dataOffset, uint32_t length, uint32_t resultOffset) { auto interface = getInterfaceFromVontext(ctx); return interface->eeiCreate(valueOffset, dataOffset, length, resultOffset); } void eeiSelfDestruct(wasmer_instance_context_t *ctx, uint32_t addressOffset) { auto interface = getInterfaceFromVontext(ctx); interface->eeiSelfDestruct(addressOffset); } #if HERA_DEBUGGING void print32(wasmer_instance_context_t *, uint32_t value) { HERA_DEBUG<< "DEBUG print32: " << value << " " << hex << "0x" << value << dec << endl; } void print64(wasmer_instance_context_t *, uint64_t value) { HERA_DEBUG<< "DEBUG print64: " << value << " " << hex << "0x" << value << dec << endl; } void printMem(wasmer_instance_context_t *ctx, uint32_t offset, uint32_t size) { auto interface = getInterfaceFromVontext(ctx); interface->debugPrintMem(false, offset, size); } void printMemHex(wasmer_instance_context_t *ctx, uint32_t offset, uint32_t size) { auto interface = getInterfaceFromVontext(ctx); interface->debugPrintMem(true, offset, size); } void printStorage(wasmer_instance_context_t *ctx, uint32_t offset) { auto interface = getInterfaceFromVontext(ctx); interface->debugPrintStorage(false, offset); } void printStorageHex(wasmer_instance_context_t *ctx, uint32_t offset) { auto interface = getInterfaceFromVontext(ctx); interface->debugPrintStorage(true, offset); } #endif shared_ptr<vector<wasmer_import_t>> initImportes() { wasmer_byte_array ethModule = getNameArray("ethereum"); shared_ptr<vector<wasmer_import_t>> imports( new vector<wasmer_import_t>{ {ethModule, getNameArray("useGas"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiUseGas, i64, 1, NULL, 0)}, {ethModule, getNameArray("getGasLeft"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetGasLeft, NULL, 0, i64, 1)}, {ethModule, getNameArray("getAddress"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetAddress, i32, 1, NULL, 0)}, {ethModule, getNameArray("getExternalBalance"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetExternalBalance, i32_2, 2, NULL, 0)}, {ethModule, getNameArray("getBlockHash"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetBlockHash, i64_i32, 2, i32, 1)}, {ethModule, getNameArray("getCallDataSize"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetCallDataSize, NULL, 0, i32, 1)}, {ethModule, getNameArray("callDataCopy"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiCallDataCopy, i32_3, 3, i32, 1)}, {ethModule, getNameArray("getCaller"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetCaller, i32, 1, NULL, 0)}, {ethModule, getNameArray("getCallValue"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetCallValue, i32, 1, NULL, 0)}, {ethModule, getNameArray("codeCopy"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiCodeCopy, i32_3, 3, NULL, 0)}, {ethModule, getNameArray("getCodeSize"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetCodeSize, NULL, 0, i32, 1)}, {ethModule, getNameArray("externalCodeCopy"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiExternalCodeCopy, i32_4, 4, NULL, 0)}, {ethModule, getNameArray("getExternalCodeSize"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetExternalCodeSize, i32, 1, i32, 1)}, {ethModule, getNameArray("getBlockCoinbase"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetBlockCoinbase, i32, 1, NULL, 0)}, {ethModule, getNameArray("getBlockDifficulty"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetBlockDifficulty, i32, 1, NULL, 0)}, {ethModule, getNameArray("getBlockGasLimit"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetBlockGasLimit, NULL, 0, i64, 1)}, {ethModule, getNameArray("getTxGasPrice"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetTxGasPrice, i32, 1, NULL, 0)}, {ethModule, getNameArray("log"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiLog, i32_7, 7, NULL, 0)}, {ethModule, getNameArray("getBlockNumber"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetBlockNumber, NULL, 0, i64, 1)}, {ethModule, getNameArray("getBlockTimestamp"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetBlockTimestamp, NULL, 0, i64, 1)}, {ethModule, getNameArray("getTxOrigin"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetTxOrigin, i32, 1, NULL, 0)}, {ethModule, getNameArray("storageStore"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiStorageStore, i32_2, 2, NULL, 0)}, {ethModule, getNameArray("storageLoad"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiStorageLoad, i32_2, 2, NULL, 0)}, {ethModule, getNameArray("finish"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiFinish, i32_2, 2, NULL, 0)}, {ethModule, getNameArray("revert"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiRevert, i32_2, 2, NULL, 0)}, {ethModule, getNameArray("getReturnDataSize"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiGetReturnDataSize, NULL, 0, i32, 1)}, {ethModule, getNameArray("returnDataCopy"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiReturnDataCopy, i32_3, 3, NULL, 0)}, {ethModule, getNameArray("create"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiCreate, i32_4, 4, NULL, 0)}, {ethModule, getNameArray("selfDestruct"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))eeiSelfDestruct, i32, 1, NULL, 0)}, }, [](auto p) { for (size_t i = 0; i < p->size(); ++i) { wasmer_import_func_destroy((wasmer_import_func_t *)p->at(i).value.func); } delete p; }); #if HERA_DEBUGGING wasmer_byte_array debugModule = getNameArray("debug"); imports->push_back(wasmer_import_t{debugModule, getNameArray("print32"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))print32, i32, 1, NULL, 0)}); imports->push_back(wasmer_import_t{debugModule, getNameArray("print64"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))print64, i64, 1, NULL, 0)}); imports->push_back(wasmer_import_t{debugModule, getNameArray("printMem"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))printMem, i32_2, 2, NULL, 0)}); imports->push_back(wasmer_import_t{debugModule, getNameArray("printMemHex"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))printMemHex, i32_2, 2, NULL, 0)}); imports->push_back(wasmer_import_t{debugModule, getNameArray("printStorage"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))printStorage, i32, 1, NULL, 0)}); imports->push_back(wasmer_import_t{debugModule, getNameArray("printStorageHex"), wasmer_import_export_kind::WASM_FUNCTION, .value.func = wasmer_import_func_new((void (*)(void *))printStorageHex, i32, 1, NULL, 0)}); #endif return imports; } } // namespace static const set<string> eeiFunctions{"useGas", "getGasLeft", "getAddress", "getExternalBalance", "getBlockHash", "getCallDataSize", "callDataCopy", "getCaller", "getCallValue", "codeCopy", "getCodeSize", "externalCodeCopy", "getExternalCodeSize", "getBlockCoinbase", "getBlockDifficulty", "getBlockGasLimit", "getTxGasPrice", "log", "getBlockNumber", "getBlockTimestamp", "getTxOrigin", "storageStore", "storageLoad", "finish", "revert", "getReturnDataSize", "returnDataCopy", "call", "callCode", "callDelegate", "callStatic", "create", "selfDestruct"}; void WasmerEngine::verifyContract(bytes_view code) { auto codeData = new unsigned char[code.size()]; memcpy(codeData, code.data(), code.size()); wasmer_module_t *module; auto compile_result = wasmer_compile(&module, codeData, (unsigned int)code.size()); ensureCondition( compile_result == wasmer_result_t::WASMER_OK, ContractValidationFailure, "Compile wasm failed."); wasmer_export_descriptors_t *exports; wasmer_export_descriptors(module, &exports); auto len = wasmer_export_descriptors_len(exports); for (int i = 0; i < len; ++i) { auto exportObj = wasmer_export_descriptors_get(exports, i); auto nameBytes = wasmer_export_descriptor_name(exportObj); string objectName((char *)nameBytes.bytes, nameBytes.bytes_len); if (objectName == "memory") { // multiple memories are not supported for wasmer 0.17.0 ensureCondition(wasmer_export_descriptor_kind(exportObj) == wasmer_import_export_kind::WASM_MEMORY, ContractValidationFailure, "\"memory\" is not pointing to memory."); } else if (objectName == "main") { ensureCondition(wasmer_export_descriptor_kind(exportObj) == wasmer_import_export_kind::WASM_FUNCTION, ContractValidationFailure, "\"main\" is not pointing to function."); } else { ensureCondition(false, ContractValidationFailure, "Invalid export is present."); } } wasmer_export_descriptors_destroy(exports); wasmer_import_descriptors_t *imports; wasmer_import_descriptors(module, &imports); auto importsLength = wasmer_import_descriptors_len(imports); for (unsigned int i = 0; i < importsLength; ++i) { auto importObj = wasmer_import_descriptors_get(imports, i); auto moduleNameBytes = wasmer_import_descriptor_module_name(importObj); string moduleName((char *)moduleNameBytes.bytes, moduleNameBytes.bytes_len); #if HERA_DEBUGGING if (moduleName == "debug") continue; #endif ensureCondition(moduleName == "ethereum", ContractValidationFailure, "Import from invalid namespace."); auto nameBytes = wasmer_import_descriptor_name(importObj); string objectName((char *)nameBytes.bytes, nameBytes.bytes_len); ensureCondition(eeiFunctions.count(objectName), ContractValidationFailure, "Importing invalid EEI method."); ensureCondition(wasmer_import_descriptor_kind(importObj) == wasmer_import_export_kind::WASM_FUNCTION, ContractValidationFailure, "Imported function type mismatch."); } wasmer_import_descriptors_destroy(imports); wasmer_module_destroy(module); } ExecutionResult WasmerEngine::execute(evmc::HostContext &context, bytes_view code, bytes_view state_code, evmc_message const &msg, bool meterInterfaceGas) { instantiationStarted(); HERA_DEBUG << "Executing with wasmer...\n"; // Set up interface to eei host functions ExecutionResult result; WasmerEthereumInterface interface{context, state_code, msg, result, meterInterfaceGas}; // Define an array containing our imports auto imports = initImportes(); // Instantiate a WebAssembly Instance from Wasm bytes and imports wasmer_instance_t *instance = NULL; auto codeData = new unsigned char[code.size()]; memcpy(codeData, code.data(), code.size()); wasmer_result_t compile_result = wasmer_instantiate(&instance, // Our reference to our Wasm instance codeData, // The bytes of the WebAssembly modules (uint32_t)code.size(), // The length of the bytes of the WebAssembly module static_cast<wasmer_import_t *>(imports->data()), // The Imports array the will be used as our importObject (int32_t)imports->size() // The number of imports in the imports array ); ensureCondition(compile_result == wasmer_result_t::WASMER_OK, ContractValidationFailure, string("Compile wasm failed, ") + getWasmerErrorString()); // Assert the Wasm instantion completed wasmer_instance_context_data_set(instance, (void *)&interface); auto ctx = wasmer_instance_context_get(instance); interface.setWasmMemory(wasmer_instance_context_memory(ctx, 0)); // Call the Wasm function wasmer_result_t call_result = wasmer_instance_call( instance, // Our Wasm Instance "main", // the name of the exported function we want to call on the guest Wasm module NULL, // Our array of parameters 0, // The number of parameters NULL, // Our array of results 0 // The number of results ); ensureCondition(call_result == wasmer_result_t::WASMER_OK, EndExecution, string("Call main failed, ") + getWasmerErrorString()); wasmer_instance_destroy(instance); return result; }; } // namespace hera
57.24295
232
0.643564
[ "vector" ]
38ee0a0d07d5fa5cad9843c3a7b2972714b9daa1
7,240
hxx
C++
src/krn/mws-mod.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
1
2017-12-26T14:29:37.000Z
2017-12-26T14:29:37.000Z
src/krn/mws-mod.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
src/krn/mws-mod.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
#pragma once #include "pfm.hxx" #include "krn.hxx" #include <functional> #include <memory> #include <string> #include <vector> class mws_app_storage_impl; class mws_mod_ctrl; class mws_mod_list; class mws_page_tab; class mws_key_ctrl; class mws_touch_ctrl; class updatectrl; class gfx_scene; class mws_camera; class mws_file; class mws_list_model; class mws_video_params; class app_impl { public: virtual ~app_impl() {} protected: app_impl() {} }; class mws_mod_settings { public: mws_mod_settings(); bool requires_gfx; bool log_enabled; uint32_t pref_screen_width; uint32_t pref_screen_height; double pref_aspect_ratio; bool start_full_screen; bool draw_touch_symbols_trail; bool show_onscreen_console; bool show_fps; uint32_t font_db_pow_of_two_size; bool emulate_mobile_screen; }; class mws_app_storage { public: const mws_file_map& get_res_file_list() const; std::vector<std::byte> load_as_byte_vect(mws_sp<mws_file> i_file) const; std::vector<std::byte> load_as_byte_vect(const mws_path& i_file_path) const; mws_sp<std::vector<std::byte>> load_as_sp_byte_vect(const mws_path& i_file_path) const; std::string load_as_string(mws_sp<mws_file> i_file) const; std::string load_as_string(const mws_path& i_file_path) const; // writable/private/persistent files directory const mws_path& prv_dir() const; // read-only/resource files directory const mws_path& res_dir() const; // temporary files directory const mws_path& tmp_dir() const; // screenshot void save_screenshot(const mws_path& i_file_path = "") const; // screen video recording void start_recording_screen(const mws_path& i_file_path = "", const mws_video_params* i_params = nullptr); void stop_recording_screen(); bool is_recording_screen(); void toggle_screen_recording(); private: friend class mws_mod; friend class mws_mod_ctrl; mws_app_storage(); mws_up<mws_app_storage_impl> p; }; class mws_mod : public std::enable_shared_from_this<mws_mod>, public mws_node { public: enum mod_type { e_mod_base, e_mod_list, }; virtual ~mws_mod(); virtual mod_type get_mod_type(); uint32_t get_width(); uint32_t get_height(); // internal name (only used inside the engine for identification purposes). may be the same as external name const std::string& name() const; void name(const std::string& i_name); // external (display name). this is used for example, when setting the application name. may be the same as internal name const std::string& external_name() const; void external_name(const std::string& i_name); const std::string& description() const; void description(const std::string& i_description); const mws_path& get_proj_rel_path(); void set_proj_rel_path(const mws_path& i_path); bool is_gfx_mod(); const mws_mod_settings& settings() const { return settings_v; } // true to exit app, false to continue virtual bool back(); void run_on_next_frame_start(const std::function<void()>& i_op); void run_on_crt_frame_end(const std::function<void()>& i_op); /// return a reference to the app_impl implementation template <typename T> T& i_m() const { mws_assert(p.get() != nullptr); return *mws_dynamic_cast<T*>(p.get()); } bool i_m_is_null() const { return p.get() == nullptr; } virtual void process(mws_sp<mws_dp> i_dp); bool handle_function_key(mws_key_types i_key); virtual void config_font_db_size(); uint32_t game_time = 0; mws_sp<updatectrl> update_ctrl_inst; mws_sp<mws_touch_ctrl> touch_ctrl_inst; mws_sp<mws_key_ctrl> key_ctrl_inst; mws_sp<gfx_scene> gfx_scene_inst; mws_sp<mws_camera> mws_cam; mws_sp<mws_page_tab> mws_root; mws_app_storage storage; protected: mws_mod(const char* i_include_guard); mws_sp<mws_mod> get_smtp_instance(); void set_internal_name_from_include_guard(const char* i_include_guard); static void exit_on_next_run(bool i_app_exit_on_next_run); static bool gfx_available(); virtual bool update(); virtual void pre_update() {} virtual void post_update() {} virtual void on_resize(); virtual void on_pause() {} virtual void on_resume() {} virtual void receive(mws_sp<mws_dp> i_dp); // finish-constructor. here you can use things that won't work in the constructor, ie shared_from_this(), etc virtual void base_init(); /** called on entering the mws_mod for the first time */ virtual void init() {} /** called before the mws_mod is destroyed */ virtual void on_destroy(); /** creates the sws pages */ virtual void build_sws() {} /** initializes the sws pages */ virtual void init_sws(); /** loads the sws pages/items into the scene by calling the 2 methods above */ virtual void load_sws(); /** called on entering the mws_mod */ virtual void load() {} /** called on leaving the mws_mod */ virtual void unload() {} virtual mws_sp<mws_sender> sender_inst(); virtual void update_view(uint32_t update_count); virtual void post_update_view(); mws_up<app_impl> p; mws_mod_settings settings_v; uint32_t frame_count = 0; float fps = 0.f; uint32_t last_frame_time = 0; private: using operation_queue_type = std::vector<std::function<void()>>; friend class mws_mod_ctrl; friend class mws_mod_list; void run_step(); void base_load(); void base_unload(); bool is_init(); void set_init(bool i_is_init); // mws_mod name/id std::string name_v; // mws_mod external/display name std::string external_name_v; std::string description_v; // mws_mod path, relative to project (appplex) path mws_path proj_rel_path; mws_wp<mws_mod> parent; bool init_val = false; operation_queue_type on_frame_begin_q0, on_frame_begin_q1; mws_atomic_ptr_swap<operation_queue_type> on_frame_begin_q_ptr = mws_atomic_ptr_swap<operation_queue_type>(&on_frame_begin_q0, &on_frame_begin_q1); operation_queue_type on_frame_end_q0, on_frame_end_q1; mws_atomic_ptr_swap<operation_queue_type> on_frame_end_q_ptr = mws_atomic_ptr_swap<operation_queue_type>(&on_frame_end_q0, &on_frame_end_q1); inline static uint32_t mod_count = 0; }; class mws_mod_list : public mws_mod { public: static mws_sp<mws_mod_list> nwi(); mod_type get_mod_type(); void add(mws_sp<mws_mod> i_mod); mws_sp<mws_mod> mod_at(uint32_t i_index); mws_sp<mws_mod> mod_by_name(const std::string& i_name); uint32_t get_mod_count()const; virtual void on_resize(); virtual void receive(mws_sp<mws_dp> i_dp); void forward(); static void up_one_level(); protected: mws_mod_list(); virtual void on_destroy(); virtual void build_sws(); private: friend class mws_mod_ctrl; std::vector<mws_sp<mws_mod>> ulist; mws_wp<mws_list_model> ulmodel; static uint32_t mod_list_count; }; class mws_mod_setup { private: friend class mws_mod_ctrl; static void append_mod_list(mws_sp<mws_mod_list> i_mod_list); static mws_sp<mws_mod_list> get_mod_list(); static void add_mod(mws_sp<mws_mod> i_mod, const mws_path& i_mod_path, bool i_set_current = false); static inline mws_wp<mws_mod_list> ul; static inline mws_wp<mws_mod> next_crt_mod; };
29.193548
150
0.736878
[ "vector" ]
38f0a6de8025443014453776b5de85822c00f8d8
16,042
hxx
C++
include/opengm/inference/auxiliary/lp_reparametrization.hxx
yanlend/opengm
910cba0323ddafd1f1b8bb5d4483d77dba234efd
[ "MIT" ]
null
null
null
include/opengm/inference/auxiliary/lp_reparametrization.hxx
yanlend/opengm
910cba0323ddafd1f1b8bb5d4483d77dba234efd
[ "MIT" ]
null
null
null
include/opengm/inference/auxiliary/lp_reparametrization.hxx
yanlend/opengm
910cba0323ddafd1f1b8bb5d4483d77dba234efd
[ "MIT" ]
null
null
null
/* * lp_reparametrization_storage.hxx * * Created on: Sep 16, 2013 * Author: bsavchyn */ #ifndef LP_REPARAMETRIZATION_STORAGE_HXX_ #define LP_REPARAMETRIZATION_STORAGE_HXX_ #include <opengm/inference/trws/utilities2.hxx> #include <opengm/graphicalmodel/graphicalmodel_factor_accumulator.hxx> #ifdef WITH_HDF5 #include <opengm/graphicalmodel/graphicalmodel_hdf5.hxx> #endif namespace opengm{ #ifdef TRWS_DEBUG_OUTPUT using OUT::operator <<; #endif template<class GM> class LPReparametrisationStorage{ public: typedef GM GraphicalModelType; typedef typename GM::ValueType ValueType; typedef typename GM::FactorType FactorType; typedef typename GM::IndexType IndexType; typedef typename GM::LabelType LabelType; //typedef std::valarray<ValueType> UnaryFactor; typedef std::vector<ValueType> UnaryFactor; typedef ValueType* uIterator; typedef std::vector<UnaryFactor> VecUnaryFactors; typedef std::map<IndexType,IndexType> VarIdMapType; LPReparametrisationStorage(const GM& gm); const UnaryFactor& get(IndexType factorIndex,IndexType relativeVarIndex)const//const access { OPENGM_ASSERT(factorIndex < _gm.numberOfFactors()); OPENGM_ASSERT(relativeVarIndex < _dualVariables[factorIndex].size()); return _dualVariables[factorIndex][relativeVarIndex]; } std::pair<uIterator,uIterator> getIterators(IndexType factorIndex,IndexType relativeVarIndex) { OPENGM_ASSERT(factorIndex < _gm.numberOfFactors()); OPENGM_ASSERT(relativeVarIndex < _dualVariables[factorIndex].size()); UnaryFactor& uf=_dualVariables[factorIndex][relativeVarIndex]; uIterator begin=&uf[0]; return std::make_pair(begin,begin+uf.size()); } template<class ITERATOR> ValueType getFactorValue(IndexType findex,ITERATOR it)const { OPENGM_ASSERT(findex < _gm.numberOfFactors()); const typename GM::FactorType& factor=_gm[findex]; ValueType res=0;//factor(it); if (factor.numberOfVariables()>1) { res=factor(it); for (IndexType varId=0;varId<factor.numberOfVariables();++varId) { OPENGM_ASSERT(varId < _dualVariables[findex].size()); OPENGM_ASSERT(*(it+varId) < _dualVariables[findex][varId].size()); res+=_dualVariables[findex][varId][*(it+varId)]; } }else { res=getVariableValue(factor.variableIndex(0),*it); } return res; } ValueType getVariableValue(IndexType varIndex,LabelType label)const { OPENGM_ASSERT(varIndex < _gm.numberOfVariables()); ValueType res=0.0; for (IndexType i=0;i<_gm.numberOfFactors(varIndex);++i) { IndexType factorId=_gm.factorOfVariable(varIndex,i); OPENGM_ASSERT(factorId < _gm.numberOfFactors()); if (_gm[factorId].numberOfVariables()==1) { res+=_gm[factorId](&label); continue; } OPENGM_ASSERT( factorId < _dualVariables.size() ); OPENGM_ASSERT(label < _dualVariables[factorId][localId(factorId,varIndex)].size()); res-=_dualVariables[factorId][localId(factorId,varIndex)][label]; } return res; } #ifdef TRWS_DEBUG_OUTPUT void PrintTestData(std::ostream& fout)const; #endif IndexType localId(IndexType factorId,IndexType varIndex)const{ typename VarIdMapType::const_iterator it = _localIdMap[factorId].find(varIndex); trws_base::exception_check(it!=_localIdMap[factorId].end(),"LPReparametrisationStorage:localId() - factor and variable are not connected!"); return it->second;}; template<class VECTOR> void serialize(VECTOR* pserialization)const; template<class VECTOR> void deserialize(const VECTOR& serialization); private: LPReparametrisationStorage(const LPReparametrisationStorage&);//TODO: carefully implement, when needed LPReparametrisationStorage& operator=(const LPReparametrisationStorage&);//TODO: carefully implement, when needed const GM& _gm; std::vector<VecUnaryFactors> _dualVariables; std::vector<VarIdMapType> _localIdMap; }; template<class GM> LPReparametrisationStorage<GM>::LPReparametrisationStorage(const GM& gm) :_gm(gm),_localIdMap(gm.numberOfFactors()) { _dualVariables.resize(_gm.numberOfFactors()); //for all factors with order > 1 for (IndexType findex=0;findex<_gm.numberOfFactors();++findex) { IndexType numVars=_gm[findex].numberOfVariables(); VarIdMapType& mapFindex=_localIdMap[findex]; if (numVars>=2) { _dualVariables[findex].resize(numVars); //std::valarray<IndexType> v(numVars); std::vector<IndexType> v(numVars); _gm[findex].variableIndices(&v[0]); for (IndexType n=0;n<numVars;++n) { //_dualVariables[findex][n].assign(_gm.numberOfLabels(v[n]),0.0);//TODO. Do it like this _dualVariables[findex][n].resize(_gm.numberOfLabels(v[n])); mapFindex[v[n]]=n; } } } } #ifdef TRWS_DEBUG_OUTPUT template<class GM> void LPReparametrisationStorage<GM>::PrintTestData(std::ostream& fout)const { fout << "_dualVariables.size()=" << _dualVariables.size()<<std::endl; for (IndexType factorIndex=0;factorIndex<_dualVariables.size();++factorIndex ) { fout <<"factorIndex="<<factorIndex<<": ---------------------------------"<<std::endl; for (IndexType varId=0;varId<_dualVariables[factorIndex].size();++varId) fout <<"varId="<<varId<<": "<< _dualVariables[factorIndex][varId]<<std::endl; } } #endif template<class GM> template<class VECTOR> void LPReparametrisationStorage<GM>::serialize(VECTOR* pserialization)const { //computing total space needed: size_t i=0; for (IndexType factorId=0;factorId<_dualVariables.size();++factorId) for (IndexType localId=0;localId<_dualVariables[factorId].size();++localId) for (LabelType label=0;label<_dualVariables[factorId][localId].size();++label) ++i; pserialization->resize(i); //serializing.... i=0; for (IndexType factorId=0;factorId<_dualVariables.size();++factorId) for (IndexType localId=0;localId<_dualVariables[factorId].size();++localId) for (LabelType label=0;label<_dualVariables[factorId][localId].size();++label) (*pserialization)[i++]=_dualVariables[factorId][localId][label]; } template<class GM> template<class VECTOR> void LPReparametrisationStorage<GM>::deserialize(const VECTOR& serialization) { size_t i=0; for (IndexType factorId=0;factorId<_gm.numberOfFactors();++factorId) { OPENGM_ASSERT(factorId<_dualVariables.size()); if (_gm[factorId].numberOfVariables()==1) continue; for (IndexType localId=0;localId<_gm[factorId].numberOfVariables();++localId) { OPENGM_ASSERT(localId<_dualVariables[factorId].size()); for (LabelType label=0;label<_dualVariables[factorId][localId].size();++label) { OPENGM_ASSERT(label<_dualVariables[factorId][localId].size()); if (i>=serialization.size()) throw std::runtime_error("LPReparametrisationStorage<GM>::deserialize(): Size of serialization is less than required for the graphical model! Deserialization failed."); _dualVariables[factorId][localId][label]=serialization[i++]; } } } if (i!=serialization.size()) throw std::runtime_error("LPReparametrisationStorage<GM>::deserialize(): Size of serialization is greater than required for the graphical model! Deserialization failed."); } #ifdef WITH_HDF5 template<class GM> void save(const LPReparametrisationStorage<GM>& repa,const std::string& filename,const std::string& modelname) { hid_t file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); OPENGM_ASSERT(file >= 0); marray::Vector<typename GM::ValueType> marr; repa.serialize(&marr); marray::hdf5::save(file,modelname.c_str(),marr); H5Fclose(file); } template<class GM> void load(LPReparametrisationStorage<GM>* prepa, const std::string& filename, const std::string& modelname) { hid_t file = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); OPENGM_ASSERT(file>=0); marray::Vector<typename GM::ValueType> marr; marray::hdf5::load(file,modelname.c_str(),marr); prepa->deserialize(marr); H5Fclose(file); }; #endif template<class GM, class REPASTORAGE> class ReparametrizationView : public opengm::FunctionBase<ReparametrizationView<GM,REPASTORAGE>, typename GM::ValueType,typename GM::IndexType, typename GM::LabelType> { public: typedef typename GM::ValueType ValueType; typedef ValueType value_type; typedef typename GM::FactorType FactorType; typedef typename GM::OperatorType OperatorType; typedef typename GM::IndexType IndexType; typedef typename GM::LabelType LabelType; typedef GM GraphicalModelType; typedef REPASTORAGE ReparametrizationStorageType; ReparametrizationView(const FactorType & factor,const REPASTORAGE& repaStorage,IndexType factorId) :_pfactor(&factor),_prepaStorage(&repaStorage),_factorId(factorId) {}; template<class Iterator> ValueType operator()(Iterator begin)const { switch (_pfactor->numberOfVariables()) { case 1: return _prepaStorage->getVariableValue(_pfactor->variableIndex(0),*begin); default: return _prepaStorage->getFactorValue(_factorId,begin); }; } LabelType shape(const IndexType& index)const{return _pfactor->numberOfLabels(index);}; IndexType dimension()const{return _pfactor->numberOfVariables();}; IndexType size()const{return _pfactor->size();}; private: const FactorType* _pfactor; const REPASTORAGE* _prepaStorage; IndexType _factorId; }; struct LPReparametrizer_Parameter { LPReparametrizer_Parameter(){}; }; template<class GM, class ACC> class LPReparametrizer { public: typedef GM GraphicalModelType; typedef typename GraphicalModelType::ValueType ValueType; typedef typename GraphicalModelType::IndexType IndexType; typedef typename GraphicalModelType::LabelType LabelType; typedef typename std::vector<bool> MaskType; typedef LPReparametrisationStorage<GM> RepaStorageType; typedef opengm::GraphicalModel<ValueType,opengm::Adder,opengm::ReparametrizationView<GM,RepaStorageType>, opengm::DiscreteSpace<IndexType,LabelType> > ReparametrizedGMType; typedef LPReparametrizer_Parameter Parameter; LPReparametrizer(const GM& gm):_gm(gm),_repastorage(_gm){}; virtual ~LPReparametrizer(){}; RepaStorageType& Reparametrization(){return _repastorage;}; //TODO: To implement virtual void getArcConsistency(std::vector<bool>* pmask,std::vector<LabelType>* plabeling,IndexType modelorder=2); virtual void reparametrize(const MaskType* pmask=0){}; virtual void getReparametrizedModel(ReparametrizedGMType& gm)const; const GM& graphicalModel()const{return _gm;} private: const GM& _gm; RepaStorageType _repastorage; }; template<class GM, class ACC> void LPReparametrizer<GM,ACC>::getReparametrizedModel(ReparametrizedGMType& gm)const { gm=ReparametrizedGMType(_gm.space()); //copying factors for (typename GM::IndexType factorID=0;factorID<_gm.numberOfFactors();++factorID) { const typename GM::FactorType& f=_gm[factorID]; opengm::ReparametrizationView<GM,RepaStorageType> repaView(f,_repastorage,factorID); typename ReparametrizedGMType::FunctionIdentifier fId=gm.addFunction(repaView); gm.addFactor(fId,f.variableIndicesBegin(), f.variableIndicesEnd()); } } template<class GM, class ACC> void LPReparametrizer<GM,ACC>::getArcConsistency(std::vector<bool>* pmask,std::vector<LabelType>* plabeling,IndexType modelorder) { pmask->assign(_gm.numberOfVariables(),true); ReparametrizedGMType repagm; getReparametrizedModel(repagm); /** for (all factors) compute optimal values and labels (label sequences) create the list of unary factors; find optimal label for each variable **/ std::vector<ValueType> optimalValues(repagm.numberOfFactors()); std::vector< std::vector<LabelType> > optimalLabelings(repagm.numberOfFactors(),std::vector<LabelType>(modelorder)); //std::vector<LabelType> locallyOptimalLabels(repagm.numberOfVariables(),0);//in case there is no corresponding unary factor 0 is always one of optimal labels (all labels are optimal) std::vector<LabelType>& locallyOptimalLabels=*plabeling; locallyOptimalLabels.assign(repagm.numberOfVariables(),0);//in case there is no corresponding unary factor 0 is always one of optimal labels (all labels are optimal) std::vector<IndexType> unaryFactors; unaryFactors.reserve(repagm.numberOfFactors()); std::vector<ValueType> worstValue(repagm.numberOfFactors(),0); // std::cout << "First cycle:" <<std::endl; for (IndexType factorId=0;factorId<repagm.numberOfFactors();++factorId) { const typename ReparametrizedGMType::FactorType& factor=repagm[factorId]; optimalLabelings[factorId].resize(factor.numberOfVariables()); //accumulate.template<ACC>(factor,optimalValues[factorId],optimalLabelings[factorId]); accumulate<ACC,typename ReparametrizedGMType::FactorType,ValueType,LabelType>(factor,optimalValues[factorId],optimalLabelings[factorId]); // std::cout << "factorId=" << factorId<< ", optimalValues=" << optimalValues[factorId] << ", optimalLabelings=" << optimalLabelings[factorId] <<std::endl; if (factor.numberOfVariables() == 1) { unaryFactors.push_back(factorId); locallyOptimalLabels[factor.variableIndex(0)]=optimalLabelings[factorId][0]; // std::cout << "locallyOptimalLabels[" << factor.variableIndex(0)<<"]=" << locallyOptimalLabels[factor.variableIndex(0)] << std::endl; }else { if (ACC::bop(0,1)) worstValue[factorId]=factor.max(); else worstValue[factorId]=factor.min(); } } /* //385=200+9*19+7*2 ValueType magicNum=200+9*19+7*2; //std::cout << "97,98? : "<<repagm[magicNum].variableIndex(0)<<","<<repagm[magicNum].variableIndex(1) <<std::endl; std::vector<ValueType> lab(2); lab[0]=locallyOptimalLabels[97]; lab[1]=locallyOptimalLabels[98]; std::vector<ValueType> lab1(2,1); size_t t0=0,t1=1; std::cout << "385: max="<<worstValue[magicNum]<< ", optimalVal="<<optimalValues[magicNum] <<", optLabel[97]="<<locallyOptimalLabels[97]<<", optLabel[98]="<<locallyOptimalLabels[98] <<", optimalLabeling="<<optimalLabelings[magicNum] <<", labeling[97,98]="<<repagm[magicNum](lab.begin()) <<", labeling[97,98](1,1)="<< repagm[magicNum](lab1.begin()) <<", val[97]="<<repagm[97](&t0)<<","<<repagm[97](&t1) <<", val[98]="<<repagm[98](&t0)<<","<<repagm[98](&t1) << std::endl; */ /** for (unary factors and the optimal label) { for (each NON-nary factor) if NOT (locally optimal labels form an eps-optimal factor value or the optimal label produces THE (very) optimal factor value) mark the node as NON-consistent } **/ // std::cout << "Second cycle:" <<std::endl; for (IndexType i=0;i<unaryFactors.size();++i) { IndexType var= repagm[unaryFactors[i]].variableIndex(0); IndexType numOfFactors=repagm.numberOfFactors(var); for (IndexType f=0;f<numOfFactors;++f) { IndexType factorId=repagm.factorOfVariable(var,f); const typename ReparametrizedGMType::FactorType& factor=repagm[factorId]; // std::cout << "factorId=" <<factorId <<", optimalValues="<< optimalValues[factorId]<< std::endl; if (factor.numberOfVariables() <= 1) continue;//!> only higher order factors are considered IndexType localVarIndex= std::find(factor.variableIndicesBegin(),factor.variableIndicesEnd(),var) -factor.variableIndicesBegin();//!>find the place of the variable OPENGM_ASSERT(localVarIndex != (factor.variableIndicesEnd()-factor.variableIndicesBegin())); if (optimalLabelings[factorId][localVarIndex]==locallyOptimalLabels[var]) continue; //!>if the label belongs to the optimal configuration of the factor std::vector<LabelType> labeling(optimalLabelings[factorId].size()); //labeling[localVarIndex]=locallyOptimalLabels[var]; for (IndexType v=0;v<factor.numberOfVariables();++v) labeling[v]=locallyOptimalLabels[factor.variableIndex(v)]; // std::cout <<"worstValue="<<worstValue[factorId] << ", localVarIndex=" <<localVarIndex <<", labeling="<< labeling<<std::endl; if (fabs(factor(labeling.begin())-optimalValues[factorId]) <factor.numberOfVariables()*fabs(worstValue[factorId])*std::numeric_limits<ValueType>::epsilon()) continue;//!> if it is connected to other optimal labels with eps-optimal hyperedge /** else **/ // std::cout << "False:("<<std::endl; (*pmask)[var]=false; break; } } } } #endif /* LP_REPARAMETRIZATION_STORAGE_HXX_ */
36.459091
185
0.746977
[ "shape", "vector", "model" ]
f19b889732a256a354d9eeb36552aeabe0484d9e
20,647
cpp
C++
DirectXHermano/DirectXHermano/ResourceManager.cpp
HeladodePistacho/DirectXEngine
9ace14a8b4c3734324d9871acdf8f3da77e2482c
[ "MIT" ]
null
null
null
DirectXHermano/DirectXHermano/ResourceManager.cpp
HeladodePistacho/DirectXEngine
9ace14a8b4c3734324d9871acdf8f3da77e2482c
[ "MIT" ]
null
null
null
DirectXHermano/DirectXHermano/ResourceManager.cpp
HeladodePistacho/DirectXEngine
9ace14a8b4c3734324d9871acdf8f3da77e2482c
[ "MIT" ]
null
null
null
#include <iostream> #include "ResourceManager.h" #include "Mesh.h" #include "VertexBuffer.h" #include "IndexBuffer.h" #include "Topology.h" #include "InputLayout.h" #include "ShaderProgram.h" #include "ImGui/imgui.h" #include "FileDrop.h" #include "Texture.h" #include "Sampler.h" #include "Material.h" #include "TextureResource.h" #include "Preset.h" //Assimp #pragma comment(lib, "Assimp/libx86/assimp.lib") #include "Assimp/include/scene.h" #include "Assimp/include/Importer.hpp" #include "Assimp/include/postprocess.h" #include "Assimp/include/mesh.h" //image load #define STB_IMAGE_IMPLEMENTATION #include "STB Image/stb_image.h" ResourceManager::~ResourceManager() { for (std::multimap<RESOURCE_TYPE, Resource*>::iterator iter = mapped_resources.begin(); iter != mapped_resources.end(); iter++) { delete iter->second; iter->second = nullptr; } mapped_resources.erase(mapped_resources.begin(), mapped_resources.end()); } void ResourceManager::Start(Render& ren) { //Current path GetCurrentDirectory(256, my_path); //Load Basic meshes LoadShaders(ren); LoadCube(ren); LoadPlane(ren); //Load Null Texture LoadNullTexture(ren); //Load Default material LoadDefaultMaterial(ren); //Load some Meshes std::string model = my_path; model += "/3DModels/Patrick/Patrick.obj"; actual_resource_path = model.c_str(); ImportMesh(actual_resource_path, ren); model = my_path; model += "/3DModels/PalmTree/PalmTree.obj"; actual_resource_path = model.c_str(); ImportMesh(actual_resource_path, ren); model = my_path; model += "/3DModels/sibenik/sibenik.obj"; actual_resource_path = model.c_str(); ImportMesh(actual_resource_path, ren); model = my_path; model += "/3DModels/Sphere/sphere.obj"; actual_resource_path = model.c_str(); ImportMesh(actual_resource_path, ren); sphere_mesh = (Mesh*)GetResourceByName("sphere.obj", RESOURCE_TYPE::MESH); //model = my_path; //model += "/3DModels/sponza_crytek/sponza.obj"; //actual_resource_path = model.c_str(); //ImportMesh(actual_resource_path, ren); } void ResourceManager::DrawMaterialEditorUI(Render& ren) { ImGui::Begin("Material Editor"); ImGui::Text("Material Editor: "); ImGui::InputTextWithHint(" ##material editor creator", "Insert Material Name", material_name_buffer, 128); if (ImGui::Button("Create Material")) { if (strlen(material_name_buffer) != 0) { Material* new_material = new Material(material_name_buffer); new_material->InitColorBuffer(ren); new_material->SetAlbedoTexture((TextureResource*)GetResourceByName("Null Texture", RESOURCE_TYPE::TEXTURE)); mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(MATERIAL, new_material)); material_to_modify = new_material; } } ImGui::Separator(); if (material_to_modify != nullptr) { ImGui::Text("Diffuse: "); ID3D11ShaderResourceView* albedo = material_to_modify->GetTexture(TEXTURE_TYPE::ALBEDO); if(albedo) ImGui::Image(albedo, ImVec2(50.0f, 50.0f)); ImGui::SameLine(); if (ImGui::BeginCombo(" ##difuse texture selector", "Select Texture", ImGuiComboFlags_::ImGuiComboFlags_None)) { const TextureResource* tmp = (TextureResource*)DrawResourceSelectableUI(TEXTURE); if (tmp != nullptr) material_to_modify->SetAlbedoTexture((TextureResource*)tmp); ImGui::EndCombo(); } ImGui::Text("Color:"); ImGui::SameLine(); ImGui::PushItemWidth(120.0f); if (ImGui::ColorPicker4(" ##difuse color", material_to_modify->GetColor(TEXTURE_TYPE::ALBEDO), ImGuiColorEditFlags_::ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_::ImGuiColorEditFlags_NoSidePreview)) material_to_modify->UpdateColor(TEXTURE_TYPE::ALBEDO, ren); ImGui::PopItemWidth(); ImGui::Separator(); ImGui::Text("Normals: "); ID3D11ShaderResourceView* normal = material_to_modify->GetTexture(TEXTURE_TYPE::NORMAL); if (normal) ImGui::Image(normal, ImVec2(50.0f, 50.0f)); ImGui::SameLine(); if (ImGui::BeginCombo(" ##normal texture selector", "Select Texture", ImGuiComboFlags_::ImGuiComboFlags_None)) { const TextureResource* tmp = (TextureResource*)DrawResourceSelectableUI(TEXTURE); if (tmp != nullptr) material_to_modify->SetNormalTexture((TextureResource*)tmp); ImGui::EndCombo(); } int specular_value = material_to_modify->GetSpecular(); if (ImGui::SliderInt("Specular", &specular_value, 2, 512)) { material_to_modify->SetSpecular(specular_value); } } ImGui::End(); } void ResourceManager::ImportResource(const File* file, Render & ren) { actual_resource_path = file->GetPath(); switch (file->GetType()) { case FILE_TYPE::FBX: case FILE_TYPE::OBJ: ImportMesh(actual_resource_path, ren); break; case FILE_TYPE::PNG: case FILE_TYPE::JPG: ImportTexture(actual_resource_path, ren); break; } } Material* ResourceManager::GetMaterialByName(std::string name) const { std::multimap<RESOURCE_TYPE, Resource*>::const_iterator lower, up; lower = mapped_resources.lower_bound(RESOURCE_TYPE::MATERIAL); up = mapped_resources.upper_bound(RESOURCE_TYPE::MATERIAL); for (; lower != up; lower++) { if (name == lower->second->GetName()) return (Material*)lower->second; } return nullptr; } void ResourceManager::SetMaterialToModify(Material * current_mat) { if (current_mat != nullptr) material_to_modify = current_mat; } void ResourceManager::ImportMesh(const char* path, Render& ren) { //new Mesh std::string name = path; Mesh* new_mesh = new Mesh(path); //Load Mesh from assimp Assimp::Importer importer; const aiScene* scene= importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FixInfacingNormals | aiProcess_JoinIdenticalVertices | aiProcess_PreTransformVertices | //aiProcess_RemoveRedundantMaterials | aiProcess_SortByPType | aiProcess_ImproveCacheLocality | aiProcess_FlipUVs | aiProcess_OptimizeMeshes); //Check for errors if (!scene || !scene->mRootNode || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) { const char* tmp = importer.GetErrorString(); std::cout << "ASSIMP ERROR: " << importer.GetErrorString() << std::endl; return; } //Load each node from scene nodes.push(scene->mRootNode); Preset* new_preset = new Preset(actual_resource_path); while (!nodes.empty()) { new_mesh->AddSubmesh(ProcessNode(scene, nodes.front(), ren)); new_preset->AddMaterialName(ProcessMaterials(scene, nodes.front(), ren)); for (int i = 0; i < nodes.front()->mNumChildren; i++) nodes.push(nodes.front()->mChildren[i]); nodes.pop(); } mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(PRESET, new_preset)); std::pair<RESOURCE_TYPE, Resource*> map_element = { RESOURCE_TYPE::MESH, new_mesh }; mapped_resources.insert(map_element); } void ResourceManager::LoadShaders(Render& ren) { mesh_shader = new ShaderProgram(ren, L"Shaders/VertexShader.cso", L"Shaders/PixelShader.cso"); screen_shader = new ShaderProgram(ren, L"Shaders/ScreenVertexShader.cso", L"Shaders/ScreenPixelShader.cso"); light_shader = new ShaderProgram(ren, L"Shaders/LightVertexShader.cso", L"Shaders/LightPixelShader.cso"); grid_shader = new ShaderProgram(ren, L"Shaders/ScreenVertexShader.cso", L"Shaders/GridPixelShader.cso"); light_mesh_shader = new ShaderProgram(ren, L"Shaders/PointLightVertexShader.cso", L"Shaders/PointLightPixelShader.cso"); } void ResourceManager::LoadCube(Render& ren) { //Cube Vertices std::vector<Vertex> vertices = { //Back { { -1.0f, -1.0f, -1.0f }, { 0.0f, 0.0f, -1.0f }, { 0.0f, 1.0f} }, { { -1.0f, 1.0f, -1.0f }, { 0.0f, 0.0f, -1.0f }, { 0.0f, 0.0f } }, { { 1.0f, 1.0f, -1.0f }, { 0.0f, 0.0f, -1.0f }, { 1.0f, 0.0f } }, { { 1.0f, -1.0f, -1.0f }, { 0.0f, 0.0f, -1.0f }, { 1.0f, 1.0f } }, //Front { { -1.0f, -1.0f, 1.0f }, {0.0f, 0.0f, 1.0f}, { 1.0f, 1.0f } }, { { -1.0f, 1.0f, 1.0f },{ 0.0f, 0.0f, 1.0f },{ 1.0f, 0.0f } }, { { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f },{ 0.0f, 0.0f } }, { { 1.0f, -1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f },{ 0.0f, 1.0f } }, //Right { { 1.0f, 1.0f, -1.0f },{ 1.0f, 0.0f, 0.0f },{ 0.0f, 0.0f } }, { { 1.0f, -1.0f, -1.0f },{ 1.0f, 0.0f, 0.0f },{ 0.0f, 1.0f } }, { { 1.0f, 1.0f, 1.0f },{ 1.0f, 0.0f, 0.0f },{ 1.0f, 0.0f } }, { { 1.0f, -1.0f, 1.0f },{ 1.0f, 0.0f, 0.0f },{ 1.0f, 1.0f } }, //Left { { -1.0f, -1.0f, -1.0f }, { -1.0f, 0.0f, 0.0f }, { 1.0f, 1.0f } }, { { -1.0f, 1.0f, -1.0f }, { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f } }, { { -1.0f, -1.0f, 1.0f }, { -1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f } }, { { -1.0f, 1.0f, 1.0f }, { -1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f } }, //Up { { -1.0f, 1.0f, -1.0f }, { 0.0f, 1.0f, 0.0f }, { 1.0f, 0.0f } }, { { 1.0f, 1.0f, -1.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f } }, { { -1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f } }, { { 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 1.0f } }, //Down { { -1.0f, -1.0f, -1.0f }, { 0.0f, -1.0f, 0.0f }, { 1.0f, 1.0f } }, { { 1.0f, -1.0f, -1.0f }, { 0.0f, -1.0f, 0.0f }, { 0.0f, 1.0f } }, { { -1.0f, -1.0f, 1.0f }, { 0.0f, -1.0f, 0.0f }, { 1.0f, 0.0f } }, { { 1.0f, -1.0f, 1.0f }, { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f } }, }; //Cube Index Buffer std::vector<unsigned short> indices = { //Back 0, 1, 2, 0, 2, 3, //Front 7, 6, 5, 7, 5, 4, //Right 9, 8, 10, 9, 10, 11, //Left 14, 15, 13, 14, 13, 12, //Up 16, 18, 19, 16, 19, 17, //Down 20, 21, 23, 20, 23, 22 }; std::vector<D3D11_INPUT_ELEMENT_DESC> layout = { { "Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "Normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 3, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TextureCoords", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float) * 6, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; VertexBuffer* new_vertexbuffer = new VertexBuffer(ren, vertices); IndexBuffer* new_indexbuffer = new IndexBuffer(ren, indices); Topology* new_topology = new Topology(D3D11_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); InputLayout* new_inputlayout = new InputLayout(ren, layout, mesh_shader->GetVertexByteCode()); Submesh* new_submesh = new Submesh(); new_submesh->AddBind(new_vertexbuffer); new_submesh->AddBind(new_topology); new_submesh->AddBind(new_inputlayout); new_submesh->AddIndices(new_indexbuffer); new_submesh->AddInfo(vertices.size(), indices.size()); //CubeMesh Mesh* new_mesh = new Mesh((std::string)"/Cube Mesh"); new_mesh->AddSubmesh(new_submesh); std::pair<RESOURCE_TYPE, Resource*> map_element_mesh = { RESOURCE_TYPE::MESH, new_mesh }; mapped_resources.insert(map_element_mesh); //Cube Mesh Only For Lights drawing std::vector<D3D11_INPUT_ELEMENT_DESC> light_layout = { { "Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; Submesh* light_submesh = new Submesh(); light_submesh->AddBind(new_vertexbuffer); light_submesh->AddBind(new_topology); light_submesh->AddBind(new_inputlayout); light_submesh->AddIndices(new_indexbuffer); light_submesh->AddInfo(vertices.size(), indices.size()); light_mesh = new Mesh((std::string)"/Light Mesh"); light_mesh->AddSubmesh(light_submesh); } void ResourceManager::LoadNullTexture(Render& ren) { TextureResource* null_texture = new TextureResource("/No Texture"); Texture* null_text = new Texture(ren, nullptr, 0, 0, 0); null_texture->AddTexture(null_text); mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(TEXTURE, null_texture)); } void ResourceManager::LoadPlane(Render & ren) { std::vector<Vertex> plane_vertexs = { { { -1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 1.0f } }, { { -1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 1.0f, 0.0f } }, { { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f } }, { { 1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { 0.0f, 1.0f } }, }; std::vector<unsigned short> indices = { 3, 2, 1, 3, 1, 0 }; std::vector<D3D11_INPUT_ELEMENT_DESC> layout = { { "Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "Normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 3, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TextureCoords", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float) * 6, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; VertexBuffer* new_vertexbuffer = new VertexBuffer(ren, plane_vertexs); IndexBuffer* new_indexbuffer = new IndexBuffer(ren, indices); Topology* new_topology = new Topology(D3D11_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); InputLayout* new_inputlayout = new InputLayout(ren, layout, screen_shader->GetVertexByteCode()); Submesh* new_submesh = new Submesh(); new_submesh->AddBind(new_vertexbuffer); new_submesh->AddBind(new_topology); new_submesh->AddBind(new_inputlayout); new_submesh->AddIndices(new_indexbuffer); new_submesh->AddInfo(plane_vertexs.size(), indices.size()); //std::string name = "Cube Mesh"; Mesh* new_mesh = new Mesh((std::string)"/Plane Mesh"); new_mesh->AddSubmesh(new_submesh); screen_mesh = new_mesh; mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(RESOURCE_TYPE::MESH, new_mesh)); } void ResourceManager::LoadDefaultMaterial(Render & ren) { Material* default_material = new Material("/Default"); default_material->InitColorBuffer(ren); default_material->SetAlbedoTexture((TextureResource*)GetResourceByName("No Texture", RESOURCE_TYPE::TEXTURE)); mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(MATERIAL, default_material)); } std::vector<Submesh*> ResourceManager::ProcessNode(const aiScene* scene, aiNode* node, Render& ren) { std::vector<Submesh*> ret; for (int i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; ret.push_back(ProcessMesh(scene, mesh, ren)); } return ret; } Submesh* ResourceManager::ProcessMesh(const aiScene * scene, aiMesh * mesh, Render& ren) { Submesh* new_submesh = new Submesh(); std::vector<Vertex> vertices; bool has_text_coords = false; for (int i = 0; i < mesh->mNumVertices; i++) { //Vertex position / Normals / Tex Coords Vertex new_vertex; new_vertex.position = { mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z }; new_vertex.normal = { mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z }; if (mesh->mTextureCoords[0]) { has_text_coords = true; new_vertex.texture_coords = { mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y }; } vertices.push_back(new_vertex); } std::vector<unsigned short> indices; for (int i = 0; i < mesh->mNumFaces; i++) { aiFace poligon_face = mesh->mFaces[i]; for (int k = 0; k < poligon_face.mNumIndices; k++) indices.push_back(poligon_face.mIndices[k]); } std::cout << indices.size() << std::endl; std::vector<D3D11_INPUT_ELEMENT_DESC> layout = { { "Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "Normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 3, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (has_text_coords) layout.push_back({ "TextureCoords", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float) * 6, D3D11_INPUT_PER_VERTEX_DATA, 0 }); VertexBuffer* new_vertexbuffer = new VertexBuffer(ren, vertices); IndexBuffer* new_indexbuffer = new IndexBuffer(ren, indices); Topology* new_topology = new Topology(D3D11_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); InputLayout* new_inputlayout = new InputLayout(ren, layout, mesh_shader->GetVertexByteCode()); new_submesh->AddBind(new_vertexbuffer); new_submesh->AddIndices(new_indexbuffer); new_submesh->AddBind(new_topology); new_submesh->AddBind(new_inputlayout); new_submesh->AddInfo(vertices.size(), indices.size()); return new_submesh; } void ResourceManager::ImportTexture(const char * path, Render & ren) { //Check if the Texture is already loaded TextureResource* new_texture = (TextureResource*)GetResourceByPath(actual_resource_path, TEXTURE); if (new_texture != nullptr) return; //Check if there is problems with the importation Texture* tmp = ImportImage(nullptr, ren); if (tmp != nullptr) { //Create Texture new_texture = new TextureResource(actual_resource_path); Sampler* new_sampler = new Sampler(ren); new_texture->AddTexture(tmp); new_texture->AddSampler(new_sampler); if (new_texture != nullptr) mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(TEXTURE, new_texture)); } } Texture* ResourceManager::ImportImage(const char * path, Render & ren) { //IMAGE load std::string full_texture_path = actual_resource_path; if (path != nullptr) { if (full_texture_path.find_last_of('/') != -1) full_texture_path.erase(full_texture_path.find_last_of('/') + 1); else full_texture_path.erase(full_texture_path.find_last_of('\\') + 1); full_texture_path.append(path); } int width, height, color_channels; unsigned char* data = stbi_load(full_texture_path.c_str(), &width, &height, &color_channels, 4); if (data != nullptr) { Texture* texture = new Texture(ren, data, width, height, color_channels); return texture; } return nullptr; } const char* ResourceManager::ProcessMaterials(const aiScene * scene, aiNode * node, Render & ren) { for (int i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; //Load Materials if (scene->HasMaterials()) { aiMaterial* mesh_material = scene->mMaterials[mesh->mMaterialIndex]; //Create Material aiString material_name; aiGetMaterialString(mesh_material, AI_MATKEY_NAME, &material_name); Material* new_material = new Material(material_name.C_Str()); new_material->InitColorBuffer(ren); //Look For Difuse Texture aiString texture_path; if (aiGetMaterialTexture(mesh_material, aiTextureType_DIFFUSE, 0, &texture_path) == aiReturn_SUCCESS) { //Check if the texture is already loaded TextureResource* new_texture = (TextureResource*)GetResourceByName(texture_path.C_Str(), TEXTURE); if (new_texture == nullptr) { //Load the Texture new_texture = new TextureResource(texture_path.C_Str()); new_texture->AddTexture(ImportImage(texture_path.C_Str(), ren)); new_texture->AddSampler(new Sampler(ren)); //Add the texture to resources mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(TEXTURE, new_texture)); } //Add the albedo to the Material new_material->SetAlbedoTexture(new_texture); } //Look For Normal Texture if (aiGetMaterialTexture(mesh_material, aiTextureType_NORMALS, 0, &texture_path) == aiReturn_SUCCESS) { //Check if the texture is already loaded TextureResource* new_texture = (TextureResource*)GetResourceByName(texture_path.C_Str(), TEXTURE); if (new_texture == nullptr) { //Load the Texture new_texture = new TextureResource(texture_path.C_Str()); new_texture->AddTexture(ImportImage(texture_path.C_Str(), ren)); new_texture->AddSampler(new Sampler(ren)); //Add the texture to resources mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(TEXTURE, new_texture)); } //Add the normal to the material new_material->SetNormalTexture(new_texture); } //Look for Difuse Color aiColor4D difuse_color; if (aiGetMaterialColor(mesh_material, AI_MATKEY_COLOR_DIFFUSE, &difuse_color) == aiReturn_SUCCESS) { new_material->SetAlbedoColor(ren, difuse_color.r, difuse_color.g, difuse_color.b, difuse_color.a); } //Add Material and Preset to the Resources map mapped_resources.insert(std::pair<RESOURCE_TYPE, Resource*>(MATERIAL, new_material)); return new_material->GetName(); } } } Resource* ResourceManager::GetResourceByPath(const char * full_path, RESOURCE_TYPE type) { std::multimap<RESOURCE_TYPE, Resource*>::const_iterator lower, up; lower = mapped_resources.lower_bound(type); up = mapped_resources.upper_bound(type); for (; lower != up; lower++) { if (lower->second->GetPath() == full_path) return lower->second; } return nullptr; } Resource* ResourceManager::GetResourceByName(const char * name, RESOURCE_TYPE type) { std::multimap<RESOURCE_TYPE, Resource*>::const_iterator lower, up; lower = mapped_resources.lower_bound(type); up = mapped_resources.upper_bound(type); for (; lower != up; lower++) { if (strcmp(lower->second->GetName(), name) == 0) return lower->second; } return nullptr; } Resource* ResourceManager::DrawResourceSelectableUI(RESOURCE_TYPE type) { std::multimap<RESOURCE_TYPE, Resource*>::const_iterator lower, up; lower = mapped_resources.lower_bound(type); up = mapped_resources.upper_bound(type); for (; lower != up; lower++) { if (ImGui::Selectable(lower->second->GetName())) return lower->second; } return nullptr; }
31.188822
202
0.698794
[ "mesh", "render", "vector", "model" ]
f19fb0fc570310b60a61f19d0ea92d9f9a89cb07
1,780
cpp
C++
search_and_graph/topo_sort/demo/leetcode1857.cpp
Fanjunmin/algorithm-template
db0d37a7c9c37ee9a167918fb74b03d1d09b6fad
[ "MIT" ]
1
2021-04-26T11:03:04.000Z
2021-04-26T11:03:04.000Z
search_and_graph/topo_sort/demo/leetcode1857.cpp
Fanjunmin/algrithm-template
db0d37a7c9c37ee9a167918fb74b03d1d09b6fad
[ "MIT" ]
null
null
null
search_and_graph/topo_sort/demo/leetcode1857.cpp
Fanjunmin/algrithm-template
db0d37a7c9c37ee9a167918fb74b03d1d09b6fad
[ "MIT" ]
null
null
null
class Solution { private: const static int N = 1e5 + 10, M = 1e5 + 10; int h[N], d[N]; int e[M], ne[M], idx; int topo[N]; int n; int q[N], head, tail; int f[N][26]; //f[i][k]表示以节点i尾节点的路径中颜色为k的节点的个数 int max_color; void init() { memset(h, -1, sizeof(h)); memset(d, 0, sizeof(d)); memset(f, 0, sizeof(f)); idx = 0; max_color = 1; } void add(int a, int b) { idx++; e[idx] = b; ne[idx] = h[a]; h[a] = idx; } bool topo_sort(const string &colors) { int cnt = 0; head = 0; tail = -1; for (int i = 0; i < n; ++i) { if (d[i] == 0) { q[++tail] = i; f[i][colors[i] - 'a'] = 1; } } while (head <= tail) { int t = q[head++]; topo[cnt++] = t; for (int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; if (d[j] > 0) { --d[j]; for (int k = 0; k < 26; ++k) { if (k == colors[j] - 'a') f[j][k] = max(f[j][k], f[t][k] + 1); else f[j][k] = max(f[j][k], f[t][k]); max_color = max(f[j][k], max_color); } } if (d[j] == 0) q[++tail] = j; } } return cnt == n; // 拓扑排序判断是否存在环 } public: int largestPathValue(string colors, vector<vector<int>>& edges) { init(); for (auto edge : edges) { if (edge[0] == edge[1]) return -1; add(edge[0], edge[1]); d[edge[1]]++; } n = colors.size(); if (!topo_sort(colors)) return -1; return max_color; } };
28.709677
86
0.363483
[ "vector" ]
f1a225029501c4c5a924065877859538e5cca163
1,477
cpp
C++
src/cpp-leetcode/third/Code_144_PreorderOfBT.cpp
17hao/algorithm
0e96883a4638b33182bd590fffd12fd6ba0783c8
[ "Apache-2.0" ]
null
null
null
src/cpp-leetcode/third/Code_144_PreorderOfBT.cpp
17hao/algorithm
0e96883a4638b33182bd590fffd12fd6ba0783c8
[ "Apache-2.0" ]
1
2019-03-25T15:17:54.000Z
2019-03-25T15:20:30.000Z
src/cpp-leetcode/third/Code_144_PreorderOfBT.cpp
17hao/algorithm
0e96883a4638b33182bd590fffd12fd6ba0783c8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <stack> #include <vector> #include "../Tree.h" /** * preorder traversal of binary tree * * @since 2020-12-17 Thursday 22:50 */ class Solution { void recursiveHelper(TreeNode* root, std::vector<int>& res) { if (root == nullptr) { return; } res.push_back(root->val); recursiveHelper(root->left, res); recursiveHelper(root->right, res); } public: std::vector<int> preorderTraversalRecursively(TreeNode* root) { std::vector<int> v; recursiveHelper(root, v); return v; } std::vector<int> preorderTraversalIteratively(TreeNode* root) { std::vector<int> res; if (root != nullptr) { std::stack<TreeNode*> stack; stack.push(root); while (!stack.empty()) { TreeNode* cur = stack.top(); stack.pop(); res.push_back(cur->val); if (cur->right != nullptr) { stack.push(cur->right); } if (cur->left != nullptr) { stack.push(cur->left); } } } return res; } }; int main(int argc, const char* argv[]) { TreeNode* root = Tree::binarySearchTree(); Solution s; std::vector<int> res1 = s.preorderTraversalRecursively(root); std::vector<int> res2 = s.preorderTraversalIteratively(root); std::cout << "recursive res: "; for(int i : res1) { std::cout << i << " "; } std::cout << "\n===\n"; std::cout << "iterative res: "; for (int i : res2) { std::cout << i << " "; } }
23.078125
67
0.578199
[ "vector" ]
f1aacc87614a3a7aceb2831303a2d863d67746b3
14,419
cpp
C++
Rules/PossibleForwardDeclarationRule.cpp
colobot/colobot-lint
30921edb55b49dbda27d645357e24d6d22f5c48f
[ "BSD-3-Clause" ]
7
2015-08-28T14:26:51.000Z
2020-05-18T01:37:27.000Z
Rules/PossibleForwardDeclarationRule.cpp
piotrdz/colobot-lint
30921edb55b49dbda27d645357e24d6d22f5c48f
[ "BSD-3-Clause" ]
7
2015-07-31T20:54:10.000Z
2015-08-24T22:26:55.000Z
Rules/PossibleForwardDeclarationRule.cpp
piotrdz/colobot-lint
30921edb55b49dbda27d645357e24d6d22f5c48f
[ "BSD-3-Clause" ]
2
2015-09-09T15:11:28.000Z
2018-11-14T20:34:35.000Z
#include "Rules/PossibleForwardDeclarationRule.h" #include "Common/Context.h" #include "Common/OutputPrinter.h" #include "Common/SourceLocationHelper.h" #include "Common/TagTypeMatchers.h" #include "Common/TagTypeNameHelper.h" #include <clang/AST/Decl.h> #include <boost/format.hpp> #include <algorithm> #include <vector> using namespace llvm; using namespace clang; using namespace clang::ast_matchers; namespace { QualType RecursivelyDesugarType(const QualType& type) { QualType desugaredType = type; while (true) { const ElaboratedType* elaboratedType = desugaredType->getAs<ElaboratedType>(); if (elaboratedType != nullptr) { desugaredType = elaboratedType->desugar(); continue; } if (desugaredType->isArrayType()) { desugaredType = desugaredType->getAsArrayTypeUnsafe()->getElementType(); continue; } const PointerType* pointerType = desugaredType->getAs<PointerType>(); if (pointerType != nullptr) { desugaredType = pointerType->getPointeeType(); continue; } const ReferenceType* referenceType = desugaredType->getAs<ReferenceType>(); if (referenceType != nullptr) { desugaredType = referenceType->getPointeeType(); continue; } break; } return desugaredType; } QualType RecursivelyDesugarTypedefType(const QualType& type) { QualType desugaredType = type; bool haveTypedefType = false; while (true) { const TypedefType* typedefType = desugaredType->getAs<TypedefType>(); if (typedefType != nullptr) { desugaredType = typedefType->desugar(); haveTypedefType = true; continue; } const ElaboratedType* elaboratedType = desugaredType->getAs<ElaboratedType>(); if (elaboratedType != nullptr) { desugaredType = elaboratedType->desugar(); continue; } if (desugaredType->isArrayType()) { desugaredType = desugaredType->getAsArrayTypeUnsafe()->getElementType(); continue; } const PointerType* pointerType = desugaredType->getAs<PointerType>(); if (pointerType != nullptr) { desugaredType = pointerType->getPointeeType(); continue; } const ReferenceType* referenceType = desugaredType->getAs<ReferenceType>(); if (referenceType != nullptr) { desugaredType = referenceType->getPointeeType(); continue; } break; } if (!haveTypedefType) { return QualType(); } return desugaredType; } } // anonymous namespace namespace clang { namespace ast_matchers { AST_MATCHER_P(QualType, recursivelyDesugaredType, internal::Matcher<QualType>, InnerMatcher) { if (Node.isNull()) return false; QualType desugaredType = RecursivelyDesugarType(Node); return InnerMatcher.matches(desugaredType, Finder, Builder); } AST_MATCHER_P(QualType, recursivelyDesugaredTypedefType, internal::Matcher<QualType>, InnerMatcher) { if (Node.isNull()) return false; QualType desugaredType = RecursivelyDesugarTypedefType(Node); return InnerMatcher.matches(desugaredType, Finder, Builder); } AST_MATCHER_P(QualType, pointerOrReferenceTypeTo, internal::Matcher<QualType>, InnerMatcher) { if (Node.isNull()) return false; const PointerType* pointerType = Node->getAs<PointerType>(); if (pointerType != nullptr) { return InnerMatcher.matches(pointerType->getPointeeType(), Finder, Builder); } const ReferenceType* referenceType = Node->getAs<ReferenceType>(); if (referenceType != nullptr) { return InnerMatcher.matches(referenceType->getPointeeType(), Finder, Builder); } return false; } AST_MATCHER(TagDecl, isForwardDeclaration) { return Node.getDefinition() == nullptr; } AST_MATCHER(EnumDecl, isScopedUsingClassTag) { return Node.isScopedUsingClassTag(); } } // namespace ast_matchers } // namespace clang internal::Matcher<QualType> CreateActualTagTypeMatcher() { return qualType(hasDeclaration(tagDecl( unless(isExpansionInSystemHeader()), anyOf(classTemplateSpecializationDecl().bind("classTemplate"), enumDecl(unless(isScopedUsingClassTag())).bind("oldStyleEnum"), tagDecl(isForwardDeclaration()).bind("existingForwardDeclaration"), anything())) .bind("tagDecl"))); } internal::Matcher<QualType> CreateTemplateTagTypeMatcher() { return templateSpecializationType( hasAnyTemplateArgument( refersToType( recursivelyDesugaredType(CreateActualTagTypeMatcher())))); } internal::Matcher<QualType> CreateTagTypeMatcher() { return anyOf(qualType(recursivelyDesugaredTypedefType(CreateTemplateTagTypeMatcher())), qualType(recursivelyDesugaredTypedefType(CreateActualTagTypeMatcher())), qualType(recursivelyDesugaredType(CreateTemplateTagTypeMatcher())), qualType(pointerOrReferenceTypeTo(recursivelyDesugaredType(CreateActualTagTypeMatcher()))).bind("ptrOrRefType"), qualType(recursivelyDesugaredType(CreateActualTagTypeMatcher()))); } PossibleForwardDeclarationRule::PossibleForwardDeclarationRule(Context& context) : Rule(context) {} void PossibleForwardDeclarationRule::RegisterASTMatcherCallback(MatchFinder& finder) { finder.addMatcher(recordDecl().bind("recordDecl"), this); finder.addMatcher(declRefExpr().bind("declRefExpr"), this); finder.addMatcher( decl(anyOf(valueDecl(hasType(CreateTagTypeMatcher())), functionDecl(returns(CreateTagTypeMatcher())))).bind("declWithTagType"), this); finder.addMatcher(expr(hasType(CreateTagTypeMatcher())).bind("exprWithTagType"), this); } void PossibleForwardDeclarationRule::run(const MatchFinder::MatchResult& result) { m_sourceManager = result.SourceManager; const DeclRefExpr* declarationReferenceExpression = result.Nodes.getNodeAs<DeclRefExpr>("declRefExpr"); if (declarationReferenceExpression != nullptr) return HandleDeclarationReferenceExpression(declarationReferenceExpression); const CXXRecordDecl* recordDeclaration = result.Nodes.getNodeAs<CXXRecordDecl>("recordDecl"); if (recordDeclaration != nullptr) return HandleRecordDeclaration(recordDeclaration); const TagDecl* tagDeclaration = result.Nodes.getNodeAs<TagDecl>("tagDecl"); if (tagDeclaration == nullptr) return; if (IsInBlacklistedProjectHeader(tagDeclaration)) return; // already blacklisted, so no point of checking further if (! IsInDirectlyIncludedProjectHeader(tagDeclaration)) return; bool isExistingForwardDeclaration = result.Nodes.getNodeAs<Decl>("existingForwardDeclaration") != nullptr; if (isExistingForwardDeclaration) return; tagDeclaration = tagDeclaration->getCanonicalDecl(); bool isPointerOrReferenceType = result.Nodes.getNodeAs<QualType>("ptrOrRefType") != nullptr; bool isTemplateClassType = result.Nodes.getNodeAs<Decl>("classTemplate") != nullptr; bool isOldStyleEnum = result.Nodes.getNodeAs<Decl>("oldStyleEnum") != nullptr; const Decl* declarationWithTagType = result.Nodes.getNodeAs<Decl>("declWithTagType"); if (declarationWithTagType != nullptr) return HandleDeclarationWithTagType(tagDeclaration, declarationWithTagType, isPointerOrReferenceType, isTemplateClassType, isOldStyleEnum); const Expr* expressionWithTagType = result.Nodes.getNodeAs<Expr>("exprWithTagType"); if (expressionWithTagType != nullptr) return HandleExpressionWithTagType(tagDeclaration, expressionWithTagType); } bool PossibleForwardDeclarationRule::IsInBlacklistedProjectHeader(const Decl* declaration) { FileID tagDeclarationFileID = m_sourceManager->getFileID(declaration->getLocation()); return !tagDeclarationFileID.isInvalid() && m_blacklistedProjectHeaders.count(tagDeclarationFileID) > 0; } void PossibleForwardDeclarationRule::BlacklistIncludedProjectHeader(const Decl* declaration) { FileID tagDeclarationFileID = m_sourceManager->getFileID(declaration->getLocation()); m_blacklistedProjectHeaders.insert(tagDeclarationFileID); } bool PossibleForwardDeclarationRule::IsInDirectlyIncludedProjectHeader(const Decl* declaration) { SourceLocation tagDeclarationLocation = declaration->getLocation(); if (! m_context.sourceLocationHelper.IsLocationInProjectSourceFile(tagDeclarationLocation, *m_sourceManager)) return false; FileID tagDeclarationFileID = m_sourceManager->getFileID(declaration->getLocation()); if (tagDeclarationFileID.isInvalid()) return false; SourceLocation tagDeclarationIncludeLocation = m_sourceManager->getIncludeLoc(tagDeclarationFileID); if (tagDeclarationIncludeLocation.isInvalid()) return false; FileID tagDeclarationIncludeFileID = m_sourceManager->getFileID(tagDeclarationIncludeLocation); if (tagDeclarationIncludeFileID.isInvalid()) return false; FileID mainFileID = m_context.sourceLocationHelper.GetMainFileID(*m_sourceManager); if (mainFileID.isInvalid()) return false; // we want declaration from directly included project header (no indirect dependencies) return tagDeclarationFileID != mainFileID && tagDeclarationIncludeFileID == mainFileID; } void PossibleForwardDeclarationRule::HandleDeclarationReferenceExpression(const DeclRefExpr* declarationReferenceExpression) { SourceLocation location = declarationReferenceExpression->getLocation(); if (! m_context.sourceLocationHelper.IsLocationOfInterest(GetName(), location, *m_sourceManager)) return; const Decl* declaration = declarationReferenceExpression->getDecl(); if (IsInDirectlyIncludedProjectHeader(declaration)) { BlacklistIncludedProjectHeader(declaration); } } void PossibleForwardDeclarationRule::HandleRecordDeclaration(const CXXRecordDecl* recordDeclaration) { SourceLocation location = recordDeclaration->getLocation(); if (! m_context.sourceLocationHelper.IsLocationOfInterest(GetName(), location, *m_sourceManager)) return; const CXXRecordDecl* recordDefinition = recordDeclaration->getDefinition(); if (recordDefinition == nullptr) return; for (const auto& base : recordDefinition->bases()) { const RecordType* baseRecordType = base.getType()->getAs<RecordType>(); if (baseRecordType == nullptr) continue; const RecordDecl* baseDeclaration = baseRecordType->getDecl(); if (baseDeclaration == nullptr) continue; const RecordDecl* baseDefinition = baseDeclaration->getDefinition(); if (baseDefinition == nullptr) continue; if (IsInDirectlyIncludedProjectHeader(baseDefinition)) { BlacklistIncludedProjectHeader(baseDefinition); } } } void PossibleForwardDeclarationRule::HandleDeclarationWithTagType(const TagDecl* tagDeclaration, const Decl* declarationWithTagType, bool isPointerOrReferenceType, bool isTemplateClassType, bool isOldStyleEnum) { SourceLocation location = declarationWithTagType->getLocation(); if (! m_context.sourceLocationHelper.IsLocationOfInterest(GetName(), location, *m_sourceManager)) return; if (isPointerOrReferenceType && !isTemplateClassType && !isOldStyleEnum && (isa<ParmVarDecl>(declarationWithTagType) || isa<FieldDecl>(declarationWithTagType) || isa<FunctionDecl>(declarationWithTagType))) { if (m_candidateForwardDeclarations.count(tagDeclaration) == 0) { m_candidateForwardDeclarations.insert(std::make_pair(tagDeclaration, location)); } } else { m_candidateForwardDeclarations.erase(tagDeclaration); BlacklistIncludedProjectHeader(tagDeclaration); } } void PossibleForwardDeclarationRule::HandleExpressionWithTagType(const TagDecl* tagDeclaration, const Expr* expressionWithTagType) { SourceLocation location = expressionWithTagType->getLocStart(); if (! m_context.sourceLocationHelper.IsLocationOfInterest(GetName(), location, *m_sourceManager)) return; m_candidateForwardDeclarations.erase(tagDeclaration); BlacklistIncludedProjectHeader(tagDeclaration); } void PossibleForwardDeclarationRule::onEndOfTranslationUnit() { using DeclarationInfoPair = std::pair<const TagDecl*, SourceLocation>; std::vector<DeclarationInfoPair> forwardDeclarations; for (const DeclarationInfoPair& forwardDeclaration : m_candidateForwardDeclarations) { if (! IsInBlacklistedProjectHeader(forwardDeclaration.first)) { forwardDeclarations.push_back(forwardDeclaration); } } std::sort(forwardDeclarations.begin(), forwardDeclarations.end(), [this](const DeclarationInfoPair& left, const DeclarationInfoPair& right) { return m_sourceManager->isBeforeInTranslationUnit(left.second, right.second); }); for (const DeclarationInfoPair& forwardDeclaration : forwardDeclarations) { m_context.outputPrinter->PrintRuleViolation( "possible forward declaration", Severity::Information, boost::str(boost::format("%s '%s' can be forward declared instead of #included") % GetTagTypeString(forwardDeclaration.first) % forwardDeclaration.first->getQualifiedNameAsString()), forwardDeclaration.second, *m_sourceManager); } m_candidateForwardDeclarations.clear(); }
34.577938
129
0.686733
[ "vector" ]
f1aae9634d84ce22c4c646f64280567e33653b02
2,652
hpp
C++
include/universal/blas/generators/uniform_random.hpp
AI-App/universal
a2e8eff7a1354faa8c9584e347414ee62b12e1be
[ "MIT" ]
254
2017-05-24T16:51:57.000Z
2022-03-22T13:07:29.000Z
include/universal/blas/generators/uniform_random.hpp
jamesquinlan/universal
3b7e6bf37cbb9123425b634d18af18a409c2eccc
[ "MIT" ]
101
2017-11-09T22:57:24.000Z
2022-03-17T12:44:59.000Z
include/universal/blas/generators/uniform_random.hpp
jamesquinlan/universal
3b7e6bf37cbb9123425b634d18af18a409c2eccc
[ "MIT" ]
55
2017-06-09T10:04:38.000Z
2022-02-01T16:54:56.000Z
#pragma once // uniform_random.hpp: uniform random matrix generator // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <cstdint> #include <random> namespace sw::universal::blas { // generate a uniform random MxN matrix template<typename Matrix> Matrix uniform_random(size_t M, size_t N, double lowerbound = 0.0, double upperbound = 1.0) { Matrix A(M, N); return uniform_random(A, lowerbound, upperbound); } // fill a dense vector with random values between [lowerbound, upperbound] template <typename Scalar> vector<Scalar>& uniform_random(vector<Scalar>& v, double lowerbound = 0.0, double upperbound = 1.0) { // Use random_device to generate a seed for Mersenne twister engine. std::random_device rd{}; // Use Mersenne twister engine to generate pseudo-random numbers. std::mt19937 engine{ rd() }; // "Filter" MT engine's output to generate pseudo-random double values, // **uniformly distributed** on the closed interval [lowerbound, upperbound]. // (Note that the range is [inclusive, inclusive].) std::uniform_real_distribution<double> dist{ lowerbound, upperbound }; // Pattern to generate pseudo-random number. // double rnd_value = dist(engine); // generate and insert random values in A for (size_t i = 0; i < v.size(); ++i) { v[i] = Scalar(dist(engine)); } return v; } // fill a dense matrix with random values between [lowerbound, upperbound] template <typename Scalar> matrix<Scalar>& uniform_random(matrix<Scalar>& A, double lowerbound = 0.0, double upperbound = 1.0) { // Use random_device to generate a seed for Mersenne twister engine. std::random_device rd{}; // Use Mersenne twister engine to generate pseudo-random numbers. std::mt19937 engine{ rd() }; // "Filter" MT engine's output to generate pseudo-random double values, // **uniformly distributed** on the closed interval [lowerbound, upperbound]. // (Note that the range is [inclusive, inclusive].) std::uniform_real_distribution<double> dist{ lowerbound, upperbound }; // Pattern to generate pseudo-random number. // double rnd_value = dist(engine); using Matrix = matrix<Scalar>; typedef typename Matrix::value_type value_type; typedef typename Matrix::size_type size_type; // inserters add to the elements, so we need to set the value to 0 before we begin A = 0.0; // generate and insert random values in A for (size_type r = 0; r < num_rows(A); r++) { for (size_type c = 0; c < num_cols(A); c++) { A[r][c] = value_type(dist(engine)); } } return A; } } // namespace sw::universal::blas
37.352113
106
0.725113
[ "vector" ]
f1ad489cb0ae85132a20c6cc67a69b0264e455b6
25,845
cpp
C++
storage/driver.azure/src/cloud_blob_container.cpp
gamunu/bolt
c1a2956f02656f3ec2c244486a816337126905ae
[ "Apache-2.0" ]
1
2022-03-06T09:23:56.000Z
2022-03-06T09:23:56.000Z
storage/driver.azure/src/cloud_blob_container.cpp
gamunu/bolt
c1a2956f02656f3ec2c244486a816337126905ae
[ "Apache-2.0" ]
3
2021-04-23T18:12:20.000Z
2021-04-23T18:12:47.000Z
storage/driver.azure/src/cloud_blob_container.cpp
gamunu/bolt
c1a2956f02656f3ec2c244486a816337126905ae
[ "Apache-2.0" ]
null
null
null
// ----------------------------------------------------------------------------------------- // <copyright file="cloud_blob_container.cpp" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- #include "stdafx.h" #include "was/blob.h" #include "wascore/protocol.h" #include "wascore/protocol_xml.h" #include "wascore/util.h" #include "wascore/constants.h" namespace azure { namespace storage { cloud_blob_container::cloud_blob_container(storage_uri uri) : m_uri(std::move(uri)), m_metadata(std::make_shared<cloud_metadata>()), m_properties(std::make_shared<cloud_blob_container_properties>()) { init(storage_credentials()); } cloud_blob_container::cloud_blob_container(storage_uri uri, storage_credentials credentials) : m_uri(std::move(uri)), m_metadata(std::make_shared<cloud_metadata>()), m_properties(std::make_shared<cloud_blob_container_properties>()) { init(std::move(credentials)); } cloud_blob_container::cloud_blob_container(utility::string_t name, cloud_blob_client client) : m_name(std::move(name)), m_client(std::move(client)), m_uri(core::append_path_to_uri(m_client.base_uri(), m_name)), m_metadata(std::make_shared<cloud_metadata>()), m_properties(std::make_shared<cloud_blob_container_properties>()) { } cloud_blob_container::cloud_blob_container(utility::string_t name, cloud_blob_client client, cloud_blob_container_properties properties, cloud_metadata metadata) : m_name(std::move(name)), m_client(std::move(client)), m_uri(core::append_path_to_uri(m_client.base_uri(), m_name)), m_metadata(std::make_shared<cloud_metadata>(std::move(metadata))), m_properties(std::make_shared<cloud_blob_container_properties>(std::move(properties))) { } void cloud_blob_container::init(storage_credentials credentials) { utility::string_t snapshot; m_uri = core::verify_blob_uri(m_uri, credentials, snapshot); if (!core::parse_container_uri(m_uri, m_name)) { throw std::invalid_argument("uri"); } m_client = cloud_blob_client(core::get_service_client_uri(m_uri), std::move(credentials)); } utility::string_t cloud_blob_container::get_shared_access_signature(const blob_shared_access_policy& policy, const utility::string_t& stored_policy_identifier) const { if (!service_client().credentials().is_shared_key()) { throw std::logic_error(protocol::error_sas_missing_credentials); } utility::ostringstream_t resource_str; resource_str << U('/') << service_client().credentials().account_name() << U('/') << name(); return protocol::get_blob_sas_token(stored_policy_identifier, policy, cloud_blob_shared_access_headers(), U("c"), resource_str.str(), service_client().credentials()); } cloud_blob cloud_blob_container::get_blob_reference(utility::string_t blob_name) const { return get_blob_reference(std::move(blob_name), utility::string_t()); } cloud_blob cloud_blob_container::get_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const { return cloud_blob(std::move(blob_name), std::move(snapshot_time), *this); } cloud_page_blob cloud_blob_container::get_page_blob_reference(utility::string_t blob_name) const { return get_page_blob_reference(std::move(blob_name), utility::string_t()); } cloud_page_blob cloud_blob_container::get_page_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const { return cloud_page_blob(std::move(blob_name), std::move(snapshot_time), *this); } cloud_block_blob cloud_blob_container::get_block_blob_reference(utility::string_t blob_name) const { return get_block_blob_reference(std::move(blob_name), utility::string_t()); } cloud_block_blob cloud_blob_container::get_block_blob_reference(utility::string_t blob_name, utility::string_t snapshot_time) const { return cloud_block_blob(std::move(blob_name), std::move(snapshot_time), *this); } cloud_blob_directory cloud_blob_container::get_directory_reference(utility::string_t name) const { // TODO: Consider renaming the parameter to directory_name for consistency return cloud_blob_directory(std::move(name), *this); } pplx::task<void> cloud_blob_container::download_attributes_async(const access_condition& condition, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto metadata = m_metadata; auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::get_blob_container_properties, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_location_mode(core::command_location_mode::primary_or_secondary); command->set_preprocess_response([properties, metadata](const web::http::http_response& response, operation_context context) { protocol::preprocess_response(response, context); *properties = protocol::blob_response_parsers::parse_blob_container_properties(response); *metadata = protocol::parse_metadata(response); }); return core::executor<void>::execute_async(command, modified_options, context); } pplx::task<void> cloud_blob_container::upload_metadata_async(const access_condition& condition, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::set_blob_container_metadata, metadata(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); }); return core::executor<void>::execute_async(command, modified_options, context); } pplx::task<utility::string_t> cloud_blob_container::acquire_lease_async(const lease_time& duration, const utility::string_t& proposed_lease_id, const access_condition& condition, const blob_request_options& options, operation_context context) const { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<utility::string_t>>(uri()); command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_acquire, proposed_lease_id, duration, lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) -> utility::string_t { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); return protocol::parse_lease_id(response); }); return core::executor<utility::string_t>::execute_async(command, modified_options, context); } pplx::task<void> cloud_blob_container::renew_lease_async(const access_condition& condition, const blob_request_options& options, operation_context context) const { if (condition.lease_id().empty()) { throw std::invalid_argument("condition"); } blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_renew, utility::string_t(), lease_time(), lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); }); return core::executor<void>::execute_async(command, modified_options, context); } pplx::task<utility::string_t> cloud_blob_container::change_lease_async(const utility::string_t& proposed_lease_id, const access_condition& condition, const blob_request_options& options, operation_context context) const { if (condition.lease_id().empty()) { throw std::invalid_argument("condition"); } blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<utility::string_t>>(uri()); command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_change, proposed_lease_id, lease_time(), lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) -> utility::string_t { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); return protocol::parse_lease_id(response); }); return core::executor<utility::string_t>::execute_async(command, modified_options, context); } pplx::task<void> cloud_blob_container::release_lease_async(const access_condition& condition, const blob_request_options& options, operation_context context) const { if (condition.lease_id().empty()) { throw std::invalid_argument("condition"); } blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_release, utility::string_t(), lease_time(), lease_break_period(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); }); return core::executor<void>::execute_async(command, modified_options, context); } pplx::task<std::chrono::seconds> cloud_blob_container::break_lease_async(const lease_break_period& break_period, const access_condition& condition, const blob_request_options& options, operation_context context) const { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<std::chrono::seconds>>(uri()); command->set_build_request(std::bind(protocol::lease_blob_container, protocol::header_value_lease_break, utility::string_t(), lease_time(), break_period, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) -> std::chrono::seconds { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); return protocol::parse_lease_time(response); }); return core::executor<std::chrono::seconds>::execute_async(command, modified_options, context); } pplx::task<void> cloud_blob_container::create_async(blob_container_public_access_type public_access, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::create_blob_container, public_access, metadata(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); }); return core::executor<void>::execute_async(command, modified_options, context); } pplx::task<bool> cloud_blob_container::create_if_not_exists_async(blob_container_public_access_type public_access, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto instance = std::make_shared<cloud_blob_container>(*this); return exists_async(true, modified_options, context).then([instance, public_access, modified_options, context](bool exists_result) -> pplx::task < bool > { if (!exists_result) { return instance->create_async(public_access, modified_options, context).then([](pplx::task<void> create_task) -> bool { try { create_task.wait(); return true; } catch (const storage_exception& e) { const azure::storage::request_result& result = e.result(); if (result.is_response_available() && (result.http_status_code() == web::http::status_codes::Conflict) && (result.extended_error().code() == protocol::error_code_container_already_exists)) { return false; } else { throw; } } }); } else { return pplx::task_from_result(false); } }); } pplx::task<void> cloud_blob_container::delete_container_async(const access_condition& condition, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::delete_blob_container, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response(std::bind(protocol::preprocess_response, std::placeholders::_1, std::placeholders::_2)); return core::executor<void>::execute_async(command, modified_options, context); } pplx::task<bool> cloud_blob_container::delete_container_if_exists_async(const access_condition& condition, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto instance = std::make_shared<cloud_blob_container>(*this); return exists_async(true, modified_options, context).then([instance, condition, modified_options, context](bool exists_result) -> pplx::task < bool > { if (exists_result) { return instance->delete_container_async(condition, modified_options, context).then([](pplx::task<void> delete_task) -> bool { try { delete_task.wait(); return true; } catch (const storage_exception& e) { const azure::storage::request_result& result = e.result(); if (result.is_response_available() && (result.http_status_code() == web::http::status_codes::NotFound) && (result.extended_error().code() == protocol::error_code_container_not_found)) { return false; } else { throw; } } }); } else { return pplx::task_from_result<bool>(false); } }); } pplx::task<blob_result_segment> cloud_blob_container::list_blobs_segmented_async(const utility::string_t& prefix, bool use_flat_blob_listing, blob_listing_details::values includes, int max_results, const continuation_token& token, const blob_request_options& options, operation_context context) const { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto container = *this; utility::string_t delimiter; if (!use_flat_blob_listing) { if ((includes & blob_listing_details::snapshots) != 0) { throw std::invalid_argument("includes"); } delimiter = service_client().directory_delimiter(); } auto command = std::make_shared<core::storage_command<blob_result_segment>>(uri()); command->set_build_request(std::bind(protocol::list_blobs, prefix, delimiter, includes, max_results, token, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_location_mode(core::command_location_mode::primary_or_secondary, token.target_location()); command->set_preprocess_response(std::bind(protocol::preprocess_response<blob_result_segment>, blob_result_segment(), std::placeholders::_1, std::placeholders::_2)); command->set_postprocess_response([container, delimiter](const web::http::http_response& response, const request_result& result, const core::ostream_descriptor&, operation_context context) -> pplx::task < blob_result_segment > { protocol::list_blobs_reader reader(response.body()); std::vector<protocol::cloud_blob_list_item> blob_items(reader.extract_blob_items()); std::vector<cloud_blob> blobs; for (std::vector<protocol::cloud_blob_list_item>::iterator iter = blob_items.begin(); iter != blob_items.end(); ++iter) { blobs.push_back(cloud_blob(iter->name(), iter->snapshot_time(), container, iter->properties(), iter->metadata(), iter->copy_state())); } std::vector<protocol::cloud_blob_prefix_list_item> blob_prefix_items(reader.extract_blob_prefix_items()); std::vector<cloud_blob_directory> directories; for (auto iter = blob_prefix_items.begin(); iter != blob_prefix_items.end(); ++iter) { directories.push_back(cloud_blob_directory(iter->name(), container)); } continuation_token next_token(reader.extract_next_marker()); next_token.set_target_location(result.target_location()); return pplx::task_from_result(blob_result_segment(std::move(blobs), std::move(directories), next_token)); }); return core::executor<blob_result_segment>::execute_async(command, modified_options, context); } pplx::task<void> cloud_blob_container::upload_permissions_async(const blob_container_permissions& permissions, const access_condition& condition, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); protocol::access_policy_writer<blob_shared_access_policy> writer; concurrency::streams::istream stream(concurrency::streams::bytestream::open_istream(writer.write(permissions.policies()))); auto properties = m_properties; auto command = std::make_shared<core::storage_command<void>>(uri()); command->set_build_request(std::bind(protocol::set_blob_container_acl, permissions.public_access(), condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); }); return core::istream_descriptor::create(stream).then([command, context, modified_options](core::istream_descriptor request_body) -> pplx::task < void > { command->set_request_body(request_body); return core::executor<void>::execute_async(command, modified_options, context); }); } pplx::task<blob_container_permissions> cloud_blob_container::download_permissions_async(const access_condition& condition, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto command = std::make_shared<core::storage_command<blob_container_permissions>>(uri()); command->set_build_request(std::bind(protocol::get_blob_container_acl, condition, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_location_mode(core::command_location_mode::primary_or_secondary); command->set_preprocess_response([properties](const web::http::http_response& response, operation_context context) -> blob_container_permissions { protocol::preprocess_response(response, context); properties->update_etag_and_last_modified(protocol::blob_response_parsers::parse_blob_container_properties(response)); return blob_container_permissions(); }); command->set_postprocess_response([](const web::http::http_response& response, const request_result&, const core::ostream_descriptor&, operation_context context) -> pplx::task < blob_container_permissions > { blob_container_permissions permissions; protocol::access_policy_reader<blob_shared_access_policy> reader(response.body()); permissions.set_policies(reader.extract_policies()); permissions.set_public_access(protocol::blob_response_parsers::parse_public_access_type(response)); return pplx::task_from_result<blob_container_permissions>(permissions); }); return core::executor<blob_container_permissions>::execute_async(command, modified_options, context); } pplx::task<bool> cloud_blob_container::exists_async(bool primary_only, const blob_request_options& options, operation_context context) { blob_request_options modified_options(options); modified_options.apply_defaults(service_client().default_request_options(), blob_type::unspecified); auto properties = m_properties; auto metadata = m_metadata; auto command = std::make_shared<core::storage_command<bool>>(uri()); command->set_build_request(std::bind(protocol::get_blob_container_properties, access_condition(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); command->set_authentication_handler(service_client().authentication_handler()); command->set_location_mode(primary_only ? core::command_location_mode::primary_only : core::command_location_mode::primary_or_secondary); command->set_preprocess_response([properties, metadata](const web::http::http_response& response, operation_context context) -> bool { if (response.status_code() == web::http::status_codes::NotFound) { return false; } protocol::preprocess_response(response, context); *properties = protocol::blob_response_parsers::parse_blob_container_properties(response); *metadata = protocol::parse_metadata(response); return true; }); return core::executor<bool>::execute_async(command, modified_options, context); } } } // namespace azure::storage
51.89759
302
0.764442
[ "vector" ]
f1b4d838b7b49afe9bd0be7996536c093214d060
6,447
cpp
C++
source/smeardeformer/Extensions.cpp
youdiaozi/c4d-nr-toolbox
ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6
[ "BSD-3-Clause" ]
16
2018-09-12T10:38:26.000Z
2021-06-28T22:57:30.000Z
source/smeardeformer/Extensions.cpp
youdiaozi/c4d-nr-toolbox
ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6
[ "BSD-3-Clause" ]
10
2018-09-11T17:20:09.000Z
2020-06-02T04:11:01.000Z
source/smeardeformer/Extensions.cpp
NiklasRosenstein/c4d-nr-toolbox
28197ea7fcf396b5941277b049168d7faf00bfbf
[ "BSD-3-Clause" ]
6
2018-11-30T23:34:49.000Z
2021-04-02T15:03:23.000Z
/** * Copyright (C) 2013, Niklas Rosenstein * All rights reserved. * * Extensions.cpp */ #define _USE_MATH_DEFINES #include <cmath> #include <c4d_apibridge.h> #include "Engines.h" #include "res/c4d_symbols.h" #include "res/description/Osmeardeformer.h" #include "res/description/Spositional.h" #include "res/description/Shistorical.h" #include "res/description/Wvertexnormal.h" class PositionalSmearing : public SmearingEngine { public: static BaseEngine* Alloc() { return NewObjClear(PositionalSmearing); } //| SmearingEngine overrides virtual Int32 GetMaxHistoryLevel() const { return 1; // We only need the previous position } virtual Vector SmearVertex(Int32 vertex_index, Float weight, const SmearData& data, const SmearHistory& history) { const SmearState* prev = history.GetState(1); const SmearState* curr = history.GetState(0); if (!curr) return Vector(); // We can garuantee that the vertex_index will not exceed the // bounds of the current smear state. const Vector& curr_p = curr->original_vertices[vertex_index]; // But we can not garuantee this for the previous state. if (!prev || vertex_index >= prev->vertex_count) { return curr_p; } const Vector& prev_p = prev->original_vertices[vertex_index]; return curr_p * (1.0 - weight) + prev_p * weight; } }; class HistoricalSmearing : public SmearingEngine { public: static BaseEngine* Alloc() { return NewObjClear(HistoricalSmearing); } HistoricalSmearing() : SmearingEngine(), m_count(0) { } //| SmearingEngine overrides virtual Int32 GetMaxHistoryLevel() const { return m_count; } virtual Vector SmearVertex(Int32 vertex_index, Float weight, const SmearData& data, const SmearHistory& history) { if (weight < 0.0) weight = 0.0; if (weight > 1.0) weight = 1.0; Int32 count = history.GetHistoryCount(); count = maxon::Min<Int32>(count, m_count); if (count <= 0) return Vector(); count -= 1; Int32 frame_1 = (count) * weight; Int32 frame_2 = frame_1 + 1; const SmearState* state_1 = history.GetState(frame_1); const SmearState* state_2 = history.GetState(frame_2); if (!state_1 || vertex_index >= state_1->vertex_count) { // TODO: This shouldn't happen!! return Vector(); } const Vector& p1 = state_1->original_vertices[vertex_index]; if (!state_2 || vertex_index >= state_2->vertex_count) { return p1; } const Vector& p2 = state_2->original_vertices[vertex_index]; Float rweight = fmod(count * weight, 1.0); return p1 * (1.0 - rweight) + p2 * rweight; } //| BaseEngine overrides virtual Bool InitParameters(BaseContainer& bc) { if (bc.GetType(SHISTORICAL_TIMEDELTA) != DA_REAL) { bc.SetFloat(SHISTORICAL_TIMEDELTA, 0.1); } return true; } virtual Bool InitData(const BaseContainer& bc, const SmearData& data) { m_count = data.doc->GetFps() * bc.GetFloat(SHISTORICAL_TIMEDELTA); return true; } private: Int32 m_count; }; class VertexNormalWeighting : public WeightingEngine { public: static BaseEngine* Alloc() { return NewObjClear(VertexNormalWeighting); } VertexNormalWeighting() : WeightingEngine(), m_vertex_based(false) { } Vector GetVertexMovement(Int32 index, const SmearState* curr, const SmearState* prev) { if (m_vertex_based) { if (index >= curr->vertex_count || index >= prev->vertex_count) return Vector(); return curr->original_vertices[index] - prev->original_vertices[index]; } else { return curr->mg.off - prev->mg.off; } } //| WeightingEngine overrides virtual Float WeightVertex(Int32 vertex_index, const SmearData& data, const SmearHistory& history) { const SmearState* curr = history.GetState(0); const SmearState* prev = history.GetState(1); if (!curr || !prev) return 0.0; if (vertex_index >= prev->vertex_count) return 0.0; static const Float ellipsis = 0.0000001; // Figure the movement direction. If there was not movement in the last frames, // we will check the previous frames until a movement was found. Vector mvdir = GetVertexMovement(vertex_index, curr, prev); Int32 state_index = 2; while (mvdir.GetSquaredLength() <= ellipsis && state_index < history.GetHistoryCount()) { const SmearState* curr = history.GetState(state_index - 1); const SmearState* prev = history.GetState(state_index); mvdir = GetVertexMovement(vertex_index, curr, prev); state_index++; } // No movement figured, no weighting. if (mvdir.GetSquaredLength() < ellipsis) { return 0.0; } // Again, we _can_ assume that the vertex_index will not exceed // the bounds of the _current_ state. const Vector& vxdir = curr->original_normals[vertex_index]; Float angle = GetAngle(mvdir, vxdir); return angle / M_PI; } //| BaseEngine overrides virtual Bool InitParameters(BaseContainer& bc) { if (bc.GetType(WVERTEXNORMAL_VERTEXBASEDMOVEMENT) != DA_LONG) { bc.SetBool(WVERTEXNORMAL_VERTEXBASEDMOVEMENT, true); } return true; } virtual Bool InitData(const BaseContainer& bc, const SmearData& data) { m_vertex_based = bc.GetBool(WVERTEXNORMAL_VERTEXBASEDMOVEMENT); return true; } private: Bool m_vertex_based; }; Bool RegisterSmearExtensions() { RegisterEnginePlugin( Wvertexnormal, ID_WEIGHTINGENGINE, GeLoadString(IDC_WEIGHTING_VERTEXNORMAL), "Wvertexnormal", VertexNormalWeighting::Alloc); RegisterEnginePlugin( Spositional, ID_SMEARINGENGINE, GeLoadString(IDC_SMEARING_POSITIONAL), "Spositional", PositionalSmearing::Alloc); RegisterEnginePlugin( Shistorical, ID_SMEARINGENGINE, GeLoadString(IDC_SMEARING_HISTORICAL), "Shistorical", HistoricalSmearing::Alloc); return true; } Bool RegisterWeightExtensions() { return true; }
29.847222
118
0.639522
[ "vector" ]
f1bc57391727c2cb1af42f97a7d5525939b6ba5f
11,876
cpp
C++
test/TestApp/AutoGenTests/AutoGenContentTests.cpp
PlayFab/XPlatCSdk
101896fff5c5ce822dd188e4670a9ba8c1705619
[ "MIT" ]
null
null
null
test/TestApp/AutoGenTests/AutoGenContentTests.cpp
PlayFab/XPlatCSdk
101896fff5c5ce822dd188e4670a9ba8c1705619
[ "MIT" ]
1
2022-03-04T20:50:28.000Z
2022-03-04T21:02:12.000Z
test/TestApp/AutoGenTests/AutoGenContentTests.cpp
PlayFab/XPlatCSdk
101896fff5c5ce822dd188e4670a9ba8c1705619
[ "MIT" ]
3
2021-12-04T20:43:04.000Z
2022-01-03T21:16:32.000Z
#include "TestAppPch.h" #include "TestContext.h" #include "TestApp.h" #include "AutoGenContentTests.h" #include "XAsyncHelper.h" #include "playfab/PFAuthentication.h" namespace PlayFabUnit { using namespace PlayFab::Wrappers; AutoGenContentTests::ContentTestData AutoGenContentTests::testData; void AutoGenContentTests::Log(std::stringstream& ss) { TestApp::LogPut(ss.str().c_str()); ss.str(std::string()); ss.clear(); } HRESULT AutoGenContentTests::LogHR(HRESULT hr) { if (TestApp::ShouldTrace(PFTestTraceLevel::Information)) { TestApp::Log("Result: 0x%0.8x", hr); } return hr; } void AutoGenContentTests::AddTests() { // Generated tests #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestContentAdminDeleteContent", &AutoGenContentTests::TestContentAdminDeleteContent); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestContentAdminGetContentList", &AutoGenContentTests::TestContentAdminGetContentList); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestContentAdminGetContentUploadUrl", &AutoGenContentTests::TestContentAdminGetContentUploadUrl); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestContentClientGetContentDownloadUrl", &AutoGenContentTests::TestContentClientGetContentDownloadUrl); #endif #if HC_PLATFORM != HC_PLATFORM_GDK AddTest("TestContentServerGetContentDownloadUrl", &AutoGenContentTests::TestContentServerGetContentDownloadUrl); #endif } void AutoGenContentTests::ClassSetUp() { HRESULT hr = PFAdminInitialize(testTitleData.titleId.data(), testTitleData.developerSecretKey.data(), testTitleData.connectionString.data(), nullptr, &stateHandle); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { PFAuthenticationLoginWithCustomIDRequest request{}; request.customId = "CustomId"; request.createAccount = true; PFGetPlayerCombinedInfoRequestParams combinedInfoRequestParams{}; combinedInfoRequestParams.getCharacterInventories = true; combinedInfoRequestParams.getCharacterList = true; combinedInfoRequestParams.getPlayerProfile = true; combinedInfoRequestParams.getPlayerStatistics = true; combinedInfoRequestParams.getTitleData = true; combinedInfoRequestParams.getUserAccountInfo = true; combinedInfoRequestParams.getUserData = true; combinedInfoRequestParams.getUserInventory = true; combinedInfoRequestParams.getUserReadOnlyData = true; combinedInfoRequestParams.getUserVirtualCurrency = true; request.infoRequestParameters = &combinedInfoRequestParams; XAsyncBlock async{}; hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously wait for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle); assert(SUCCEEDED(hr) && titlePlayerHandle); hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle, &entityHandle); assert(SUCCEEDED(hr) && entityHandle); } } request.customId = "CustomId2"; async = {}; hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously what for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle2); assert(SUCCEEDED(hr) && titlePlayerHandle2); hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle2, &entityHandle2); assert(SUCCEEDED(hr) && entityHandle2); } } PFAuthenticationGetEntityTokenRequest titleTokenRequest{}; async = {}; hr = PFAuthenticationGetEntityTokenAsync(stateHandle, &titleTokenRequest, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously wait for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationGetEntityTokenGetResult(&async, &titleEntityHandle); assert(SUCCEEDED(hr)); } } } } void AutoGenContentTests::ClassTearDown() { PFTitlePlayerCloseHandle(titlePlayerHandle); PFEntityCloseHandle(entityHandle); PFEntityCloseHandle(titleEntityHandle); XAsyncBlock async{}; HRESULT hr = PFUninitializeAsync(stateHandle, &async); assert(SUCCEEDED(hr)); hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); UNREFERENCED_PARAMETER(hr); } void AutoGenContentTests::SetUp(TestContext& testContext) { if (!entityHandle) { testContext.Skip("Skipping test because login failed"); } } #pragma region AdminDeleteContent #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenContentTests::TestContentAdminDeleteContent(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFContentDeleteContentRequestWrapper<> request; FillAdminDeleteContentRequest(request); LogDeleteContentRequest(&request.Model(), "TestContentAdminDeleteContent"); HRESULT hr = PFContentAdminDeleteContentAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFContentContentAdminDeleteContentAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region AdminGetContentList #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenContentTests::TestContentAdminGetContentList(TestContext& testContext) { struct AdminGetContentListResultHolderStruct : public GetContentListResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFContentAdminGetContentListGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFContentAdminGetContentListGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogGetContentListResult(result); return S_OK; } HRESULT Validate() override { return ValidateAdminGetContentListResponse(result); } }; auto async = std::make_unique<XAsyncHelper<AdminGetContentListResultHolderStruct>>(testContext); PFContentGetContentListRequestWrapper<> request; FillAdminGetContentListRequest(request); LogGetContentListRequest(&request.Model(), "TestContentAdminGetContentList"); HRESULT hr = PFContentAdminGetContentListAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFContentContentAdminGetContentListAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region AdminGetContentUploadUrl #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenContentTests::TestContentAdminGetContentUploadUrl(TestContext& testContext) { struct AdminGetContentUploadUrlResultHolderStruct : public GetContentUploadUrlResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFContentAdminGetContentUploadUrlGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFContentAdminGetContentUploadUrlGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogGetContentUploadUrlResult(result); return S_OK; } HRESULT Validate() override { return ValidateAdminGetContentUploadUrlResponse(result); } }; auto async = std::make_unique<XAsyncHelper<AdminGetContentUploadUrlResultHolderStruct>>(testContext); PFContentGetContentUploadUrlRequestWrapper<> request; FillAdminGetContentUploadUrlRequest(request); LogGetContentUploadUrlRequest(&request.Model(), "TestContentAdminGetContentUploadUrl"); HRESULT hr = PFContentAdminGetContentUploadUrlAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFContentContentAdminGetContentUploadUrlAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region ClientGetContentDownloadUrl #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenContentTests::TestContentClientGetContentDownloadUrl(TestContext& testContext) { struct ClientGetContentDownloadUrlResultHolderStruct : public GetContentDownloadUrlResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFContentClientGetContentDownloadUrlGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFContentClientGetContentDownloadUrlGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogGetContentDownloadUrlResult(result); return S_OK; } HRESULT Validate() override { return ValidateClientGetContentDownloadUrlResponse(result); } }; auto async = std::make_unique<XAsyncHelper<ClientGetContentDownloadUrlResultHolderStruct>>(testContext); PFContentGetContentDownloadUrlRequestWrapper<> request; FillClientGetContentDownloadUrlRequest(request); LogGetContentDownloadUrlRequest(&request.Model(), "TestContentClientGetContentDownloadUrl"); HRESULT hr = PFContentClientGetContentDownloadUrlAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFContentContentClientGetContentDownloadUrlAsync", hr); return; } async.release(); } #endif #pragma endregion #pragma region ServerGetContentDownloadUrl #if HC_PLATFORM != HC_PLATFORM_GDK void AutoGenContentTests::TestContentServerGetContentDownloadUrl(TestContext& testContext) { struct ServerGetContentDownloadUrlResultHolderStruct : public GetContentDownloadUrlResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFContentServerGetContentDownloadUrlGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFContentServerGetContentDownloadUrlGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogGetContentDownloadUrlResult(result); return S_OK; } HRESULT Validate() override { return ValidateServerGetContentDownloadUrlResponse(result); } }; auto async = std::make_unique<XAsyncHelper<ServerGetContentDownloadUrlResultHolderStruct>>(testContext); PFContentGetContentDownloadUrlRequestWrapper<> request; FillServerGetContentDownloadUrlRequest(request); LogGetContentDownloadUrlRequest(&request.Model(), "TestContentServerGetContentDownloadUrl"); HRESULT hr = PFContentServerGetContentDownloadUrlAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFContentContentServerGetContentDownloadUrlAsync", hr); return; } async.release(); } #endif #pragma endregion }
34.028653
168
0.70933
[ "model" ]
f1c17ce66bac14a1a609d684cacfa3fde37310d3
3,189
cpp
C++
src/gnss_parser/src/gnss_parser.cpp
mfkiwl/lidar-mapping
c05a50d267d9b24239766be56714b55a7d189f33
[ "MIT" ]
1
2021-11-19T09:32:01.000Z
2021-11-19T09:32:01.000Z
src/gnss_parser/src/gnss_parser.cpp
mfkiwl/lidar-mapping
c05a50d267d9b24239766be56714b55a7d189f33
[ "MIT" ]
null
null
null
src/gnss_parser/src/gnss_parser.cpp
mfkiwl/lidar-mapping
c05a50d267d9b24239766be56714b55a7d189f33
[ "MIT" ]
null
null
null
#include <string> #include <ros/ros.h> #include <serial/serial.h> #include <sensor_msgs/NavSatFix.h> serial::Serial gnss_serial; ros::Publisher gnss_pub; template <class Type> Type stringToNum(const std::string &str) { std::istringstream iss(str); Type num; iss >> num; return num; } std::vector<std::string> stringSplit(const std::string &s, const char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } void gnssMessageParser(const std::string &msg) { //$GNGGA,090031.00,2057.59811809,N,10546.17292292,E,1,18,2.2,16.4378,M,-28.2478,M,,*64 //ROS_INFO_STREAM(msg); std::vector<std::string> message = stringSplit(msg, ','); if (message[0] == "$GNGGA") { sensor_msgs::NavSatFix navfix_msg; //if (gnss_pub.getNumSubscribers() > 0) //{ navfix_msg.latitude = stringToNum<double>(message[2]); navfix_msg.longitude = stringToNum<double>(message[4]); navfix_msg.altitude = stringToNum<double>(message[9]); ROS_INFO_STREAM(std::setprecision(20) << navfix_msg.latitude << ", " << navfix_msg.longitude << ", " << navfix_msg.altitude); gnss_pub.publish(navfix_msg); //} } } int main(int argc, char **argv) { ros::init(argc, argv, "gnss_parser"); ros::NodeHandle node; gnss_pub = node.advertise<sensor_msgs::NavSatFix>("gnss_position", 100); std::string port; int32_t baudrate; ros::param::get("~port", port); ros::param::get("~baudrate", baudrate); ROS_INFO_STREAM("Opening " << port << " with baudrate " << baudrate); gnss_serial.setPort(port); gnss_serial.setBaudrate(baudrate); while (ros::ok()) { try { gnss_serial.open(); } catch (serial::IOException &e) { ROS_ERROR_STREAM("Unable to open the serial port!"); } if (gnss_serial.isOpen()) { ROS_INFO_STREAM("Successfully connected to serial port."); gnss_serial.flushInput(); try { while (ros::ok()) { ros::spinOnce(); std::string message; gnss_serial.waitReadable(); if (gnss_serial.available()) { message = gnss_serial.readline(); gnssMessageParser(message); } } } catch (const std::exception &e) { if (gnss_serial.isOpen()) { gnss_serial.close(); } ROS_ERROR_STREAM(e.what()); ROS_INFO_STREAM("Re-connect in 1 second."); ros::Duration(1.0).sleep(); } } else { ROS_ERROR_STREAM("The serial port is not connected correctly!"); ROS_INFO_STREAM("Re-connect in 1 second."); ros::Duration(1.0).sleep(); } } }
28.221239
133
0.541863
[ "vector" ]
f1c2591cb1d285eb4711411a4ab83a0ff395243a
4,869
cpp
C++
src/main.cpp
RandalJBarnes/Gimiwan
7b7be3037a77b50ebcb78b22450d736dd8069682
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
RandalJBarnes/Gimiwan
7b7be3037a77b50ebcb78b22450d736dd8069682
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
RandalJBarnes/Gimiwan
7b7be3037a77b50ebcb78b22450d736dd8069682
[ "BSD-3-Clause" ]
null
null
null
//============================================================================= // main.cpp // // The driver for the command line version of the user interface. // // author: // Dr. Randal J. Barnes // Department of Civil, Environmental, and Geo- Engineering // University of Minnesota // // version: // 30 June 2017 //============================================================================= #include <cstring> #include <ctime> #include <iostream> #include "engine.h" #include "now.h" #include "numerical_constants.h" #include "read_data.h" #include "version.h" #include "write_results.h" //----------------------------------------------------------------------------- int main(int argc, char* argv[]) { // Check the command line. switch (argc) { case 1: { Usage(); return 0; } case 2: { if ( strcmp(argv[1], "--help") == 0 ) Help(); else if ( strcmp(argv[1], "--version") == 0 ) Version(); else Usage(); return 0; } case 13: { Banner( std::cout ); break; } default: { Usage(); return 1; } } // Gimiwan <xo> <yo> <k alpha> <k beta> <k count> <h alpha> <h beta> <h count> <radius> <obs file> <wells file> <output root> // [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] // Get <xo> and <yo>. double xo = atof( argv[1] ); double yo = atof( argv[2] ); // Get and check the hydraulic conductivity distribution. double k_alpha = atof( argv[3] ); double k_beta = atof( argv[4] ); if ( k_beta <= EPS ) { std::cerr << "ERROR: k_beta = " << argv[4] << " is not valid; 0 < k_beta." << std::endl; std::cerr << std::endl; Usage(); return 2; } int k_count = atoi( argv[5] ); if ( k_count < 1 ) { std::cerr << "ERROR: k_count = " << argv[5] << " is not valid; 0 < k_count." << std::endl; std::cerr << std::endl; Usage(); return 2; } // Get and check the aquifer thickness distribution. double h_alpha = atof( argv[6] ); double h_beta = atof( argv[7] ); if ( h_beta <= EPS ) { std::cerr << "ERROR: h_beta = " << argv[7] << " is not valid; 0 < h_beta." << std::endl; std::cerr << std::endl; Usage(); return 2; } int h_count = atoi( argv[8] ); if ( h_count < 1 ) { std::cerr << "ERROR: h_count = " << argv[5] << " is not valid; 0 < h_count." << std::endl; std::cerr << std::endl; Usage(); return 2; } // Get and check the buffer radius. double radius = atof( argv[9] ); if ( radius < 0 ) { std::cerr << "ERROR: buffer radius = " << argv[9] << " is not valid; 0 <= buffer radius." << std::endl; std::cerr << std::endl; Usage(); return 2; } // Read in the observation data from the specified <obs file>. std::vector<ObsRecord> obs; try { obs = read_obs_data( argv[10] ); std::cout << obs.size() << " observation data records read from <" << argv[10] << ">." << std::endl; } catch (InvalidObsFile& e) { std::cerr << e.what() << std::endl; return 3; } catch (InvalidObsRecord& e) { std::cerr << e.what() << std::endl; return 3; } // Read in the well data from the specified <well file>. std::vector<WellRecord> wells; try { wells = read_well_data( argv[11] ); std::cout << wells.size() << " well data records read from <" << argv[11] << ">." << std::endl; } catch (InvalidWellFile& e) { std::cerr << e.what() << std::endl; return 3; } catch (InvalidWellRecord& e) { std::cerr << e.what() << std::endl; return 3; } // Execute all of the computations. Results results; try { results = Engine(xo, yo, k_alpha, k_beta, k_count, h_alpha, h_beta, h_count, radius, obs, wells); } catch (TooFewObservations& e) { std::cerr << e.what() << std::endl; return 4; } catch (CholeskyDecompositionFailed& e) { std::cerr << e.what() << std::endl; return 4; } catch (...) { std::cerr << "The Gimiwan Engine failed for an unknown reason." << std::endl; throw; } // Write out the results to the specified output data file. try { write_results( argv[12], results ); std::cout << "Six output files with root name <" << argv[12] << "> created. " << std::endl; } catch (InvalidOutputFile& e) { std::cerr << e.what() << std::endl; return 4; } // Successful termination. double elapsed = static_cast<double>(clock())/CLOCKS_PER_SEC; std::cout << "elapsed time: " << std::fixed << elapsed << " seconds." << std::endl; std::cout << std::endl; // Terminate execution. return 0; }
27.664773
128
0.499281
[ "vector" ]
f1c746edb6e0262343dadf280a039d966c49969d
2,204
cc
C++
cassandra/src/model/DescribeBackupResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
cassandra/src/model/DescribeBackupResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
cassandra/src/model/DescribeBackupResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cassandra/model/DescribeBackupResult.h> #include <json/json.h> using namespace AlibabaCloud::Cassandra; using namespace AlibabaCloud::Cassandra::Model; DescribeBackupResult::DescribeBackupResult() : ServiceResult() {} DescribeBackupResult::DescribeBackupResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeBackupResult::~DescribeBackupResult() {} void DescribeBackupResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto backupNode = value["Backup"]; if(!backupNode["ClusterId"].isNull()) backup_.clusterId = backupNode["ClusterId"].asString(); if(!backupNode["DataCenterId"].isNull()) backup_.dataCenterId = backupNode["DataCenterId"].asString(); if(!backupNode["BackupId"].isNull()) backup_.backupId = backupNode["BackupId"].asString(); if(!backupNode["BackupType"].isNull()) backup_.backupType = backupNode["BackupType"].asString(); if(!backupNode["Status"].isNull()) backup_.status = backupNode["Status"].asString(); if(!backupNode["StartTime"].isNull()) backup_.startTime = backupNode["StartTime"].asString(); if(!backupNode["EndTime"].isNull()) backup_.endTime = backupNode["EndTime"].asString(); if(!backupNode["Size"].isNull()) backup_.size = std::stol(backupNode["Size"].asString()); if(!backupNode["Details"].isNull()) backup_.details = backupNode["Details"].asString(); } DescribeBackupResult::Backup DescribeBackupResult::getBackup()const { return backup_; }
31.942029
75
0.740018
[ "model" ]
f1d2a4a230b7b58f6372c4c9da042ef7d403e2d8
3,109
cpp
C++
thrift/compiler/detail/mustache/test/comments_test.cpp
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
thrift/compiler/detail/mustache/test/comments_test.cpp
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
1
2022-03-03T09:40:25.000Z
2022-03-03T09:40:25.000Z
thrift/compiler/detail/mustache/test/comments_test.cpp
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/portability/GTest.h> #include <thrift/compiler/detail/mustache/mstch.h> using namespace apache::thrift; // Comment blocks should be removed from the template. TEST(CommentsTEST, Inline) { EXPECT_EQ( "1234567890", mstch::render("12345{{! Comment Block! }}67890", mstch::node())); } // Multiline comments should be permitted. TEST(CommentsTEST, Multiline) { EXPECT_EQ( "1234567890\n", mstch::render( "12345{{!\n This is a\n multi-line comment...\n}}67890\n", mstch::node())); } // All standalone comment lines should be removed. TEST(CommentsTEST, Standalone) { EXPECT_EQ( "Begin.\nEnd.\n", mstch::render("Begin.\n{{! Comment Block! }}\nEnd.\n", mstch::node())); } // All standalone comment lines should be removed. TEST(CommentsTEST, IndentedStandalone) { EXPECT_EQ( "Begin.\nEnd.\n", mstch::render( "Begin.\n {{! Indented Comment Block! }}\nEnd.\n", mstch::node())); } // "\r\n" should be considered a newline for standalone tags. TEST(CommentsTEST, StandaloneLineEndings) { EXPECT_EQ( "|\r\n|", mstch::render("|\r\n{{! Standalone Comment }}\r\n|", mstch::node())); } // Standalone tags should not require a newline to precede them. TEST(CommentsTEST, StandaloneWithoutPreviousLine) { EXPECT_EQ( "!", mstch::render(" {{! I'm Still Standalone }}\n!", mstch::node())); } // Standalone tags should not require a newline to follow them. TEST(CommentsTEST, StandaloneWithoutNewline) { EXPECT_EQ( "!\n", mstch::render("!\n {{! I'm Still Standalone }}", mstch::node())); } // All standalone comment lines should be removed. TEST(CommentsTEST, MultilineStandalone) { EXPECT_EQ( "Begin.\nEnd.\n", mstch::render( "Begin.\n{{!\nSomething's going on here...\n}}\nEnd.\n", mstch::node())); } // All standalone comment lines should be removed. TEST(CommentsTEST, IndentedMultilineStandalone) { EXPECT_EQ( "Begin.\nEnd.\n", mstch::render( "Begin.\n {{!\n Something's going on here...\n }}\nEnd.\n", mstch::node())); } // Inline comments should not strip whitespace TEST(CommentsTEST, IndentedInline) { EXPECT_EQ(" 12 \n", mstch::render(" 12 {{! 34 }}\n", mstch::node())); } // Comment removal should preserve surrounding whitespace. TEST(CommentsTEST, SurroundingWhitespace) { EXPECT_EQ( "12345 67890", mstch::render("12345 {{! Comment Block! }} 67890", mstch::node())); }
34.164835
79
0.661306
[ "render" ]
f1d6ed4966208bbc2682864516486f674ce6d565
9,009
cpp
C++
src/graphics/camera.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/graphics/camera.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/graphics/camera.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
1
2021-03-02T16:54:40.000Z
2021-03-02T16:54:40.000Z
#include "camera.hpp" // Standard Headers #include <utility> #include <math.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include <glm/gtx/string_cast.hpp> // Local Headers #include "common/planet.hpp" #include "graphics/window_size.hpp" #include "graphics/input/key_input.hpp" #include "graphics/input/mouse_input.hpp" #include "graphics/imgui/imgui.h" Camera::Camera(float viewportWidth, float viewportHeight, float fov): state({glm::vec3(100, 100, -500), glm::vec3(0, 0, 1), glm::vec3(0, 1, 0), glm::vec3(1, 0, 0)}), viewportWidth(viewportWidth), viewportHeight(viewportHeight), fov(fov) { } void Camera::ShowDebugWindow(bool* p_open) { ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Camera Debug", p_open)) { ImGui::End(); return; } struct funcs { static void ShowKeyValue(const char* key, float value) { ImGui::PushID(key); ImGui::Text("%s: %f", key, value); ImGui::PopID(); } static void ShowKeyValue(const char* key, const char* value) { ImGui::PushID(key); ImGui::Text("%s: %s", key, value); ImGui::PopID(); // if (node_open) // { // static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; // for (int i = 0; i < 8; i++) // { // ImGui::PushID(i); // Use field index as identifier. // if (i < 2) // { // ShowDummyObject("Child", 424242); // } // else // { // // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) // ImGui::AlignTextToFramePadding(); // ImGui::TreeNodeEx("Field", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet, "Field_%d", i); // ImGui::NextColumn(); // ImGui::SetNextItemWidth(-1); // if (i >= 5) // ImGui::InputFloat("##value", &dummy_members[i], 1.0f); // else // ImGui::DragFloat("##value", &dummy_members[i], 0.01f); // ImGui::NextColumn(); // } // ImGui::PopID(); // } // ImGui::TreePop(); // } } }; funcs::ShowKeyValue("position", glm::to_string(state.position).c_str()); funcs::ShowKeyValue("direction", glm::to_string(state.direction).c_str()); funcs::ShowKeyValue("up", glm::to_string(state.up).c_str()); funcs::ShowKeyValue("z_far", last_z_far); funcs::ShowKeyValue("z_near", last_z_near); ImGui::End(); } void Camera::lookAt(vec3 target) { lookAt(target, mu::Y); } void Camera::lookAt(vec3 target, vec3 localYAxis) { state.direction = glm::normalize(target - state.position); state.right = glm::normalize(glm::cross(state.direction, localYAxis)); state.up = glm::normalize(glm::cross(state.right, state.direction)); } void Camera::orientUp(vec3 new_up) { state.up = new_up; state.right = glm::normalize(glm::cross(state.direction, new_up)); } void Camera::rotate(float degrees, glm::vec3 axis, CameraState & state) { float rads = glm::radians(degrees); state.direction = glm::rotate(state.direction, rads, axis); state.right = glm::rotate(state.right, rads, axis); state.up = glm::rotate(state.up, rads, axis); } glm::vec3 Camera::getRayDirection(float viewportX, float viewportY) const { glm::vec2 point = glm::vec2(viewportX / WindowSize::width, 1 - viewportY / WindowSize::height) * glm::vec2(2) - glm::vec2(1); glm::vec4 eyeCoords = inverse(projection) * glm::vec4(point.x, point.y, -1, 1); eyeCoords = glm::vec4(eyeCoords.x, eyeCoords.y, -1.f, 0); glm::vec3 worldCoords = inverse(view) * eyeCoords; return glm::normalize(worldCoords); } // glm::vec3 Camera::getRayDirection(float viewportX, float viewportY) const // { // glm::vec2 point = glm::vec2((2.f * viewportX / viewportWidth) - 1.f, 1.f - (2.f * viewportY) / viewportHeight); // glm::vec4 rayView = glm::inverse(projection) * glm::vec4(point.x, point.y, -1, 1); // rayView = glm::vec4(rayView.x, rayView.y, -1.f, 0.f); // return glm::normalize(glm::inverse(view) * rayView); // } glm::vec3 Camera::getCursorRayDirection() const { return getRayDirection(MouseInput::mouseX, MouseInput::mouseY); } vec3 Camera::project(const vec3 &p, bool &inViewport) const { vec4 homogeneous = combined * vec4(p, 1); vec3 h3 = homogeneous / homogeneous.w; if (!inViewport && homogeneous.z >= 0 && all(lessThanEqual(h3, vec3(1))) && all(greaterThanEqual(h3, vec3(-1)))) inViewport = true; return h3; } glm::quat RotationBetweenVectors(vec3 start, vec3 dest){ start = normalize(start); dest = normalize(dest); float cosTheta = dot(start, dest); vec3 rotationAxis; if (cosTheta < -1 + 0.001f){ // special case when vectors in opposite directions: // there is no "ideal" rotation axis // So guess one; any will do as long as it's perpendicular to start rotationAxis = cross(vec3(0.0f, 0.0f, 1.0f), start); if (glm::length2(rotationAxis) < 0.01 ) // bad luck, they were parallel, try again! rotationAxis = cross(vec3(1.0f, 0.0f, 0.0f), start); rotationAxis = normalize(rotationAxis); return glm::angleAxis(glm::radians(180.0f), rotationAxis); } rotationAxis = cross(start, dest); float s = sqrt( (1+cosTheta)*2 ); float invs = 1 / s; return quat( s * 0.5f, rotationAxis.x * invs, rotationAxis.y * invs, rotationAxis.z * invs ); } void Camera::moveTo(CameraState newState, bool calculateAnimation) { // Find the rotation between the front of the object (that we assume towards +Z, // but this depends on your model) and the desired direction quat rot1 = RotationBetweenVectors(mu::Z, newState.direction); // Because of the 1rst rotation, the up is probably completely screwed up. // Find the rotation between the "up" of the rotated object, and the desired up quat rot2 = RotationBetweenVectors(rot1 * mu::Y, newState.up); targetRotation = rot2 * rot1; targetPosition = newState.position; // targetRotation = glm::quat(glm::lookAt( // newState.position, // newState.position + newState.direction, // newState.up // )); // state.position = newState.position; // state.direction = newState.direction; // state.right = newState.right; // state.up = newState.up; if (calculateAnimation) { float dist = glm::distance(newState.position, state.position); posTotalTime = dist / MAX_SPEED; posT = 0; lastPosition = state.position; // Find the rotation between the front of the object (that we assume towards +Z, // but this depends on your model) and the desired direction quat rot1 = RotationBetweenVectors(mu::Z, state.direction); // Because of the 1rst rotation, the up is probably completely screwed up. // Find the rotation between the "up" of the rotated object, and the desired up quat rot2 = RotationBetweenVectors(rot1 * mu::Y, state.up); lastRotation = rot2 * rot1; } } bool blah = true; glm::vec3 Camera::project(const vec3 &p) const { return project(p, blah); } void Camera::calculate(float z_near, float z_far, float dt) { last_z_near = z_near; last_z_far = z_far; if (mode == Perspective) { projection = glm::perspective(glm::radians(fov), viewportWidth / viewportHeight, z_near, z_far); } else if (mode == Orthographic) { projection = glm::ortho<float>(viewportWidth * -.5, viewportWidth * .5, viewportHeight * -.5, viewportHeight * .5, z_near, z_far); } else { throw "Unknown camera mode"; } // If currently animating if (posT < posTotalTime) { posT += dt; float factor = clamp(posT / posTotalTime, 0.f, 1.f); state.position = glm::mix(lastPosition, targetPosition, factor); glm::quat interRot = glm::slerp(lastRotation, targetRotation, factor); state.direction = interRot * mu::Z; state.up = interRot * mu::Y; state.right = glm::cross(state.direction, state.up); if (posT > posTotalTime) { posT = posTotalTime = 0; } } else { state.position = targetPosition; state.direction = targetRotation * mu::Z; state.up = targetRotation * mu::Y; state.right = glm::cross(state.direction, state.up); } view = glm::lookAt( state.position, state.position + state.direction, state.up ); combined = projection * view; }
32.76
160
0.604951
[ "object", "model" ]
f1da1b2a012ee01c3dce0bd7c50cd216b53d0989
309
cc
C++
lambda/main.cc
zhuhaijun753/cplusplus11.Examples
30076615a88039084a4478e4ce091c00c3bfc9d6
[ "Unlicense" ]
59
2016-05-22T08:09:03.000Z
2022-02-20T13:37:36.000Z
lambda/main.cc
zhuhaijun753/cplusplus11.Examples
30076615a88039084a4478e4ce091c00c3bfc9d6
[ "Unlicense" ]
1
2017-10-26T11:40:43.000Z
2017-10-26T15:14:04.000Z
lambda/main.cc
lostjared/cplusplus11.Examples
30076615a88039084a4478e4ce091c00c3bfc9d6
[ "Unlicense" ]
15
2017-03-09T16:15:43.000Z
2021-09-22T16:36:17.000Z
#include<iostream> #include<vector> int main(int argc, char **argv) { std::vector<int> vec = { 2, 6, 0, 5, 7 }; int findLargest = [](std::vector<int> &v) { int large=0; for(auto &i : v) { if(i > large) large = i; } return large; } (vec); std::cout << findLargest << "\n"; return 0; }
14.714286
44
0.546926
[ "vector" ]
f1e10d08497c12fc8ed0ac264b58079eedd88d9e
10,165
cc
C++
algorithms_cpp/test/scan_test.cc
bufferoverflow/embb
1ff7f601d8e903355e83d766029a3e6164f31750
[ "BSD-2-Clause" ]
1
2020-08-17T11:06:50.000Z
2020-08-17T11:06:50.000Z
algorithms_cpp/test/scan_test.cc
bufferoverflow/embb
1ff7f601d8e903355e83d766029a3e6164f31750
[ "BSD-2-Clause" ]
null
null
null
algorithms_cpp/test/scan_test.cc
bufferoverflow/embb
1ff7f601d8e903355e83d766029a3e6164f31750
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2014, Siemens AG. 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 BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <scan_test.h> #include <embb/algorithms/scan.h> #include <vector> #include <deque> #include <functional> /** * Functor to compute the square of a number. */ struct Square { template<typename Type> Type operator()(Type& l) { return l * l; } }; static int SquareFunction(int &val) { return val * val; } static int AddFunction(int lhs, int rhs) { return lhs + rhs; } ScanTest::ScanTest() { CreateUnit("Different data structures") .Add(&ScanTest::TestDataStructures, this); CreateUnit("Transform").Add(&ScanTest::TestTransform, this); CreateUnit("Function Pointers").Add(&ScanTest::TestFunctionPointers, this); CreateUnit("Ranges").Add(&ScanTest::TestRanges, this); CreateUnit("Block sizes").Add(&ScanTest::TestBlockSizes, this); CreateUnit("Policies").Add(&ScanTest::TestPolicy, this); CreateUnit("Stress test").Add(&ScanTest::StressTest, this); } void ScanTest::TestDataStructures() { using embb::algorithms::Scan; int array[kCountSize]; std::vector<double> vector(kCountSize); std::deque<int> deque(kCountSize); for (size_t i = 0; i < kCountSize; i++) { array[i] = static_cast<int>(i+2); vector[i] = static_cast<int>(i+2); deque[i] = static_cast<int>(i+2); } int outputArray[kCountSize]; std::vector<double> outputVector(kCountSize); std::deque<int> outputDeque(kCountSize); Scan(array, array + kCountSize, outputArray, 0, std::plus<int>()); Scan(vector.begin(), vector.end(), outputVector.begin(), static_cast<double>(0), std::plus<double>()); Scan(deque.begin(), deque.end(), outputDeque.begin(), 0, std::plus<int>()); int expected = 0; for (size_t i = 0; i < kCountSize; i++) { expected += array[i]; PT_EXPECT_EQ(expected, outputArray[i]); PT_EXPECT_EQ(expected, outputVector[i]); PT_EXPECT_EQ(expected, outputDeque[i]); } } void ScanTest::TestTransform() { using embb::algorithms::Scan; std::vector<int> vector(kCountSize); std::vector<int> outputVector(kCountSize); for (size_t i = 0; i < kCountSize; i++) { vector[i] = static_cast<int>(i+2); } Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), Square()); int expected = 0; for (size_t i = 0; i < kCountSize; i++) { expected += vector[i] * vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } } void ScanTest::TestFunctionPointers() { using embb::algorithms::Scan; std::vector<int> vector(kCountSize); std::vector<int> init(kCountSize); std::vector<int> outputVector(kCountSize); int sum = 0; int sqr_sum = 0; for (size_t i = 0; i < kCountSize; i++) { vector[i] = static_cast<int>(i+2); init[i] = 0; sum += static_cast<int>(i + 2); sqr_sum += static_cast<int>((i + 2) * (i + 2)); } Scan(vector.begin(), vector.end(), outputVector.begin(), 0, &AddFunction); int expected = 0; for (size_t i = 0; i < kCountSize; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, &AddFunction, &SquareFunction); expected = 0; for (size_t i = 0; i < kCountSize; i++) { expected += vector[i] * vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, &AddFunction, Square()); expected = 0; for (size_t i = 0; i < kCountSize; i++) { expected += vector[i] * vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), &SquareFunction); expected = 0; for (size_t i = 0; i < kCountSize; i++) { expected += vector[i] * vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } } void ScanTest::TestRanges() { using embb::algorithms::Scan; using embb::algorithms::Identity; size_t count = 4; std::vector<int> init(count); std::vector<int> vector(count); std::vector<int> outputVector(count); for (size_t i = 0; i < count; i++) { init[i] = static_cast<int>(i+2); } vector = init; // Ommit first element outputVector = init; Scan(vector.begin() + 1, vector.end(), outputVector.begin() + 1, 0, std::plus<int>()); PT_EXPECT_EQ(outputVector[0], vector[0]); int expected = 0; for (size_t i = 1; i < count; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } // Ommit last element outputVector = init; Scan(vector.begin(), vector.end() - 1, outputVector.begin(), 0, std::plus<int>()); expected = 0; for (size_t i = 0; i < count - 1; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } PT_EXPECT_EQ(outputVector[count - 1], vector[count - 1]); // Ommit first and last element outputVector = init; Scan(vector.begin() + 1, vector.end() - 1, outputVector.begin() + 1, 0, std::plus<int>()); PT_EXPECT_EQ(outputVector[0], vector[0]); expected = 0; for (size_t i = 1; i < count - 1; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } PT_EXPECT_EQ(outputVector[count - 1], vector[count - 1]); // Only do first element outputVector = init; Scan(vector.begin(), vector.begin() + 1, outputVector.begin(), 0, std::plus<int>()); for (size_t i = 0; i < count; i++) { PT_EXPECT_EQ(outputVector[i], vector[i]); } // Only do last element outputVector = init; Scan(vector.end() - 1, vector.end(), outputVector.end() - 1, 0, std::plus<int>()); for (size_t i = 0; i < count; i++) { PT_EXPECT_EQ(outputVector[i], vector[i]); } // Only do second element outputVector = init; Scan(vector.begin() + 1, vector.begin() + 2, outputVector.begin() + 1, 0, std::plus<int>()); for (size_t i = 0; i < count; i++) { PT_EXPECT_EQ(outputVector[i], vector[i]); } } void ScanTest::TestBlockSizes() { using embb::algorithms::Scan; using embb::algorithms::ExecutionPolicy; using embb::algorithms::Identity; size_t count = 4; std::vector<int> init(count); std::vector<int> vector(count); std::vector<int> outputVector(count); for (size_t i = 0; i < count; i++) { init[i] = static_cast<int>(i+2); } vector = init; for (size_t block_size = 1; block_size < count + 2; block_size++) { outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), Identity(), ExecutionPolicy(), block_size); int expected = 0; for (size_t i = 0; i < count; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } } } void ScanTest::TestPolicy() { using embb::algorithms::Scan; using embb::algorithms::ExecutionPolicy; using embb::algorithms::Identity; size_t count = 4; std::vector<int> init(count); std::vector<int> vector(count); std::vector<int> outputVector(count); for (size_t i = 0; i < count; i++) { init[i] = static_cast<int>(i+2); } vector = init; outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), Identity(), ExecutionPolicy()); int expected = 0; for (size_t i = 0; i < count; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), Identity(), ExecutionPolicy(true)); expected = 0; for (size_t i = 0; i < count; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), Identity(), ExecutionPolicy(false)); expected = 0; for (size_t i = 0; i < count; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } outputVector = init; Scan(vector.begin(), vector.end(), outputVector.begin(), 0, std::plus<int>(), Identity(), ExecutionPolicy(true, 1)); expected = 0; for (size_t i = 0; i < count; i++) { expected += vector[i]; PT_EXPECT_EQ(expected, outputVector[i]); } } void ScanTest::StressTest() { using embb::algorithms::Scan; using embb::algorithms::Identity; using embb::algorithms::ExecutionPolicy; size_t count = embb::mtapi::Node::GetInstance().GetCoreCount() *10; std::vector<int> large_vector(count); std::vector<int> large_vector_output(count); for (size_t i = 0; i < count; i++) { large_vector[i] = static_cast<int>((i + 2) % 1000); } Scan(large_vector.begin(), large_vector.end(), large_vector_output.begin(), 0, std::plus<int>(), Identity(), ExecutionPolicy(), 2000); int expected = 0; for (size_t i = 0; i < count; i++) { expected += large_vector[i]; PT_EXPECT_EQ(expected, large_vector_output[i]); } }
31.180982
80
0.651058
[ "vector", "transform" ]
f1e5488661735a06b8fe227042eef4fa7ddc483c
5,783
cpp
C++
native/cmds/flatland/Renderers.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
native/cmds/flatland/Renderers.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
null
null
null
native/cmds/flatland/Renderers.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Flatland.h" #include "GLHelper.h" namespace android { static float colors[][4] = { { .85f, .14f, .44f, 1.0f }, { .91f, .72f, .10f, 1.0f }, { .04f, .66f, .42f, 1.0f }, { .84f, .39f, .68f, 1.0f }, { .38f, .53f, .78f, 1.0f }, }; static size_t g_colorIndex; const float* genColor() { float* color = colors[g_colorIndex]; g_colorIndex = (g_colorIndex + 1) % NELEMS(colors); return color; } void resetColorGenerator() { g_colorIndex = 0; } class GradientRenderer { public: bool setUp(GLHelper* helper) { bool result; result = helper->getShaderProgram("Gradient", &mGradPgm); if (!result) { return false; } result = helper->getDitherTexture(&mDitherTexName); if (!result) { return false; } mPosAttribLoc = glGetAttribLocation(mGradPgm, "position"); mUVAttribLoc = glGetAttribLocation(mGradPgm, "uv"); mUVToInterpUniformLoc = glGetUniformLocation(mGradPgm, "uvToInterp"); mObjToNdcUniformLoc = glGetUniformLocation(mGradPgm, "objToNdc"); mDitherKernelSamplerLoc = glGetUniformLocation(mGradPgm, "ditherKernel"); mInvDitherKernelSizeUniformLoc = glGetUniformLocation(mGradPgm, "invDitherKernelSize"); mInvDitherKernelSizeSqUniformLoc = glGetUniformLocation(mGradPgm, "invDitherKernelSizeSq"); mColor0UniformLoc = glGetUniformLocation(mGradPgm, "color0"); mColor1UniformLoc = glGetUniformLocation(mGradPgm, "color1"); return true; } void tearDown() { } bool drawGradient() { float identity[16] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; const float pos[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; const float uv[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; const float* color0 = genColor(); const float* color1 = genColor(); glUseProgram(mGradPgm); glVertexAttribPointer(mPosAttribLoc, 2, GL_FLOAT, GL_FALSE, 0, pos); glVertexAttribPointer(mUVAttribLoc, 2, GL_FLOAT, GL_FALSE, 0, uv); glEnableVertexAttribArray(mPosAttribLoc); glEnableVertexAttribArray(mUVAttribLoc); float invDitherKernelSize = 1.0f / float(GLHelper::DITHER_KERNEL_SIZE); float invDitherKernelSizeSq = invDitherKernelSize * invDitherKernelSize; glUniformMatrix4fv(mObjToNdcUniformLoc, 1, GL_FALSE, identity); glUniformMatrix4fv(mUVToInterpUniformLoc, 1, GL_FALSE, identity); glUniform1f(mInvDitherKernelSizeUniformLoc, invDitherKernelSize); glUniform1f(mInvDitherKernelSizeSqUniformLoc, invDitherKernelSizeSq); glUniform4fv(mColor0UniformLoc, 1, color0); glUniform4fv(mColor1UniformLoc, 1, color1); if (glGetError() != GL_NO_ERROR) { fprintf(stderr, "GL error! 0\n"); } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mDitherTexName); if (glGetError() != GL_NO_ERROR) { fprintf(stderr, "GL error! 1\n"); } glUniform1i(mDitherKernelSamplerLoc, 0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(mPosAttribLoc); glDisableVertexAttribArray(mUVAttribLoc); if (glGetError() != GL_NO_ERROR) { fprintf(stderr, "GL error! 2\n"); } return true; } GLuint mGradPgm; GLuint mDitherTexName; GLuint mPosAttribLoc; GLuint mUVAttribLoc; GLuint mObjToNdcUniformLoc; GLuint mUVToInterpUniformLoc; GLuint mDitherKernelSamplerLoc; GLuint mInvDitherKernelSizeUniformLoc; GLuint mInvDitherKernelSizeSqUniformLoc; GLuint mColor0UniformLoc; GLuint mColor1UniformLoc; }; Renderer* staticGradient() { class NoRenderer : public Renderer { virtual bool setUp(GLHelper* helper) { mIsFirstFrame = true; mGLHelper = helper; return mGradientRenderer.setUp(helper); } virtual void tearDown() { mGradientRenderer.tearDown(); } virtual bool render(EGLSurface surface) { if (mIsFirstFrame) { bool result; mIsFirstFrame = false; result = mGLHelper->makeCurrent(surface); if (!result) { return false; } result = mGradientRenderer.drawGradient(); if (!result) { return false; } result = mGLHelper->swapBuffers(surface); if (!result) { return false; } } return true; } bool mIsFirstFrame; GLHelper* mGLHelper; GradientRenderer mGradientRenderer; }; return new NoRenderer; } } // namespace android
29.207071
81
0.598997
[ "render" ]
f1e5e731ada9e8d409da9f4a960a7b304f755262
2,625
cc
C++
scsp/src/model/GetCMSIdByForeignIdResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
scsp/src/model/GetCMSIdByForeignIdResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
scsp/src/model/GetCMSIdByForeignIdResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/scsp/model/GetCMSIdByForeignIdResult.h> #include <json/json.h> using namespace AlibabaCloud::Scsp; using namespace AlibabaCloud::Scsp::Model; GetCMSIdByForeignIdResult::GetCMSIdByForeignIdResult() : ServiceResult() {} GetCMSIdByForeignIdResult::GetCMSIdByForeignIdResult(const std::string &payload) : ServiceResult() { parse(payload); } GetCMSIdByForeignIdResult::~GetCMSIdByForeignIdResult() {} void GetCMSIdByForeignIdResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["Status"].isNull()) data_.status = std::stoi(dataNode["Status"].asString()); if(!dataNode["CustomerTypeId"].isNull()) data_.customerTypeId = std::stoi(dataNode["CustomerTypeId"].asString()); if(!dataNode["Avatar"].isNull()) data_.avatar = dataNode["Avatar"].asString(); if(!dataNode["Gender"].isNull()) data_.gender = dataNode["Gender"].asString(); if(!dataNode["ForeignId"].isNull()) data_.foreignId = dataNode["ForeignId"].asString(); if(!dataNode["UserId"].isNull()) data_.userId = dataNode["UserId"].asString(); if(!dataNode["Nick"].isNull()) data_.nick = dataNode["Nick"].asString(); if(!dataNode["Anonymity"].isNull()) data_.anonymity = dataNode["Anonymity"].asString() == "true"; if(!dataNode["Phone"].isNull()) data_.phone = dataNode["Phone"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } std::string GetCMSIdByForeignIdResult::getMessage()const { return message_; } GetCMSIdByForeignIdResult::Data GetCMSIdByForeignIdResult::getData()const { return data_; } std::string GetCMSIdByForeignIdResult::getCode()const { return code_; } bool GetCMSIdByForeignIdResult::getSuccess()const { return success_; }
29.166667
82
0.727238
[ "model" ]
f1f1477b8012ea9161e707dd3482b32434731e6f
2,025
cpp
C++
intel_extension_for_pytorch/csrc/jit/cpu/kernels/AddLayerNorm.cpp
Manny27nyc/intel-extension-for-pytorch
b40faedf6b00d520f6483d519d2e82bce0a6c0d1
[ "Apache-2.0" ]
null
null
null
intel_extension_for_pytorch/csrc/jit/cpu/kernels/AddLayerNorm.cpp
Manny27nyc/intel-extension-for-pytorch
b40faedf6b00d520f6483d519d2e82bce0a6c0d1
[ "Apache-2.0" ]
null
null
null
intel_extension_for_pytorch/csrc/jit/cpu/kernels/AddLayerNorm.cpp
Manny27nyc/intel-extension-for-pytorch
b40faedf6b00d520f6483d519d2e82bce0a6c0d1
[ "Apache-2.0" ]
null
null
null
// this file is main from // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/cpu/layer_norm_kernel.cpp // and // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/layer_norm.cpp #include "AddLayerNorm.h" #include "csrc/utils/ipex_op_profile.h" #include <torch/csrc/autograd/function.h> namespace torch_ipex { namespace cpu { DEFINE_DISPATCH(add_layer_norm_kernel_stub); at::Tensor AddLayerNorm( const at::Tensor& a, const at::Tensor& b, int alpha, at::IntArrayRef normalized_shape, const c10::optional<at::Tensor>& weight_opt, const c10::optional<at::Tensor>& bias_opt, float eps) { #if defined(DYN_DISP_BUILD) return add_layer_norm_kernel_stub( kCPU, a, b, alpha, normalized_shape, weight_opt, bias_opt, eps); #else return add_layer_norm_kernel_impl( a, b, alpha, normalized_shape, weight_opt, bias_opt, eps); #endif } at::Tensor dil_add_layernorm( const at::Tensor& a, const at::Tensor& b, int alpha, at::IntArrayRef normalized_shape, const c10::optional<at::Tensor>& weight_opt, const c10::optional<at::Tensor>& bias_opt, float eps, bool cuda_enable) { IPEX_RECORD_FUNCTION("dil_add_layernorm", std::vector<c10::IValue>({})); // no broadcast bool no_broadcast = true; for (auto i = 0; i < a.ndimension(); i++) { if (a.size(i) != b.size(i)) { no_broadcast = false; break; } } // Only support 64byte aligned bool aligned_64_bytes = a.size(a.ndimension() - 1) % 16 == 0 && b.size(b.ndimension() - 1) % 16 == 0; // Only support contiguous tensor bool is_contiguous = a.is_contiguous() && b.is_contiguous(); if (no_broadcast && aligned_64_bytes && is_contiguous && alpha == 1.0f) { return AddLayerNorm( a, b, alpha, normalized_shape, weight_opt, bias_opt, eps); } else { auto add_res = at::add(a, b, alpha); return at::layer_norm(add_res, normalized_shape, weight_opt, bias_opt, eps); } } } // namespace cpu } // namespace torch_ipex
30.223881
96
0.682963
[ "vector" ]
f1f27ec833e3a17f215938c379b69bb08f67df43
7,079
hpp
C++
Include/FishEditor/Serialization/YAMLArchive.hpp
yushroom/FishEngine_-Experiment
81e4c06f20f6b94dc561b358f8a11a092678aeeb
[ "MIT" ]
1
2018-12-20T02:38:44.000Z
2018-12-20T02:38:44.000Z
Include/FishEditor/Serialization/YAMLArchive.hpp
yushroom/FishEngine_-Experiment
81e4c06f20f6b94dc561b358f8a11a092678aeeb
[ "MIT" ]
null
null
null
Include/FishEditor/Serialization/YAMLArchive.hpp
yushroom/FishEngine_-Experiment
81e4c06f20f6b94dc561b358f8a11a092678aeeb
[ "MIT" ]
1
2018-10-25T19:40:22.000Z
2018-10-25T19:40:22.000Z
#pragma once #include <FishEngine/Serialization/Archive.hpp> #include <FishEngine/FishEngine2.hpp> #include <set> #include <vector> #include <list> #include <iostream> #include <fstream> #include <sstream> #include <stack> #include <regex> #include <yaml-cpp/yaml.h> using namespace FishEngine; namespace FishEditor { class YAMLInputArchive : public InputArchive { public: YAMLInputArchive() = default; std::vector<Object*> LoadAllFromString(const std::string& str); Object* GetObjectByFileID(int64_t fileID) { auto it = m_FileIDToObject.find(fileID); if (it == m_FileIDToObject.end()) { // fileID not found abort(); } return it->second; // return m_FileIDToObject[fileID]; } const std::map<int64_t, Object*>& GetFileIDToObject() const { return m_FileIDToObject; }; protected: // bool Skip() override // { // return !CurrentNode(); // } virtual Object* DeserializeObject() override; virtual void Deserialize(short & t) override { t = CurrentNode().as<short>(); } virtual void Deserialize(unsigned short & t) override { t = CurrentNode().as<unsigned short>(); } virtual void Deserialize(int & t) override { t = CurrentNode().as<int>(); } virtual void Deserialize(unsigned int & t) override { t = CurrentNode().as<unsigned int>(); } virtual void Deserialize(long & t) override { t = CurrentNode().as<long>();} virtual void Deserialize(unsigned long & t) override { t = CurrentNode().as<unsigned long>();} virtual void Deserialize(long long & t) override { t = CurrentNode().as<long long>();} virtual void Deserialize(unsigned long long & t) override { t = CurrentNode().as<unsigned long long>();} virtual void Deserialize(float & t) override { t = CurrentNode().as<float>();} virtual void Deserialize(double & t) override { t = CurrentNode().as<double>();} virtual void Deserialize(bool & t) override { t = (CurrentNode().as<int>() == 1);} virtual void Deserialize(std::string & t) override { try { t = CurrentNode().as<std::string>(); } catch (const std::exception& e) { t = ""; } } // virtual void Get(std::string& t) override // { // t = CurrentNode().as<std::string>(); // } // virtual void Get(int& t) override // { // t = CurrentNode().as<int>(); // } // virtual void Get(float& t) override // { // t = CurrentNode().as<float>(); // } // virtual void Get(bool& t) override // { // t = CurrentNode().as<int>() == 1; // } // Map virtual bool MapKey(const char* name) override { auto current = CurrentNode(); assert(current.IsMap()); auto node = current[name]; if (!node) { LogWarning(Format("Key [{}] not found!", name)); } PushNode(node); return !(!node); } virtual void AfterValue() override { PopNode(); } // Map virtual int BeginMap() override { auto current = CurrentNode(); assert(current.IsMap()); int size = std::distance(current.begin(), current.end()); m_mapIterator = current.begin(); return size; } // Sequence virtual int BeginSequence() override { auto current = CurrentNode(); assert(current.IsSequence()); int size = std::distance(current.begin(), current.end()); m_sequenceIterator = current.begin(); return size; } virtual void BeginSequenceItem() override { PushNode(*m_sequenceIterator); } virtual void AfterSequenceItem() override { PopNode(); m_sequenceIterator++; } virtual void EndSequence() override { // PopNode(); } void PushNode(YAML::Node node) { // puts("push"); m_workingNodes.push(node); } void PopNode() { // puts("pop"); m_workingNodes.pop(); } YAML::Node CurrentNode() { assert(!m_workingNodes.empty()); return m_workingNodes.top(); } protected: std::vector<YAML::Node> m_nodes; YAML::Node m_currentNode; std::stack<YAML::Node> m_workingNodes; // todo: sequence inside sequence, or, map inside map YAML::const_iterator m_sequenceIterator; YAML::const_iterator m_mapIterator; // local std::map<int64_t, Object*> m_FileIDToObject; }; class YAMLOutputArchive : public OutputArchive { public: explicit YAMLOutputArchive(std::ostream& fout) : fout(fout) { fout << "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n"; } void Dump(Object* obj); protected: virtual void Serialize(short t) override { fout << t; } virtual void Serialize(unsigned short t) override { fout << t; } virtual void Serialize(int t) override { fout << t; } virtual void Serialize(unsigned int t) override { fout << t; } virtual void Serialize(long t) override { fout << t; } virtual void Serialize(unsigned long t) override { fout << t; } virtual void Serialize(long long t) override { fout << t; } virtual void Serialize(unsigned long long t) override { fout << t; } virtual void Serialize(float t) override { fout << t; } virtual void Serialize(double t) override { fout << t; } virtual void Serialize(bool t) override { fout << t; } virtual void Serialize(std::string const & t) override { fout << t; } virtual void SerializeNullPtr() override { fout << "{fileID: 0}"; } //YAMLOutputArchive & operator<<(const Vector2& t) { // fout << Format("{{x:{}, y:{}}}", t.x, t.y); //} //YAMLOutputArchive & operator<<(const Vector3& t) { // fout << Format("{{x:{}, y:{}, z:{}}}", t.x, t.y, t.x); //} //YAMLOutputArchive & operator<<(const Vector4& t) { // fout << Format("{{x:{}, y:{}, z:{}, w:{}}}", t.x, t.y, t.x, t.w); //} //YAMLOutputArchive & operator<<(const Quaternion& t) { // fout << Format("{{x:{}, y:{}, z:{}, w:{}}}", t.x, t.y, t.x, t.w); //} void MapKey(const char* name) override { NewLine(); Indent(); //state = State::MapKey; Serialize(name); fout << ": "; indent += 2; //state = State::MapValue; beginOfLine = false; } void AfterValue() override { indent -= 2; assert(indent >= 0); //state = State::None; beginOfLine = false; } void BeginSequence(int size) override { if (size == 0) fout << "[]"; else { NewLine(); } //state = State::Sequence; } void BeforeSequenceItem() override { NewLine(); indent -= 2; Indent(); indent += 2; fout << "- "; } void AfterSequenceItem() override { beginOfLine = false; } void EndSequence() override { //state = State::None; beginOfLine = true; } void SerializeObject(Object* t) override; void Indent() { for (int i = 0; i < indent; ++i) fout << ' '; } void NewLine() { if (!beginOfLine) { fout << "\n"; beginOfLine = true; } } std::vector<Object*> todo; std::set<Object*> done; std::ostream& fout; //YAML::Emitter fout; int indent = 0; //enum class State //{ // None, // Sequence, // MapKey, // MapValue, //}; //// state of next output //State state = State::None; bool beginOfLine = true; // at begin of current line? if so, additional "\n" is not needed; }; }
22.544586
106
0.613787
[ "object", "vector" ]
f1f6b9dc0d02a3266d3dc02b63f8d1c2d86517a0
23,704
cpp
C++
vm/compiler/RegisterizationME.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
vm/compiler/RegisterizationME.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
vm/compiler/RegisterizationME.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Dalvik.h" #include "Dataflow.h" #include "CompilerIR.h" #include "LoopInformation.h" #include "PassDriver.h" #include "RegisterizationME.h" #include <algorithm> /** * @brief Get the register class for a given define from a PHI node * @param mir the PHI node MIR * @param vR the virtual register number * @param regClass the RegisterClass (updated by the function) * @return whether the function found the register class */ static bool getType (const MIR *mir, int vR, RegisterClass &regClass) { //Paranoid if (mir == 0) { return false; } //Get SSA representation SSARepresentation *ssaRep = mir->ssaRep; //Paranoid if (ssaRep == 0 || ssaRep->defs == 0) { return false; } SUsedChain **chains = ssaRep->usedNext; //If chain is emtpy, we cannot do anything if (chains == 0) { return false; } //For a PHI node, it will be in chains[0] SUsedChain *chain = chains[0]; //Paranoid if (chain == 0) { return false; } MIR *firstUse = chain->mir; //Paranoid if (firstUse == 0) { return false; } //If the first use is extended, reject it if (firstUse->dalvikInsn.opcode >= static_cast<Opcode> (kMirOpFirst)) { return false; } //Ok now find out about this one bool res = dvmCompilerFindRegClass (firstUse, vR, regClass, true); if (res == false) { return false; } //Currently we ignore kX87Reg registers if (regClass == kX87Reg) { return false; } //Success return true; } /** * @brief Select the registers we want to registerize: currently only the entry PHI nodes * @param cUnit the CompilationUnit * @param info the LoopInformation * @param registers the final vector of registers */ static void selectRegisters (CompilationUnit *cUnit, const LoopInformation *info, std::vector<std::pair<int, RegisterClass> > &registers) { //Clear the vector just in case registers.clear (); //As a first iteration of the algorithm, we are only going to registerize interloop dependent variables //These variables are automatically PHI nodes in the entry block BasicBlock *entry = info->getEntryBlock (); for (MIR *mir = entry->firstMIRInsn; mir != 0; mir = mir->next) { //Get dalvik instruction DecodedInstruction &dalvikInsn = mir->dalvikInsn; //Check opcode: is it a Phi node? if (dalvikInsn.opcode == static_cast<Opcode> (kMirOpPhi)) { //Paranoid assert (mir->ssaRep != 0); assert (mir->ssaRep->numDefs > 0); //It is, ok let's get the left side for it: it is in defs[0] int ssaName = mir->ssaRep->defs[0]; //Get the first type used for this register RegisterClass type = kAnyReg; int reg = dvmConvertSSARegToDalvik (cUnit, ssaName); reg = DECODE_REG (reg); bool res = getType (mir, reg, type); //If success, we can add it if (res == true) { registers.push_back (std::make_pair<int, RegisterClass> (ssaName, type)); } } } } /** * @brief Fill the write back requests using the destination's phi nodes * @param bb the BasicBlock that will be walked to get the PHI nodes * @param bv the BitVector to fill */ static void fillWriteBackRequests (BasicBlock *bb, BitVector *bv) { //If null, we have nothing to do if (bb == 0) { return; } //Go through each instruction for (MIR *mir = bb->firstMIRInsn; mir != 0; mir = mir->next) { //Get the instruction DecodedInstruction &insn = mir->dalvikInsn; //Get the opcode Opcode opcode = insn.opcode; //Check for a PHI node if (opcode == static_cast<Opcode> (kMirOpPhi)) { //Get the va, it contains the register in question int dalvikReg = insn.vA; //Now add it dvmSetBit (bv, dalvikReg); } } } /** * @brief Fill the write back requests of the post loop basic blocks using their live outs * @param cUnit the CompilationUnit * @param info the LoopInformation */ static void handleWriteBackRequestsPostLoop (const CompilationUnit *cUnit, LoopInformation *info) { const BitVector *postBasicBlocks = info->getExitLoops (); //Now take care of write back requests BitVectorIterator bvIterator; //Const cast because of incompatibility here BitVector *tmp = const_cast<BitVector *> (postBasicBlocks); dvmBitVectorIteratorInit (tmp, &bvIterator); while (true) { //Get the block index int blockIdx = dvmBitVectorIteratorNext (&bvIterator); //If we are done if (blockIdx == -1) { break; } BasicBlock *bb = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, blockIdx); //Paranoid if (bb == 0) { continue; } //For the moment, we are being simple, exiting the loop, we request write backs of //every register in the method. Note that we do not request writebacks of //temporaries and thus we do not want to use cUnit->numDalvikRegisters unsigned int size = cUnit->numDalvikRegisters; dvmSetInitialBits (bb->requestWriteBack, size); } } /** * @brief Handle write backs requests for the PreHeader, we want to not write back the registerize requests * @param preHeader the preHeader block */ static void handlePreHeaderWriteBackRequests (BasicBlock *preHeader) { //Get a local version of the requests BitVector *requests = preHeader->requestWriteBack; //Go through the instructions for (MIR *mir = preHeader->firstMIRInsn; mir != 0; mir = mir->next) { //Get local version of the instruction const DecodedInstruction &insn = mir->dalvikInsn; //Get the opcode int opcode = insn.opcode; //If it's a registerize if (opcode == kMirOpRegisterize) { //Get the register int reg = insn.vA; //Clear it's bit from the write back requests dvmClearBit (requests, reg); } } } /** * @brief Handle write backs requests for a given BitVector representing blocks * @param cUnit the CompilationUnit * @param blocks a BitVector representing which BasicBlocks to handle */ static void handleWriteBackRequests (const CompilationUnit *cUnit, const BitVector *blocks) { //Paranoid if (blocks == 0) { return; } //Now take care of write backs requests BitVectorIterator bvIterator; //Const cast due to incompatibility here BitVector *tmp = const_cast<BitVector *> (blocks); dvmBitVectorIteratorInit (tmp, &bvIterator); while (true) { //Get the block index int blockIdx = dvmBitVectorIteratorNext (&bvIterator); //If we are done if (blockIdx == -1) { break; } BasicBlock *bb = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, blockIdx); //Paranoid if (bb == 0) { continue; } //Get any merge issues until the BE can handle them by itself //Get the write backs BitVector BitVector *writeBack = bb->requestWriteBack; //First clear the vector dvmClearAllBits (writeBack); //Now get a union of any Phi nodes we need to handle here fillWriteBackRequests (bb->taken, writeBack); fillWriteBackRequests (bb->fallThrough, writeBack); } } /** * @brief Count the register usage for each SSA register in the BasicBlock * @param cUnit the CompilationUnit * @param bb the BasicBlock * @return false, the function does not change the BasicBlock */ static bool countRegistersHelper (CompilationUnit *cUnit, BasicBlock *bb) { //Get the register count data std::map<int, int> *registerCounts = static_cast<std::map<int, int> *> (cUnit->walkData); //If there is no data, bail if (registerCounts == 0) { return false; } //Now go through the BasicBlock for (MIR *mir = bb->firstMIRInsn; mir != 0; mir = mir->next) { //If there is the SSA information SSARepresentation *ssa = mir->ssaRep; if (ssa != 0) { //Go through the uses and count for (int i = 0; i < ssa->numUses; i++) { int use = ssa->uses[i]; (*registerCounts)[use]++; } } } return false; } /** * @brief Count the register usage * @param cUnit the CompilationUnit * @param registerCounts the map to count register usage */ static void countRegisters (CompilationUnit *cUnit, std::map<int, int> &registerCounts) { //Set walking data void *walkData = static_cast<void *> (&registerCounts); //Dispatch the counting dvmCompilerDataFlowAnalysisDispatcher (cUnit, countRegistersHelper, kAllNodes, false, walkData); } /** * @class RegisterSorter * @brief Used to sort the registerize order */ class RegisterSorter { public: /** @brief Register counts to determine the order to registerize */ std::map<int, int> registerCounts; /** * @brief Operator used for the sorting of first < second, it uses the information in registerCount to sort in reverse order * @param first the first register to compare * @param second the second register to compare * @return whether first has a higher register count than second */ bool operator() (const std::pair<int, RegisterClass> &first, const std::pair<int, RegisterClass> &second) { int firstCount = registerCounts[first.second]; int secondCount = registerCounts[second.second]; //We only care about the first return (firstCount > secondCount); } /** * @brief Get the register count map * @return the registerCount map */ std::map<int, int> &getRegisterCounts (void) { return registerCounts; } /** * @brief Destructor to clear the register count map */ ~RegisterSorter (void) { registerCounts.clear (); } }; /** * @brief Parse a BasicBlock of the loop * @param bb the BasicBlock of the loop * @param verbose are we in verbose mode or not * @return whether the BasicBlock contains any opcodes we don't want to support for registerization */ static bool parseBlock (BasicBlock *bb, bool verbose) { //We want to disable registerization when we have control flow in inner loop if (bb->taken != 0 && bb->fallThrough != 0) { //We have two branches so check if we loop back if (bb->taken->blockType != kPreBackwardBlock && bb->taken->blockType != kChainingCellBackwardBranch && bb->fallThrough->blockType != kPreBackwardBlock && bb->fallThrough->blockType != kChainingCellBackwardBranch) { //We are not looping back so disable registerization return false; } } //Go through the instructions for (MIR *mir = bb->firstMIRInsn; mir != 0; mir = mir->next) { int opcode = mir->dalvikInsn.opcode; switch (opcode) { case OP_NOP: case OP_MOVE_FROM16: case OP_MOVE_16: case OP_MOVE_WIDE: case OP_MOVE_WIDE_FROM16: case OP_MOVE_WIDE_16: case OP_MOVE_OBJECT: case OP_MOVE_OBJECT_16: //Not OP_MOVE_RESULT to OP_RETURN_OBJECT case OP_CONST_4: case OP_CONST_16: case OP_CONST: case OP_CONST_HIGH16: case OP_CONST_WIDE_16: case OP_CONST_WIDE_32: case OP_CONST_WIDE: case OP_CONST_WIDE_HIGH16: case OP_CONST_STRING: case OP_CONST_STRING_JUMBO: case OP_CONST_CLASS: //Not monitor/check/instance of, array or instance/trow case OP_GOTO: case OP_GOTO_16: case OP_GOTO_32: //Not switch case OP_CMPL_FLOAT: case OP_CMPG_FLOAT: case OP_CMPL_DOUBLE: case OP_CMPG_DOUBLE: case OP_CMP_LONG: case OP_IF_EQ: case OP_IF_NE: case OP_IF_LT: case OP_IF_GE: case OP_IF_GT: case OP_IF_LE: case OP_IF_EQZ: case OP_IF_NEZ: case OP_IF_LTZ: case OP_IF_GEZ: case OP_IF_GTZ: case OP_IF_LEZ: //Not the unused //Not agets/aputs/iget/iputs/sgets/sputs case OP_AGET: case OP_AGET_WIDE: case OP_AGET_OBJECT: case OP_AGET_BYTE: case OP_AGET_CHAR: case OP_AGET_SHORT: case OP_APUT: case OP_APUT_WIDE: case OP_APUT_OBJECT: case OP_APUT_BYTE: case OP_APUT_CHAR: case OP_APUT_SHORT: //Not the invokes //Not the unused //Not the invokes //Not the unused case OP_NEG_INT: case OP_NOT_INT: case OP_NEG_LONG: case OP_NOT_LONG: case OP_NEG_FLOAT: case OP_NEG_DOUBLE: case OP_INT_TO_DOUBLE: case OP_INT_TO_LONG: case OP_INT_TO_FLOAT: case OP_LONG_TO_INT: case OP_LONG_TO_FLOAT: case OP_LONG_TO_DOUBLE: case OP_FLOAT_TO_INT: case OP_FLOAT_TO_LONG: case OP_FLOAT_TO_DOUBLE: case OP_DOUBLE_TO_INT: case OP_DOUBLE_TO_LONG: case OP_DOUBLE_TO_FLOAT: case OP_INT_TO_BYTE: case OP_INT_TO_CHAR: case OP_INT_TO_SHORT: //Only a subset of alu case OP_ADD_INT: case OP_SUB_INT: case OP_MUL_INT: case OP_DIV_INT: case OP_REM_INT: case OP_AND_INT: case OP_OR_INT: case OP_XOR_INT: case OP_SHL_INT: case OP_SHR_INT: case OP_USHR_INT: case OP_ADD_LONG: case OP_SUB_LONG: case OP_MUL_LONG: case OP_DIV_LONG: case OP_REM_LONG: case OP_AND_LONG: case OP_OR_LONG: case OP_XOR_LONG: case OP_SHL_LONG: case OP_SHR_LONG: case OP_USHR_LONG: case OP_ADD_FLOAT: case OP_SUB_FLOAT: case OP_MUL_FLOAT: case OP_DIV_FLOAT: case OP_REM_FLOAT: case OP_ADD_DOUBLE: case OP_SUB_DOUBLE: case OP_MUL_DOUBLE: case OP_DIV_DOUBLE: case OP_REM_DOUBLE: case OP_ADD_INT_2ADDR: case OP_SUB_INT_2ADDR: case OP_MUL_INT_2ADDR: case OP_DIV_INT_2ADDR: case OP_REM_INT_2ADDR: case OP_AND_INT_2ADDR: case OP_OR_INT_2ADDR: case OP_XOR_INT_2ADDR: case OP_SHL_INT_2ADDR: case OP_SHR_INT_2ADDR: case OP_USHR_INT_2ADDR: case OP_ADD_LONG_2ADDR: case OP_SUB_LONG_2ADDR: case OP_MUL_LONG_2ADDR: case OP_DIV_LONG_2ADDR: case OP_REM_LONG_2ADDR: case OP_AND_LONG_2ADDR: case OP_OR_LONG_2ADDR: case OP_XOR_LONG_2ADDR: case OP_SHL_LONG_2ADDR: case OP_SHR_LONG_2ADDR: case OP_USHR_LONG_2ADDR: case OP_ADD_FLOAT_2ADDR: case OP_SUB_FLOAT_2ADDR: case OP_MUL_FLOAT_2ADDR: case OP_DIV_FLOAT_2ADDR: case OP_REM_FLOAT_2ADDR: case OP_ADD_DOUBLE_2ADDR: case OP_SUB_DOUBLE_2ADDR: case OP_MUL_DOUBLE_2ADDR: case OP_DIV_DOUBLE_2ADDR: case OP_REM_DOUBLE_2ADDR: //Not the lit 16 lit 8 case OP_ADD_INT_LIT16: case OP_ADD_INT_LIT8: //Not the volatile //Not the breakpoint/throw/execute inline //Not the invokes //Not the return barrier //Not the quick //Only a few of the extended case kMirOpPhi: case kMirOpConst128b: case kMirOpMove128b: case kMirOpPackedMultiply: case kMirOpPackedAddition: case kMirOpPackedAddReduce: case kMirOpPackedReduce: case kMirOpPackedSet: case kMirOpPackedSubtract: case kMirOpPackedXor: case kMirOpPackedOr: case kMirOpPackedAnd: case kMirOpPackedShiftLeft: case kMirOpPackedSignedShiftRight: case kMirOpPackedUnsignedShiftRight: break; default: //Not accepted, refuse the block if (verbose == true) { ALOGD ("Rejecting registerization due to %s", dvmCompilerGetDalvikDisassembly (& (mir->dalvikInsn), NULL)); } return false; } } //Got to here, we can accept return true; } /** * @brief Check a loop: is it ok to registerize * @param cUnit the CompilationUnit * @param info the LoopInformation * @return whether it is acceptable for registerization */ static bool checkLoop (CompilationUnit *cUnit, LoopInformation *info) { // Consider only innermost loops if (info->getNested () != 0) { return false; } const BitVector *blocks = info->getBasicBlocks (); //Go through each block BitVectorIterator bvIterator; dvmBitVectorIteratorInit( (BitVector *) blocks, &bvIterator); while (true) { int blockIdx = dvmBitVectorIteratorNext(&bvIterator); //If done, bail if (blockIdx == -1) { break; } //Get BasicBlock BasicBlock *bb = (BasicBlock *) dvmGrowableListGetElement(&cUnit->blockList, blockIdx); //Paranoid if (bb == 0) { break; } //If we don't accept this one, refuse everything if (parseBlock (bb, cUnit->printMe) == false) { return false; } } //Got here so we are good return true; } /** * @brief Registerize a given loop * @param cUnit the CompilationUnit * @param info the LoopInformation * @param data required by interface (not used) * @return true to continue iteration over loops */ static bool registerizeLoop (CompilationUnit *cUnit, LoopInformation *info, void *data = 0) { // Now we check the loop. If it returns false then we don't continue with trying to registerize if (checkLoop (cUnit, info) == false) { return true; } //For now refuse to registerize inner loops that have branches if (dvmCountSetBits (info->getExitLoops ()) > 1 || dvmCountSetBits (info->getBackwardBranches ()) > 1) { return true; } RegisterSorter sorter; std::vector<std::pair<int, RegisterClass> > registers; std::map<int, int> &registerCounts = sorter.getRegisterCounts (); BasicBlock *preHeader = info->getPreHeader (); //Paranoid assert (preHeader != 0); //Select which registers should get registerized selectRegisters (cUnit, info, registers); //Set maximum registerization cUnit->maximumRegisterization = registers.size (); //Now count the uses of each register, do it for all, it's simpler than trying to do it only for the ones we care countRegisters (cUnit, registerCounts); //Finally, filter out and sort the registers in priority order std::sort (registers.begin (), registers.end (), sorter); //Now go through these registers and add the instructions for (std::vector<std::pair<int, RegisterClass> >::const_iterator it = registers.begin (); it != registers.end (); it++) { //Get the values const std::pair<int, RegisterClass> &p = *it; int reg = p.first; // Get the Dalvik number reg = dvmConvertSSARegToDalvik(cUnit, reg); RegisterClass regClass = p.second; //Create a registerize request in the preheader //Actually generate the hoisting code MIR *registerizeInsn = static_cast<MIR *> (dvmCompilerNew (sizeof (*registerizeInsn), true)); registerizeInsn->dalvikInsn.opcode = static_cast<Opcode> (kMirOpRegisterize); //We only care about the register number registerizeInsn->dalvikInsn.vA = DECODE_REG (reg); registerizeInsn->dalvikInsn.vB = regClass; registerizeInsn->dalvikInsn.vC = 0; dvmCompilerPrependMIR (preHeader, registerizeInsn); } //Handle the BasicBlocks of the loop const BitVector *basicBlocks = info->getBasicBlocks (); //Paranoid assert (basicBlocks != 0); //Call the helper function to set the writebacks for each BasicBlock handleWriteBackRequests (cUnit, basicBlocks); //Paranoid assert (preHeader->requestWriteBack != 0); //Clear the writebacks for the loop preheader handlePreHeaderWriteBackRequests (preHeader); //Handle the backward chaining cells of the loop const BitVector *backwards = info->getBackwardBranches (); //Paranoid assert (backwards != 0); //Call the helper function to set the writebacks for the backward chaining cells handleWriteBackRequests (cUnit, backwards); //Last handle the write backs of all live outs for the post loops handleWriteBackRequestsPostLoop (cUnit, info); return true; } bool dvmCompilerWriteBackAll (CompilationUnit *cUnit, BasicBlock *bb) { //First job is going through the BasicBlocks and requesting to write back any defs dvmClearAllBits (bb->requestWriteBack); if (bb->dataFlowInfo != 0 && bb->dataFlowInfo->defV != 0 && bb->dataFlowInfo->useV != 0) { dvmUnifyBitVectors (bb->requestWriteBack, bb->requestWriteBack, bb->dataFlowInfo->defV); // We also add the uses because it is possible to enter loop preheader with // physical register association but when going through interpreter, we may // clobber those register associations. dvmUnifyBitVectors (bb->requestWriteBack, bb->requestWriteBack, bb->dataFlowInfo->useV); } //We don't want to iterate, do this once return false; } void dvmCompilerRegisterize (CompilationUnit *cUnit, Pass *currentPass) { //Now let's go through the loop information LoopInformation *info = cUnit->loopInformation; //Now registerize it if (info != 0) { info->iterate (cUnit, registerizeLoop); } //Unused argument (void) currentPass; }
29.084663
137
0.609011
[ "vector" ]
f1f7cdf861fcb67250881c1d5f0a5955161ac478
321
hpp
C++
src/starling.hpp
Wasted-Audio/Via-for-Rack
5bf284121a788f364e16acd10c6ac7bbe79097ae
[ "MIT" ]
null
null
null
src/starling.hpp
Wasted-Audio/Via-for-Rack
5bf284121a788f364e16acd10c6ac7bbe79097ae
[ "MIT" ]
null
null
null
src/starling.hpp
Wasted-Audio/Via-for-Rack
5bf284121a788f364e16acd10c6ac7bbe79097ae
[ "MIT" ]
1
2022-03-29T22:07:54.000Z
2022-03-29T22:07:54.000Z
#include <rack.hpp> using namespace rack; extern Plugin *pluginInstance; extern Model *modelMeta; extern Model *modelGateseq; extern Model *modelScanner; extern Model *modelSync; extern Model *modelAtsr; extern Model *modelOsc3; extern Model *modelSync3; extern Model *modelSync3XL; extern Model *modelSync3XLLevels;
18.882353
33
0.800623
[ "model" ]
f1f8132a1e9425e2180f272d84964b454c0e4437
9,705
cxx
C++
StRoot/StBeamBackMaker/StBeamBackMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StBeamBackMaker/StBeamBackMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StBeamBackMaker/StBeamBackMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
// // Pibero Djawotho <pibero@indiana.edu> // Indiana University // November 17, 2005 // // C++ STL #include <vector> #include <set> // STAR #include "StEventTypes.h" // Local #include "Line.hh" #include "Track.hh" #include "TopologyMap.hh" #include "StBeamBackMaker.h" #define MAX_R_DISTANCE 5. // cm #define MAX_Z_DISTANCE 10. // cm #define MIN_TRACK_SEED_HITS 60 using namespace std; struct LessHit { bool operator()(const StHit* hit1, const StHit* hit2) const { return hit1->position().z() < hit2->position().z(); } }; typedef multiset<StHit*, LessHit> HitSet; typedef HitSet::iterator HitSetIter; struct LessTrack { bool operator()(const Track* track1, const Track* track2) const { return track1->size() < track2->size(); } }; typedef multiset<Track*, LessTrack> TrackSet; typedef TrackSet::iterator TrackSetIter; ClassImp(StBeamBackMaker) Int_t StBeamBackMaker::Make() { info() << "Processing run=" << GetRunNumber() << ", event=" << GetEventNumber() << endm; StEvent* event = (StEvent*)GetInputDS("StEvent"); if (!event) { warning("No StEvent"); return kStWarn; } StTpcHitCollection* tpc = event->tpcHitCollection(); if (!tpc) { info("No TPC hits"); return kStOk; } info() << tpc->numberOfHits() << " TPC hits in event" << endm; // // Collect all unused TPC hits, i.e. those that were not assigned to // any track by ITTF, into a set with the hit // with the least z-coordinate at the beginning and the hit with // the highest z-coordinate at the end. // HitSet hits; for (UInt_t sector = 0; sector < tpc->numberOfSectors(); ++sector) { for (UInt_t padrow = 0; padrow < tpc->sector(sector)->numberOfPadrows(); ++padrow) { for (UInt_t i = 0; i < tpc->sector(sector)->padrow(padrow)->hits().size(); ++i) { StHit* hit = tpc->sector(sector)->padrow(padrow)->hits()[i]; if (!hit->trackReferenceCount()) { hits.insert(hit); } } } } info() << hits.size() << " unused TPC hits in event" << endm; // // Find track seeds // info("Find track seeds"); // Allocate storage, but don't initialize Track* bufBeg = (Track*)malloc(sizeof(Track)*hits.size()); Track* bufEnd = bufBeg; TrackSet tracks; while (!hits.empty()) { Track* track = bufEnd++; new (track) Track; StHit* hit = *hits.begin(); track->push_back(hit); hits.erase(hits.begin()); // Compute initial centroid double sumX = hit->position().x(); double sumY = hit->position().y(); double meanX = sumX; double meanY = sumY; // Add hits within MAX_R_DISTANCE of centroid to track for (HitSetIter i = hits.begin(); i != hits.end();) { StHit* hit = *i; double dz = hit->position().z() - track->lastHit()->position().z(); if (fabs(dz) > MAX_Z_DISTANCE) break; double dx = meanX - hit->position().x(); double dy = meanY - hit->position().y(); double dr = hypot(dx, dy); if (dr < MAX_R_DISTANCE) { track->push_back(hit); HitSetIter next = i; ++next; hits.erase(i); i = next; // Update centroid sumX += hit->position().x(); sumY += hit->position().y(); meanX = sumX / track->size(); meanY = sumY / track->size(); } else { ++i; } } tracks.insert(track); } info() << tracks.size() << " track seeds found" << endm; // // Pick only track seeds with at least MIN_TRACK_SEED_HITS hits. // The others are put back in the set of available hits. // info() << "Removing track seeds with less than " << MIN_TRACK_SEED_HITS << " hits" << endm; for (TrackSetIter i = tracks.begin(); i != tracks.end();) { Track* track = *i; if (track->size() < MIN_TRACK_SEED_HITS) { for (Track::iterator j = track->begin(); j != track->end(); ++j) { StHit* hit = *j; hits.insert(hit); } TrackSetIter next = i; ++next; tracks.erase(i); i = next; } else { ++i; } } info() << tracks.size() << " track seeds left with " << MIN_TRACK_SEED_HITS << " hits or more" << endm; // // Try to fit track seeds to straight tracks by doing // parallel linear regression analyses in xz and yz. // info("Find linear tracks"); vector<Track*> linearTracks; for (TrackSetIter i = tracks.begin(); i != tracks.end(); ++i) { Track* track = *i; if (track->fit() && track->ok()) { // // Try to extend the straight track by looking for hits in the // pool of available hits that are within 5 cm of the centroid // of the track in the xy-plane. // for (HitSetIter j = hits.begin(); j != hits.end();) { StHit* hit = *j; if (track->accept(hit)) { track->push_back(hit); // Move added hit to its proper place nth_element(track->begin(), track->rbegin().base(), track->end(), LessHit()); track->fit(); HitSetIter next = j; ++next; hits.erase(j); j = next; } else { ++j; } } linearTracks.push_back(track); } } info() << linearTracks.size() << " linear tracks found" << endm; // // Merge linear tracks if both end points of the first track // are within 5 cm of the centroid of the track in the xy-plane. // info("Start merging tracks"); for (unsigned int i = 0; i < linearTracks.size(); ++i) { if (!linearTracks[i]) continue; for (unsigned int j = i + 1; j < linearTracks.size(); ++j) { if (!linearTracks[j]) continue; if (linearTracks[i]->accept(linearTracks[j]->firstHit()) && linearTracks[i]->accept(linearTracks[j]->lastHit())) { linearTracks[i]->merge(linearTracks[j]); linearTracks[j] = 0; } } } // // Compress vector of linear tracks (remove null entries) // linearTracks.erase(remove(linearTracks.begin(), linearTracks.end(), (Track*)0), linearTracks.end()); info() << linearTracks.size() << " merged tracks" << endm; // // Refit and remove outliers. // info("Refit and remove outliers"); for (unsigned int i = 0; i < linearTracks.size(); ++i) { Track* track = linearTracks[i]; if (track->fit()) { for (Track::iterator j = track->begin(); j != track->end();) { StHit* hit = *j; if (track->accept(hit)) { ++j; } else { j = track->erase(j); hits.insert(hit); } } } } info() << hits.size() << " unused TPC hits" << endm; // // Number of hits in linear tracks // int nHits = 0; for (unsigned int i = 0; i < linearTracks.size(); ++i) nHits += linearTracks[i]->size(); info() << nHits << " TPC hits in linear tracks" << endm; // // Track to StTrack conversion. // // Find the highest track key. Increment successively to assign // to new tracks. // info("Converting Track to StTrack"); Int_t key = 0; for (unsigned int i = 0; i < event->trackNodes().size(); ++i) { Int_t key2 = event->trackNodes()[i]->track(global)->key(); if (key < key2) key = key2; } Int_t nStTrack = 0; for (unsigned int i = 0; i < linearTracks.size(); ++i) { if (pileup(linearTracks[i])) continue; StTrack* track = createStTrack(linearTracks[i]); StTrackNode* trackNode = new StTrackNode; track->setKey(++key); trackNode->addTrack(track); event->trackNodes().push_back(trackNode); event->trackDetectorInfo().push_back(track->detectorInfo()); ++nStTrack; } info() << nStTrack << " StTrack saved" << endm; // // Clean up // for (Track* track = bufBeg; track != bufEnd; ++track) track->~Track(); free(bufBeg); return kStOk; } StTrack* StBeamBackMaker::createStTrack(Track* track) { StTrack* gTrack = new StGlobalTrack; gTrack->setLength(track->length()); gTrack->setFlag(901); // Inner geometry StThreeVectorF origin(track->x0(), track->y0(), 0); StThreeVectorF momentum(track->dxdz(), track->dydz(), 1); Line line(origin, momentum); momentum.setMag(999); // Bogus double dipAngle = atan2(1, hypot(track->dxdz(), track->dydz())); gTrack->setGeometry(new StHelixModel(-1, // Charge M_PI_2, // Psi 0, // Curvature dipAngle, // Dip angle line.perigee(track->firstHit()->position()), // Origin momentum, // Momentum 1)); // Helicity gTrack->setEncodedMethod(kLine2StepId); // Outer geometry StTrackGeometry* outerGeometry = gTrack->geometry()->copy(); outerGeometry->setOrigin(line.perigee(track->lastHit()->position())); gTrack->setOuterGeometry(outerGeometry); // Detector info StTrackDetectorInfo* detInfo = new StTrackDetectorInfo; detInfo->setFirstPoint(track->firstHit()->position()); detInfo->setLastPoint(track->lastHit()->position()); for (Track::iterator i = track->begin(); i != track->end(); ++i) detInfo->addHit(*i); // Number of points cannot be larger than 255 (unsigned char) detInfo->setNumberOfPoints(track->size() < 256 ? track->size() : 255, kTpcId); gTrack->setDetectorInfo(detInfo); // Fit traits StTrackFitTraits fitTraits; // Number of fit points cannot be larger than 255 (unsigned char) fitTraits.setNumberOfFitPoints(track->size() < 256 ? track->size() : 255, kTpcId); gTrack->setFitTraits(fitTraits); return gTrack; } inline bool StBeamBackMaker::pileup(Track* track) const { TopologyMap topoMap(track); return (topoMap.nearEast() < 4 || topoMap.farEast() < 4 || topoMap.nearWest() < 4 || topoMap.farWest() < 4); } inline ostream& StBeamBackMaker::info(const Char_t* message) { if (message) return gMessMgr->Info(Form("%s: %s", GetName(), message)); return gMessMgr->Info() << GetName() << ": "; } inline ostream& StBeamBackMaker::warning(const Char_t* message) { if (message) return gMessMgr->Warning(Form("%s: %s", GetName(), message)); return gMessMgr->Warning() << GetName() << ": "; }
28.544118
105
0.618547
[ "geometry", "vector" ]
f1fc13d2c4884905a7f46861d91acb63d99d986f
1,392
cpp
C++
src/Parsers/Kusto/ParserKQLTable.cpp
DevTeamBK/ClickHouse
f65b5d21594a07afb017a7cdaa718c5d1caa257d
[ "Apache-2.0" ]
null
null
null
src/Parsers/Kusto/ParserKQLTable.cpp
DevTeamBK/ClickHouse
f65b5d21594a07afb017a7cdaa718c5d1caa257d
[ "Apache-2.0" ]
1
2021-12-22T12:08:09.000Z
2021-12-22T12:08:09.000Z
src/Parsers/Kusto/ParserKQLTable.cpp
DevTeamBK/ClickHouse
f65b5d21594a07afb017a7cdaa718c5d1caa257d
[ "Apache-2.0" ]
null
null
null
#include <Parsers/ASTLiteral.h> #include <Parsers/IParserBase.h> #include <Parsers/ParserTablesInSelectQuery.h> #include <Parsers/Kusto/ParserKQLQuery.h> #include <Parsers/Kusto/ParserKQLTable.h> namespace DB { bool ParserKQLTable :: parsePrepare(Pos & pos) { if (!op_pos.empty()) return false; op_pos.push_back(pos); return true; } bool ParserKQLTable :: parseImpl(Pos & pos, ASTPtr & node, Expected & expected) { std::unordered_set<String> sql_keywords ({ "SELECT", "INSERT", "CREATE", "ALTER", "SYSTEM", "SHOW", "GRANT", "REVOKE", "ATTACH", "CHECK", "DESCRIBE", "DESC", "DETACH", "DROP", "EXISTS", "KILL", "OPTIMIZE", "RENAME", "SET", "TRUNCATE", "USE", "EXPLAIN" }); if (op_pos.empty()) return false; auto begin = pos; pos = op_pos.back(); String table_name(pos->begin,pos->end); String table_name_upcase(table_name); std::transform(table_name_upcase.begin(), table_name_upcase.end(),table_name_upcase.begin(), toupper); if (sql_keywords.find(table_name_upcase) != sql_keywords.end()) return false; if (!ParserTablesInSelectQuery().parse(pos, node, expected)) return false; pos = begin; return true; } }
20.173913
106
0.578305
[ "transform" ]
7b0a804103aa2f6e2c5eb219f279bde8239f294e
443
cpp
C++
src/Game.cpp
guiteixeirapimentel/eulerEquationsOnline
a331d73d1b334779520ceebec4af2acc0d019c83
[ "MIT" ]
null
null
null
src/Game.cpp
guiteixeirapimentel/eulerEquationsOnline
a331d73d1b334779520ceebec4af2acc0d019c83
[ "MIT" ]
null
null
null
src/Game.cpp
guiteixeirapimentel/eulerEquationsOnline
a331d73d1b334779520ceebec4af2acc0d019c83
[ "MIT" ]
null
null
null
#include "Game.h" #include <iostream> Game::Game(Keyboard &kbd) : cKeyboard(kbd), cGraphics(800, 600) { } Game::~Game() { } void Game::Tick() { Input(); Update(); cGraphics.Init(); Render(); cGraphics.Present(); } void Game::Update() { } void Game::Render() { } void Game::Input() { Keyboard::KeyEvent ev; while ((ev = cKeyboard.PeekAndPopEvent())) { // do events } }
10.302326
46
0.534989
[ "render" ]
7b1ee669b1e4775d23c2ac2debf397e16dec6a7c
5,242
cpp
C++
src/lfpRatiometer.cpp
stanley-rozell/lfp-cpp-library
a00a2ea67a373c869c99d6f37108c83397a4bd78
[ "Apache-2.0" ]
null
null
null
src/lfpRatiometer.cpp
stanley-rozell/lfp-cpp-library
a00a2ea67a373c869c99d6f37108c83397a4bd78
[ "Apache-2.0" ]
null
null
null
src/lfpRatiometer.cpp
stanley-rozell/lfp-cpp-library
a00a2ea67a373c869c99d6f37108c83397a4bd78
[ "Apache-2.0" ]
1
2021-03-17T18:33:09.000Z
2021-03-17T18:33:09.000Z
#include <lfpRatiometer> using namespace std; // defining what's in the object's constructor // user defines time window length (in samples) and sampling rate lfpRatiometer::lfpRatiometer(int N_input, double sampling_input) { // setting user defined variables N=N_input; f_size=N/2 + 1; sampling=sampling_input; // setting default variables lf_low = 1; lf_high = 25; hf_low = 30; hf_high = 90; // setting default window window_rect(); // establishing frequencies that will be associated with DFT output for (int n=0; n<f_size;n++){ allfreqs.push_back(sampling*n/N); } // allocating space for input time array in = (double*) fftw_malloc(sizeof(double)*N); // allocating space for N DFT terms // note: this has to be N, not N/2 + 1, for fftw_free() out = fftw_alloc_complex(N); // creating the FFTW3 plan // FFTW_MEASURE makes initialization long for faster... // calculations p = fftw_plan_dft_r2c_1d(N,in,out,FFTW_MEASURE); } // defining what's in the object's destructor lfpRatiometer::~lfpRatiometer(void) { // destroy plan fftw_destroy_plan(p); // free output array fftw_free(out); // free input array fftw_free(in); return; } // this function changes the FFT plan (previously defined in the constructor) // the existence of this function is very imperfect // this function probably shouldn't be used except for the RTXI plugin void lfpRatiometer::changeFFTPlan(int N_input, double sampling_input) { // destroying previous FFT plan (similar to destructor) fftw_destroy_plan(p); fftw_free(out); fftw_free(in); // making new plan (similar to constructor) N=N_input; f_size=N/2 + 1; sampling=sampling_input; allfreqs.clear(); for (int n=0; n<f_size;n++){ allfreqs.push_back(sampling*n/N); } in = (double*) fftw_malloc(sizeof(double)*N); out = fftw_alloc_complex(N); p = fftw_plan_dft_r2c_1d(N,in,out,FFTW_MEASURE); } // allows users to set ends of LF&HF bands void lfpRatiometer::setRatioParams(double lf_low_input, double lf_high_input, double hf_low_input, double hf_high_input) { lf_low = lf_low_input; lf_high = lf_high_input; hf_low = hf_low_input; hf_high = hf_high_input; } // allows users to push a new time series data point void lfpRatiometer::pushTimeSample(double input) { in_raw.push_back(input); if (in_raw.size() > N) { // cut it to size in_raw.erase(in_raw.begin()); } } // allows users to clear the raw time series void lfpRatiometer::clrTimeSeries() { in_raw.clear(); } // allows users to input a specific sequence of time series data void lfpRatiometer::setTimeSeries(std::vector<double> inputSeries) { clrTimeSeries(); // we require that the input time series be of the appropriate size if (inputSeries.size() == N) { in_raw = inputSeries; } } // method sets window as rectangle void lfpRatiometer::window_rect() { window.clear(); s2 = 0; for (int j=0; j<N; j++){ double val = 1; window.push_back(val); s2 = s2 + val*val; } } // method sets window as Hamming // supposed to be consistent with MATLAB hamming() function void lfpRatiometer::window_hamming(){ window.clear(); s2 = 0; double pi = atan(1) * 4; for (int j=0; j<N; j++){ double z = 2*pi*j/(N-1); double val = 0.54 - 0.46*cos(z); window.push_back(val); s2 = s2 + val*val; } } // function that calculates the LF/HF ratio void lfpRatiometer::calcRatio() { // only calculate if the input vector is full if (in_raw.size() == N) { makePSD(); lf_total = 0; hf_total = 0; // iterates over PSD, calculating running sums in each band for (int n=0; n<f_size; n++){ if (allfreqs.at(n)>= lf_low && allfreqs.at(n) <= lf_high) { lf_total = lf_total + psd.at(n); } if (allfreqs.at(n) >= hf_low && allfreqs.at(n) <= hf_high){ hf_total = hf_total + psd.at(n); } } // take ratio lf_hf_ratio = lf_total/hf_total; } // else {lf_hf_ratio = nan("");} else {lf_hf_ratio = -1;} } // function that calculates the power spectral density void lfpRatiometer::makePSD() { psd.clear(); // clear vector which stores PSD // applying window for (int n=0; n<N; n++){ in[n] = in_raw[n]*window[n]; } fftw_execute(p); // FFTW3 calculate the DFT // loop through DFT entries for (int n=0; n<f_size; n++){ // calculate |y_n|^2 double fftsqr = out[n][0]*out[n][0] + out[n][1]*out[n][1]; // calculate PSD (described in Heinzel et al., 2002) // DC & Nyquist freq is scaled to be consistent with MATLAB's spectrogram // Usually, the edges should not matter because all frequencies of interest // should be contained in the interior // WILL CHANGE WITH WINDOWING if (n==0 || n==f_size-1) { psd.push_back((1/(sampling*s2)) * fftsqr); } else { psd.push_back(2*(1/(sampling*s2)) * fftsqr); } } }
27.302083
122
0.622091
[ "object", "vector" ]
7b24c074ff692ae86caea445470c53bc8cdf0a19
543
cpp
C++
test/graph/topological_sort.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
1
2021-12-26T14:17:29.000Z
2021-12-26T14:17:29.000Z
test/graph/topological_sort.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
3
2020-07-13T06:23:02.000Z
2022-02-16T08:54:26.000Z
test/graph/topological_sort.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
null
null
null
/* * @brief グラフ/トポロジカルソート */ #define IGNORE #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_B" #include <iostream> #include <vector> #include "../../graph/edge.hpp" #include "../../graph/topological_sort.hpp" int main() { int v, e; std::cin >> v >> e; std::vector<std::vector<Edge<bool>>> graph(v); while (e--) { int s, t; std::cin >> s >> t; graph[s].emplace_back(s, t); } for (const int ver : topological_sort(graph)) std::cout << ver << '\n'; return 0; }
22.625
83
0.581952
[ "vector" ]
7b2622ae6c4ed8c2f361a555d1c4b5b9ee6a2db7
654
cpp
C++
pytorch/lib/pointops/src/sampling/sampling_cuda.cpp
beihaifusang/contrastBoundary
d784854b3a074bf4aa502fad676f6f1022f0edbf
[ "MIT" ]
20
2022-03-11T02:35:05.000Z
2022-03-25T12:13:08.000Z
examples/PointTransformer/pointops/src/sampling/sampling_cuda.cpp
zarzarj/MinkowskiEngine
1c1c09d23bd2147fa41cae25fa8837290c2bd07b
[ "MIT" ]
4
2022-03-28T11:37:11.000Z
2022-03-31T16:02:57.000Z
examples/PointTransformer/pointops/src/sampling/sampling_cuda.cpp
zarzarj/MinkowskiEngine
1c1c09d23bd2147fa41cae25fa8837290c2bd07b
[ "MIT" ]
5
2022-03-11T07:56:22.000Z
2022-03-31T11:33:11.000Z
#include <vector> #include <THC/THC.h> #include <torch/serialize/tensor.h> #include <ATen/cuda/CUDAContext.h> #include "sampling_cuda_kernel.h" void furthestsampling_cuda(int b, int n, at::Tensor xyz_tensor, at::Tensor offset_tensor, at::Tensor new_offset_tensor, at::Tensor tmp_tensor, at::Tensor idx_tensor) { const float *xyz = xyz_tensor.data_ptr<float>(); const int *offset = offset_tensor.data_ptr<int>(); const int *new_offset = new_offset_tensor.data_ptr<int>(); float *tmp = tmp_tensor.data_ptr<float>(); int *idx = idx_tensor.data_ptr<int>(); furthestsampling_cuda_launcher(b, n, xyz, offset, new_offset, tmp, idx); }
38.470588
165
0.730887
[ "vector" ]
7b29653bba3fd8f8afcf650434cf356a3fa6d86e
5,049
cpp
C++
include/GraphCut3D/Examples/KrcahGraphcut.cpp
ypauchard/ITK-KrcahSheetnessImageFilter
4b118a1b12dab22a0ff623003100eafc0f8e5382
[ "BSD-3-Clause" ]
3
2017-03-08T20:38:43.000Z
2019-04-10T09:30:46.000Z
include/GraphCut3D/Examples/KrcahGraphcut.cpp
thewtex/ITKKrcahSheetness
4b118a1b12dab22a0ff623003100eafc0f8e5382
[ "BSD-3-Clause" ]
5
2016-10-14T17:46:16.000Z
2017-10-04T03:10:05.000Z
include/GraphCut3D/Examples/KrcahGraphcut.cpp
thewtex/ITKKrcahSheetness
4b118a1b12dab22a0ff623003100eafc0f8e5382
[ "BSD-3-Clause" ]
1
2017-08-02T19:26:17.000Z
2017-08-02T19:26:17.000Z
/** * Image GraphCut 3D Segmentation * * Copyright (c) 2016, Zurich University of Applied Sciences, School of Engineering, T. Fitze, Y. Pauchard * * Licensed under GNU General Public License 3.0 or later. * Some rights reserved. */ #include "ImageGraphCut3DFilter.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" /** This example segments an image and writes the segmentation mask to a file. * It can operate on a 3D image with one component per dimension (i.e. * grayscale). */ int main(int argc, char *argv[]) { // Verify arguments if (argc != 7) { std::cerr << "Required: image.mhd foregroundMask.mhd backgroundMask.mhd output.mhd sigma lambda" << std::endl; std::cerr << "image.mhd: 3D image sheetness measure -1.0 to 1.0" << std::endl; std::cerr << "foregroundMask.mhd: 3D image non-zero pixels indicating foreground and 0 elsewhere" << std::endl; std::cerr << "backgroundMask.mhd: 3D image non-zero pixels indicating background and 0 elsewhere" << std::endl; std::cerr << "output.mhd: 3D image resulting segmentation" << std::endl; std::cerr << " Foreground as 127 and Background as 255" << std::endl; std::cerr << "sigma estimated noise in boundary term, try 0.2" << std::endl; std::cerr << "lambda boundary term weight, try 5.0" << std::endl; return EXIT_FAILURE; } // Parse arguments std::string imageFilename = argv[1]; std::string foregroundFilename = argv[2]; // This image should have non-zero pixels indicating foreground pixels and 0 elsewhere. std::string backgroundFilename = argv[3]; // This image should have non-zero pixels indicating background pixels and 0 elsewhere. std::string outputFilename = argv[4]; double sigma = atof(argv[5]); // Noise parameter double lambda = atof(argv[6]); // Boundary term weight // Print arguments std::cout << "imageFilename: " << imageFilename << std::endl << "foregroundFilename: " << foregroundFilename << std::endl << "backgroundFilename: " << backgroundFilename << std::endl << "outputFilename: " << outputFilename << std::endl << "sigma: " << sigma << std::endl << "lambda: " << lambda << std::endl; // Define all image types typedef itk::Image<float, 3> ImageType; typedef itk::Image<unsigned char, 3> ForegroundMaskType; typedef itk::Image<unsigned char, 3> BackgroundMaskType; typedef itk::Image<unsigned char, 3> OutputImageType; // Read the image std::cout << "*** Reading image ***" << std::endl; typedef itk::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(imageFilename); // Read the foreground and background masks std::cout << "*** Reading foreground mask ***" << std::endl; typedef itk::ImageFileReader<ForegroundMaskType> ForegroundMaskReaderType; ForegroundMaskReaderType::Pointer foregroundMaskReader = ForegroundMaskReaderType::New(); foregroundMaskReader->SetFileName(foregroundFilename); std::cout << "*** Reading background mask ***" << std::endl; typedef itk::ImageFileReader<BackgroundMaskType> BackgroundMaskReaderType; BackgroundMaskReaderType::Pointer backgroundMaskReader = BackgroundMaskReaderType::New(); backgroundMaskReader->SetFileName(backgroundFilename); // Set up the graph cut typedef itk::ImageGraphCut3DFilter<ImageType, ForegroundMaskType, BackgroundMaskType, OutputImageType> GraphCutFilterType; GraphCutFilterType::Pointer graphCutFilter = GraphCutFilterType::New(); graphCutFilter->SetInputImage(reader->GetOutput()); graphCutFilter->SetForegroundImage(foregroundMaskReader->GetOutput()); graphCutFilter->SetBackgroundImage(backgroundMaskReader->GetOutput()); // Set graph cut parameters graphCutFilter->SetVerboseOutput(true); graphCutFilter->SetSigma(sigma); graphCutFilter->SetBoundaryDirectionTypeToBrightDark(); graphCutFilter->SetLambda(lambda); // Define the color values of the output graphCutFilter->SetForegroundPixelValue(1); graphCutFilter->SetBackgroundPixelValue(0); // Start the computation std::cout << "*** Performing Graph Cut ***" << std::endl; graphCutFilter->Update(); // Get and write the result std::cout << "*** Writing Result ***" << std::endl; typedef itk::ImageFileWriter<GraphCutFilterType::OutputImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputFilename); writer->SetInput(graphCutFilter->GetOutput()); try { std::cout << "Writing output image " << outputFilename << std::endl; writer->Update(); } catch (itk::ExceptionObject &err) { std::cerr << "ERROR: Exception caught while writing output image" << std::endl; std::cerr << err << std::endl; } }
45.9
135
0.673401
[ "3d" ]
7b2baee3830217dd2f03df930417428ee89b457e
9,124
cpp
C++
ray-tracer/shape.cpp
mikeswhitney33/ray-nbow
c916a757401c14749818b463158e185eed63f914
[ "MIT" ]
null
null
null
ray-tracer/shape.cpp
mikeswhitney33/ray-nbow
c916a757401c14749818b463158e185eed63f914
[ "MIT" ]
3
2021-09-08T01:53:36.000Z
2022-03-12T00:24:36.000Z
ray-tracer/shape.cpp
mikeswhitney33/ray-nbow
c916a757401c14749818b463158e185eed63f914
[ "MIT" ]
null
null
null
#include "shape.hpp" namespace rt { Triangle::Triangle(const vec3 &a, const vec3 &b, const vec3 &c):a(a),b(b),c(c) {} bool Triangle::intersect(const Ray &ray, float &t) const { vec3 ab = b - a; vec3 ac = c - a; vec3 pvec = cross(ray.dir, ac); float det = dot(ab, pvec); if(fabs(det) < std::numeric_limits<float>::epsilon()) return false; float idet = 1 / det; vec3 tvec = ray.orig - a; float u = dot(tvec, pvec) * idet; if(u < 0 || u > 1) return false; vec3 qvec = cross(tvec, ab); float v = dot(ray.dir, qvec) * idet; if(v < 0 || u + v > 1) return false; float t0 = dot(ac, qvec) * idet; if(t0 > t) return false; t = t0; return true; } void Triangle::extents(vec3 &emin, vec3 &emax) const { vec3 abcx = {a.x, b.x, c.x}; vec3 abcy = {a.y, b.y, c.y}; vec3 abcz = {a.z, b.z, c.z}; emin = { min(abcx), min(abcy), min(abcz) }; emax = { max(abcx), max(abcy), max(abcz) }; } Sphere::Sphere(const vec3 &c, const float &r):center(c), radius(r),radius2(r*r) {} bool Sphere::intersect(const Ray &ray, float &t) const { vec3 L = center - ray.orig; float tca = dot(L, ray.dir); if(tca < 0) return false; // ray is facing the wrong way float d2 = dot(L, L) - tca * tca; if(d2 > radius2) return false; // ray misses the sphere float thc = sqrt(radius2 - d2); float t0 = tca - thc; float t1 = tca + thc; if(t0 > t1) std::swap(t0, t1); if(t0 < 0) t0 = t1; // we are inside the sphere if(t0 < 0 || t0 > t) return false; // the sphere is behind us or another shape is infront of it. t = t0; return true; } void Sphere::extents(vec3 &emin, vec3 &emax) const { emin = {center.x - radius, center.y - radius, center.z - radius}; emax = {center.x + radius, center.y + radius, center.z + radius}; } BoundingBox::BoundingBox(Shape *s):shape(s) { shape->extents(bounds[0], bounds[1]); } bool BoundingBox::intersect(const Ray &ray, float &t) const { if(raybox(ray, bounds)) { return shape->intersect(ray, t); } return false; } void BoundingBox::extents(vec3 &emin, vec3 &emax) const { emin = bounds[0]; emax = bounds[1]; } bool raybox(const Ray &ray, const vec3 bounds[2], float &t) { float tmin, tmax, tymin, tymax, tzmin, tzmax; tmin = (bounds[ray.sign[0]].x - ray.orig.x) * ray.invdir.x; tmax = (bounds[1 - ray.sign[0]].x - ray.orig.x) * ray.invdir.x; tymin = (bounds[ray.sign[1]].y - ray.orig.y) * ray.invdir.y; tymax = (bounds[1 - ray.sign[1]].y - ray.orig.y) * ray.invdir.y; if((tmin > tymax) || tymin > tmax) { return false; } if(tymin > tmin) { tmin = tymin; } if(tymax < tmax) { tmax = tymax; } tzmin = (bounds[ray.sign[2]].z - ray.orig.z) * ray.invdir.z; tzmax = (bounds[1 - ray.sign[2]].z - ray.orig.z) * ray.invdir.z; if((tmin > tzmax) || (tzmin > tmax)) { return false; } if(tzmin > tmin) { tmin = tzmin; } if(tzmax < tmax) { tmax = tzmax; } float t0 = tmin; if(t0 < 0) { t0 = tmax; if(t0 < 0) return false; } if(t0 > t) return false; t = t0; return true; } bool raybox(const Ray &ray, const vec3 bounds[2]) { float t = std::numeric_limits<float>::max(); return raybox(ray, bounds, t); } bool LinearContainer::intersect(const Ray &ray, float &t) const { bool hit = false; for(auto s : shapes) { if(s->intersect(ray, t)) { hit = true; } } return hit; } void LinearContainer::addShape(Shape *shape) { shapes.push_back(shape); } size_t LinearContainer::size() const { return shapes.size(); } bool MassBoxContainer::intersect(const Ray &ray, float &t) const { if(size() == 0) return false; if(!raybox(ray, bounds, t)) return false; t = std::numeric_limits<float>::max(); return shapes.intersect(ray, t); } void MassBoxContainer::addShape(Shape *shape) { if(size() == 0) { shape->extents(bounds[0], bounds[1]); } else { vec3 emin, emax; shape->extents(emin, emax); bounds[0].x = std::min(emin.x, bounds[0].x); bounds[0].y = std::min(emin.y, bounds[0].y); bounds[0].z = std::min(emin.z, bounds[0].z); bounds[1].x = std::max(emax.x, bounds[1].x); bounds[1].y = std::max(emax.y, bounds[1].y); bounds[1].z = std::max(emax.z, bounds[1].z); } shapes.addShape(shape); } size_t MassBoxContainer::size() const { return shapes.size(); } constexpr size_t OctreeNode::MAX_SIZE; constexpr size_t OctreeNode::MAX_DEPTH; OctreeNode::OctreeNode(const vec3 &emin, const vec3 &emax, size_t depth):depth(depth) { center = (emin + emax) / 2; bounds[0] = emin; bounds[1] = emax; } bool boxbox(const vec3 bounds1[2], const vec3 bounds2[2]) { return bounds1[0].x <= bounds2[1].x && bounds1[1].x >= bounds2[0].x && bounds1[0].y <= bounds2[1].y && bounds1[1].y >= bounds2[0].y && bounds1[0].z <= bounds2[1].z && bounds1[1].z >= bounds2[0].z; } bool OctreeNode::intersect(const Ray &ray, float &t) const { bool hit = false; if(children.size() == 0) { for(size_t i = 0;i < content.size();i++) { if(content[i]->intersect(ray, t)) { hit = true; } } } for(size_t i = 0;i < children.size();i++) { if(children[i].intersect(ray, t)) { hit = true; } } return hit; } bool OctreeNode::intersect(Shape *shape) const { vec3 emin, emax; shape->extents(emin, emax); vec3 bounds2[2] = {emin, emax}; return boxbox(bounds, bounds2); } void OctreeNode::addShape(Shape *shape) { if(children.size() == 0) { content.push_back(shape); if(content.size() >= MAX_SIZE && depth < MAX_DEPTH) { split(); } } else { for(auto &child : children) { if(child.intersect(shape)) { child.addShape(shape); } } } } void OctreeNode::split() { vec3 qpppnear, qnppnear, qpnpnear, qppnnear, qnnpnear, qnpnnear, qpnnnear, qnnnnear; vec3 qpppfar, qnppfar, qpnpfar, qppnfar, qnnpfar, qnpnfar, qpnnfar, qnnnfar; qpppnear = center; qnppnear = {bounds[0].x, center.y, center.z}; qpnpnear = {center.x, bounds[0].y, center.z}; qppnnear = {center.x, center.y, bounds[0].z}; qnnpnear = {bounds[0].x, bounds[0].y, center.z}; qnpnnear = {bounds[0].x, center.y, bounds[0].z}; qpnnnear = {center.x, bounds[0].y, bounds[0].z}; qnnnnear = {bounds[0].x, bounds[0].y, bounds[0].z}; qpppfar = bounds[1]; qnnnfar = center; qnppfar = {center.x, bounds[1].y, bounds[1].z}; qpnpfar = {bounds[1].x, center.y, bounds[1].z}; qppnfar = {bounds[1].x, bounds[1].y, center.z}; qnnpfar = {center.x, center.y, bounds[1].z}; qnpnfar = {center.x, bounds[1].y, center.z}; qpnnfar = {bounds[1].x, center.y, center.z}; children.push_back(OctreeNode(qpppnear, qpppfar, depth+1)); children.push_back(OctreeNode(qnppnear, qnppfar, depth+1)); children.push_back(OctreeNode(qpnpnear, qpnpfar, depth+1)); children.push_back(OctreeNode(qppnnear, qppnfar, depth+1)); children.push_back(OctreeNode(qnnpnear, qnnpfar, depth+1)); children.push_back(OctreeNode(qnpnnear, qnpnfar, depth+1)); children.push_back(OctreeNode(qpnnnear, qpnnfar, depth+1)); children.push_back(OctreeNode(qnnnnear, qnnnfar, depth+1)); for(auto shape : content) { vec3 emin, emax; shape->extents(emin, emax); vec3 ebounds[2] = {emin, emax}; for(auto &child : children) { if(boxbox(child.bounds, ebounds)) { child.addShape(shape); } } } } };
28.873418
104
0.491451
[ "shape" ]
7b31fcc76d0e9930dd1e6a8547ff2acb686c9df7
19,667
cpp
C++
source/Irrlicht/CD3D9Texture.cpp
Ciapas-Linux/irrlicht-ogles
07bce7448a0714c62475489bc01ce719cb87ace0
[ "IJG" ]
2
2020-11-04T03:17:13.000Z
2020-11-28T23:19:26.000Z
source/Irrlicht/CD3D9Texture.cpp
Ciapas-Linux/irrlicht-ogles
07bce7448a0714c62475489bc01ce719cb87ace0
[ "IJG" ]
2
2020-01-28T08:36:22.000Z
2020-02-01T10:52:04.000Z
source/Irrlicht/CD3D9Texture.cpp
Ciapas-Linux/irrlicht-ogles
07bce7448a0714c62475489bc01ce719cb87ace0
[ "IJG" ]
1
2019-09-05T05:39:18.000Z
2019-09-05T05:39:18.000Z
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_DIRECT3D_9_ #include "CD3D9Texture.h" #include "CD3D9Driver.h" #include "os.h" namespace irr { namespace video { CD3D9Texture::CD3D9Texture(const io::path& name, const core::array<IImage*>& image, E_TEXTURE_TYPE type, CD3D9Driver* driver) : ITexture(name, type), Driver(driver), InternalFormat(D3DFMT_UNKNOWN), LockReadOnly(false), LockData(0), LockLayer(0), MipLevelLocked(0), HardwareMipMaps(false), Device(0), Texture(0), CubeTexture(0), RTTSurface(0) { #ifdef _DEBUG setDebugName("CD3D9Texture"); #endif IRR_DEBUG_BREAK_IF(image.size() == 0) Device=driver->getExposedVideoData().D3D9.D3DDev9; if (Device) Device->AddRef(); DriverType = Driver->getDriverType(); HasMipMaps = Driver->getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); HardwareMipMaps = Driver->getTextureCreationFlag(ETCF_AUTO_GENERATE_MIP_MAPS) && Driver->queryFeature(EVDF_MIP_MAP_AUTO_UPDATE); getImageValues(image[0]); DWORD flags = 0; LPDIRECT3D9 intf = Driver->getExposedVideoData().D3D9.D3D9; D3DDISPLAYMODE d3ddm; intf->GetAdapterDisplayMode(Driver->Params.DisplayAdapter, &d3ddm); if (HasMipMaps && HardwareMipMaps) { if (D3D_OK == intf->CheckDeviceFormat(Driver->Params.DisplayAdapter, D3DDEVTYPE_HAL, d3ddm.Format, D3DUSAGE_AUTOGENMIPMAP, D3DRTYPE_TEXTURE, InternalFormat)) flags = D3DUSAGE_AUTOGENMIPMAP; else HardwareMipMaps = false; } VertexTextureSupport = Driver->getTextureCreationFlag(ETCF_SUPPORT_VERTEXT_TEXTURE) && (D3D_OK == intf->CheckDeviceFormat(Driver->Params.DisplayAdapter, D3DDEVTYPE_HAL, d3ddm.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, InternalFormat)); HRESULT hr = 0; switch (Type) { case ETT_2D: hr = Device->CreateTexture(Size.Width, Size.Height, HasMipMaps ? 0 : 1, flags, InternalFormat, D3DPOOL_MANAGED, &Texture, NULL); break; case ETT_CUBEMAP: hr = Device->CreateCubeTexture(Size.Width, HasMipMaps ? 0 : 1, flags, InternalFormat, D3DPOOL_MANAGED, &CubeTexture, NULL); break; default: IRR_DEBUG_BREAK_IF(true) break; } if (FAILED(hr)) { // Try again with 16-bit format if (InternalFormat == D3DFMT_A8R8G8B8) { InternalFormat = D3DFMT_A1R5G5B5; ColorFormat = ECF_A1R5G5B5; } else if (InternalFormat == D3DFMT_R8G8B8) // (24 bit is usually failing in d3d9, not sure if it's ever supported) { InternalFormat = D3DFMT_R5G6B5; ColorFormat = ECF_R5G6B5; } switch (Type) { case ETT_2D: hr = Device->CreateTexture(Size.Width, Size.Height, HasMipMaps ? 0 : 1, flags, InternalFormat, D3DPOOL_MANAGED, &Texture, NULL); break; case ETT_CUBEMAP: hr = Device->CreateCubeTexture(Size.Width, HasMipMaps ? 0 : 1, flags, InternalFormat, D3DPOOL_MANAGED, &CubeTexture, NULL); break; } } core::array<IImage*> tmpImage = image; bool releaseImageData = false; if (SUCCEEDED(hr)) { if (OriginalSize != Size || OriginalColorFormat != ColorFormat) { releaseImageData = true; for (u32 i = 0; i < image.size(); ++i) { tmpImage[i] = Driver->createImage(ColorFormat, Size); if (image[i]->getDimension() == Size) image[i]->copyTo(tmpImage[i]); else image[i]->copyToScaling(tmpImage[i]); } } for (u32 i = 0; i < tmpImage.size(); ++i) uploadTexture(tmpImage[i]->getData(), 0, i); bool autoGenerateRequired = true; for (u32 i = 0; i < tmpImage.size(); ++i) { void* mipmapsData = tmpImage[i]->getMipMapsData(); if (autoGenerateRequired || mipmapsData) regenerateMipMapLevels(mipmapsData, i); if (!mipmapsData) autoGenerateRequired = false; } } else { switch (hr ) { case D3DERR_INVALIDCALL: os::Printer::log("Could not create DIRECT3D9 Texture. D3DERR_INVALIDCALL", ELL_WARNING); break; case D3DERR_OUTOFVIDEOMEMORY: os::Printer::log("Could not create DIRECT3D9 Texture. D3DERR_OUTOFVIDEOMEMORY", ELL_WARNING); break; case E_OUTOFMEMORY: os::Printer::log("Could not create DIRECT3D9 Texture. E_OUTOFMEMORY", ELL_WARNING); break; default: os::Printer::log("Could not create DIRECT3D9 Texture.", ELL_WARNING); } } if (releaseImageData) { for (u32 i = 0; i < tmpImage.size(); ++i) tmpImage[i]->drop(); } } CD3D9Texture::CD3D9Texture(CD3D9Driver* driver, const core::dimension2d<u32>& size, const io::path& name, E_TEXTURE_TYPE type, const ECOLOR_FORMAT format) : ITexture(name, type), Driver(driver), InternalFormat(D3DFMT_UNKNOWN), LockReadOnly(false), LockData(0), LockLayer(0), MipLevelLocked(0), HardwareMipMaps(false), Device(0), Texture(0), CubeTexture(0), RTTSurface(0) { #ifdef _DEBUG setDebugName("CD3D9Texture"); #endif Device = driver->getExposedVideoData().D3D9.D3DDev9; if (Device) Device->AddRef(); DriverType = Driver->getDriverType(); HasMipMaps = false; IsRenderTarget = true; OriginalColorFormat = format; if (ECF_UNKNOWN == OriginalColorFormat) ColorFormat = getBestColorFormat(Driver->getColorFormat()); else ColorFormat = OriginalColorFormat; OriginalSize = size; Size = OriginalSize; if (!Driver->queryFeature(EVDF_TEXTURE_NPOT)) { Size = Size.getOptimalSize(true, !Driver->queryFeature(EVDF_TEXTURE_NSQUARE), true, Driver->Caps.MaxTextureWidth); if (Size != OriginalSize) os::Printer::log("RenderTarget size has to be a power of two", ELL_INFORMATION); } Pitch = Size.Width * IImage::getBitsPerPixelFromFormat(ColorFormat) / 8; InternalFormat = Driver->getD3DFormatFromColorFormat(ColorFormat); generateRenderTarget(); } CD3D9Texture::~CD3D9Texture() { releaseTexture(); if (Device) Device->Release(); } void* CD3D9Texture::lock(E_TEXTURE_LOCK_MODE mode, u32 mipmapLevel, u32 layer, E_TEXTURE_LOCK_FLAGS lockFlags) { if (LockData) return LockData; if (IImage::isCompressedFormat(ColorFormat)) return 0; MipLevelLocked = mipmapLevel; LockReadOnly = (mode == ETLM_READ_ONLY); LockLayer = layer; HRESULT hr; D3DLOCKED_RECT rect; if (!IsRenderTarget) { if (Texture) { hr = Texture->LockRect(MipLevelLocked, &rect, 0, LockReadOnly ? D3DLOCK_READONLY : 0); } else if (CubeTexture) { IRR_DEBUG_BREAK_IF(layer > 5) hr = CubeTexture->LockRect(static_cast<_D3DCUBEMAP_FACES>(layer), MipLevelLocked, &rect, 0, LockReadOnly ? D3DLOCK_READONLY : 0); } else { os::Printer::log("Could not lock DIRECT3D9 Texture. Missing internal D3D texture.", ELL_ERROR); return 0; } if (FAILED(hr)) { os::Printer::log("Could not lock DIRECT3D9 Texture.", ELL_ERROR); return 0; } } else { if (!RTTSurface) { // Make RTT surface large enough for all miplevels (including 0) D3DSURFACE_DESC desc; if (Texture) Texture->GetLevelDesc(0, &desc); else if (CubeTexture) CubeTexture->GetLevelDesc(0, &desc); hr = Device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &RTTSurface, 0); if (FAILED(hr)) { os::Printer::log("Could not lock DIRECT3D9 Texture", "Offscreen surface creation failed.", ELL_ERROR); return 0; } } IDirect3DSurface9 *surface = 0; if (Texture) hr = Texture->GetSurfaceLevel(MipLevelLocked, &surface); else if (CubeTexture) hr = CubeTexture->GetCubeMapSurface(static_cast<_D3DCUBEMAP_FACES>(layer), MipLevelLocked, &surface); if (FAILED(hr)) { os::Printer::log("Could not lock DIRECT3D9 Texture", "Could not get surface.", ELL_ERROR); return 0; } hr = Device->GetRenderTargetData(surface, RTTSurface); surface->Release(); if(FAILED(hr)) { os::Printer::log("Could not lock DIRECT3D9 Texture", "Data copy failed.", ELL_ERROR); return 0; } hr = RTTSurface->LockRect(&rect, 0, LockReadOnly ? D3DLOCK_READONLY : 0); if(FAILED(hr)) { os::Printer::log("Could not lock DIRECT3D9 Texture", "LockRect failed.", ELL_ERROR); return 0; } } LockData = rect.pBits; return LockData; } void CD3D9Texture::unlock() { if (!LockData) return; if (!IsRenderTarget) { if (Texture) { Texture->UnlockRect(MipLevelLocked); } else if (CubeTexture) { CubeTexture->UnlockRect(static_cast<_D3DCUBEMAP_FACES>(LockLayer), MipLevelLocked); } } else if (RTTSurface) { RTTSurface->UnlockRect(); } LockReadOnly = false; LockData = 0; LockLayer = 0; } void CD3D9Texture::regenerateMipMapLevels(void* data, u32 layer) { if (!HasMipMaps || (Size.Width <= 1 && Size.Height <= 1)) return; if ( HardwareMipMaps ) { // Can't update with custom data with those unfortunately // Also MSDN docs don't mention it, but GenerateMipSubLevels only works when AUTOGENMIPMAP is set. // So we can't call this to get hardware mipmaps when not setting AUTOGENMIPMAP. if (Texture) Texture->GenerateMipSubLevels(); else if (CubeTexture) CubeTexture->GenerateMipSubLevels(); } else if (data) { u32 width = Size.Width; u32 height = Size.Height; u8* tmpData = static_cast<u8*>(data); u32 dataSize = 0; u32 level = 0; do { if (width > 1) width >>= 1; if (height > 1) height >>= 1; dataSize = IImage::getDataSizeFromFormat(ColorFormat, width, height); ++level; uploadTexture(tmpData, level, layer); tmpData += dataSize; } while (width != 1 || height != 1); } else { createManualMipMaps(1); } } void CD3D9Texture::copy16BitMipMap(char* src, char* tgt, s32 width, s32 height, s32 pitchsrc, s32 pitchtgt) const { for (s32 y=0; y<height; ++y) { for (s32 x=0; x<width; ++x) { u32 a=0, r=0, g=0, b=0; for (s32 dy=0; dy<2; ++dy) { const s32 tgy = (y*2)+dy; for (s32 dx=0; dx<2; ++dx) { const s32 tgx = (x*2)+dx; SColor c; if (ColorFormat == ECF_A1R5G5B5) c = A1R5G5B5toA8R8G8B8(*(u16*)(&src[(tgx*2)+(tgy*pitchsrc)])); else c = R5G6B5toA8R8G8B8(*(u16*)(&src[(tgx*2)+(tgy*pitchsrc)])); a += c.getAlpha(); r += c.getRed(); g += c.getGreen(); b += c.getBlue(); } } a /= 4; r /= 4; g /= 4; b /= 4; u16 c; if (ColorFormat == ECF_A1R5G5B5) c = RGBA16(r,g,b,a); else c = A8R8G8B8toR5G6B5(SColor(a,r,g,b).color); *(u16*)(&tgt[(x*2)+(y*pitchtgt)]) = c; } } } void CD3D9Texture::copy32BitMipMap(char* src, char* tgt, s32 width, s32 height, s32 pitchsrc, s32 pitchtgt) const { for (s32 y=0; y<height; ++y) { for (s32 x=0; x<width; ++x) { u32 a=0, r=0, g=0, b=0; SColor c; for (s32 dy=0; dy<2; ++dy) { const s32 tgy = (y*2)+dy; for (s32 dx=0; dx<2; ++dx) { const s32 tgx = (x*2)+dx; c = *(u32*)(&src[(tgx*4)+(tgy*pitchsrc)]); a += c.getAlpha(); r += c.getRed(); g += c.getGreen(); b += c.getBlue(); } } a /= 4; r /= 4; g /= 4; b /= 4; c.set(a, r, g, b); *(u32*)(&tgt[(x*4)+(y*pitchtgt)]) = c.color; } } } bool CD3D9Texture::createManualMipMaps(u32 level) { if (level==0) return true; if (!Texture) //Manual mips for CubeTexture not supported yet { return true; } // manual mipmap generation IDirect3DSurface9* upperSurface = 0; IDirect3DSurface9* lowerSurface = 0; // get upper level HRESULT hr = Texture->GetSurfaceLevel(level-1, &upperSurface); if (FAILED(hr) || !upperSurface) { os::Printer::log("Could not get upper surface level for mip map generation", ELL_WARNING); return false; } // get lower level hr = Texture->GetSurfaceLevel(level, &lowerSurface); if (FAILED(hr) || !lowerSurface) { os::Printer::log("Could not get lower surface level for mip map generation", ELL_WARNING); upperSurface->Release(); return false; } D3DSURFACE_DESC upperDesc, lowerDesc; upperSurface->GetDesc(&upperDesc); lowerSurface->GetDesc(&lowerDesc); D3DLOCKED_RECT upperlr; D3DLOCKED_RECT lowerlr; // lock upper surface if (FAILED(upperSurface->LockRect(&upperlr, NULL, 0))) { upperSurface->Release(); lowerSurface->Release(); os::Printer::log("Could not lock upper texture for mip map generation", ELL_WARNING); return false; } // lock lower surface if (FAILED(lowerSurface->LockRect(&lowerlr, NULL, 0))) { upperSurface->UnlockRect(); upperSurface->Release(); lowerSurface->Release(); os::Printer::log("Could not lock lower texture for mip map generation", ELL_WARNING); return false; } if (upperDesc.Format != lowerDesc.Format) { os::Printer::log("Cannot copy mip maps with different formats.", ELL_WARNING); } else { if ((upperDesc.Format == D3DFMT_A1R5G5B5) || (upperDesc.Format == D3DFMT_R5G6B5)) copy16BitMipMap((char*)upperlr.pBits, (char*)lowerlr.pBits, lowerDesc.Width, lowerDesc.Height, upperlr.Pitch, lowerlr.Pitch); else if (upperDesc.Format == D3DFMT_A8R8G8B8) copy32BitMipMap((char*)upperlr.pBits, (char*)lowerlr.pBits, lowerDesc.Width, lowerDesc.Height, upperlr.Pitch, lowerlr.Pitch); else os::Printer::log("Unsupported mipmap format, cannot copy.", ELL_WARNING); } bool result=true; // unlock if (FAILED(upperSurface->UnlockRect())) result=false; if (FAILED(lowerSurface->UnlockRect())) result=false; // release upperSurface->Release(); lowerSurface->Release(); if (!result || (upperDesc.Width <= 3 && upperDesc.Height <= 3)) return result; // stop generating levels // generate next level return createManualMipMaps(level+1); } IDirect3DBaseTexture9* CD3D9Texture::getDX9BaseTexture() const { return (Texture) ? static_cast<IDirect3DBaseTexture9*>(Texture) : static_cast<IDirect3DBaseTexture9*>(CubeTexture); } IDirect3DTexture9* CD3D9Texture::getDX9Texture() const { return Texture; } IDirect3DCubeTexture9* CD3D9Texture::getDX9CubeTexture() const { return CubeTexture; } void CD3D9Texture::releaseTexture() { if (RTTSurface) { if (RTTSurface->Release() == 0) RTTSurface = 0; } if (Texture) { if (Texture->Release() == 0) Texture = 0; } if (CubeTexture) { if (CubeTexture->Release() == 0) CubeTexture = 0; } } void CD3D9Texture::generateRenderTarget() { DWORD flags = (IImage::isDepthFormat(ColorFormat)) ? D3DUSAGE_DEPTHSTENCIL : D3DUSAGE_RENDERTARGET; HRESULT hr = 0; switch (Type) { case ETT_2D: if (!Texture ) hr = Device->CreateTexture(Size.Width, Size.Height, 1, flags, InternalFormat, D3DPOOL_DEFAULT, &Texture, NULL); break; case ETT_CUBEMAP: if (!CubeTexture) hr = Device->CreateCubeTexture(Size.Width, 1, flags, InternalFormat, D3DPOOL_DEFAULT, &CubeTexture, NULL); break; default: IRR_DEBUG_BREAK_IF(true) break; } if (FAILED(hr)) { if (D3DERR_INVALIDCALL == hr) os::Printer::log("Could not create render target texture", "Invalid Call", irr::ELL_ERROR); else if (D3DERR_OUTOFVIDEOMEMORY == hr) os::Printer::log("Could not create render target texture", "Out of Video Memory", irr::ELL_ERROR); else if (E_OUTOFMEMORY == hr) os::Printer::log("Could not create render target texture", "Out of Memory", irr::ELL_ERROR); else os::Printer::log("Could not create render target texture", irr::ELL_ERROR); core::stringc params("Width:"); params += (unsigned int)Size.Width; params += " Height: "; params += (unsigned int)Size.Height; params += " flag: "; params += (unsigned int)flags; params += " format"; params += (unsigned int)InternalFormat; params += " Type: "; params += (unsigned int)Type; os::Printer::log(params.c_str(), irr::ELL_ERROR); } } ECOLOR_FORMAT CD3D9Texture::getBestColorFormat(ECOLOR_FORMAT format) { // We only try for to adapt "simple" formats ECOLOR_FORMAT destFormat = (format <= ECF_A8R8G8B8) ? ECF_A8R8G8B8 : format; switch (format) { case ECF_A1R5G5B5: if (!Driver->getTextureCreationFlag(ETCF_ALWAYS_32_BIT)) destFormat = ECF_A1R5G5B5; break; case ECF_R5G6B5: if (!Driver->getTextureCreationFlag(ETCF_ALWAYS_32_BIT)) destFormat = ECF_R5G6B5; break; case ECF_A8R8G8B8: if (Driver->getTextureCreationFlag(ETCF_ALWAYS_16_BIT) || Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED)) destFormat = ECF_A1R5G5B5; break; case ECF_R8G8B8: // Note: Using ECF_A8R8G8B8 even when ETCF_ALWAYS_32_BIT is not set as 24 bit textures fail with too many cards if (Driver->getTextureCreationFlag(ETCF_ALWAYS_16_BIT) || Driver->getTextureCreationFlag(ETCF_OPTIMIZED_FOR_SPEED)) destFormat = ECF_A1R5G5B5; default: break; } if (Driver->getTextureCreationFlag(ETCF_NO_ALPHA_CHANNEL)) { switch (destFormat) { case ECF_A1R5G5B5: destFormat = ECF_R5G6B5; break; case ECF_A8R8G8B8: destFormat = ECF_R8G8B8; break; default: break; } } return destFormat; } void CD3D9Texture::getImageValues(const IImage* image) { OriginalColorFormat = image->getColorFormat(); ColorFormat = getBestColorFormat(OriginalColorFormat); InternalFormat = Driver->getD3DFormatFromColorFormat(ColorFormat); if (IImage::isCompressedFormat(image->getColorFormat())) { HardwareMipMaps = false; } OriginalSize = image->getDimension(); Size = OriginalSize; if (Size.Width == 0 || Size.Height == 0) { os::Printer::log("Invalid size of image for texture.", ELL_ERROR); return; } const f32 ratio = (f32)Size.Width / (f32)Size.Height; if ((Size.Width > Driver->Caps.MaxTextureWidth) && (ratio >= 1.f)) { Size.Width = Driver->Caps.MaxTextureWidth; Size.Height = (u32)(Driver->Caps.MaxTextureWidth / ratio); } else if (Size.Height > Driver->Caps.MaxTextureHeight) { Size.Height = Driver->Caps.MaxTextureHeight; Size.Width = (u32)(Driver->Caps.MaxTextureHeight * ratio); } bool needSquare = (!Driver->queryFeature(EVDF_TEXTURE_NSQUARE) || Type == ETT_CUBEMAP); Size = Size.getOptimalSize(!Driver->queryFeature(EVDF_TEXTURE_NPOT), needSquare, true, Driver->Caps.MaxTextureWidth); Pitch = Size.Width * IImage::getBitsPerPixelFromFormat(ColorFormat) / 8; } void CD3D9Texture::uploadTexture(void* data, u32 mipmapLevel, u32 layer) { if (!data) return; u32 width = Size.Width >> mipmapLevel; u32 height = Size.Height >> mipmapLevel; u32 dataSize = IImage::getDataSizeFromFormat(ColorFormat, width, height); HRESULT hr = 0; D3DLOCKED_RECT lockRectangle; if (Texture) { hr = Texture->LockRect(mipmapLevel, &lockRectangle, 0, 0); } else if (CubeTexture) { IRR_DEBUG_BREAK_IF(layer > 5) hr = CubeTexture->LockRect(static_cast<_D3DCUBEMAP_FACES>(layer), mipmapLevel, &lockRectangle, 0, 0); } if (FAILED(hr)) { os::Printer::log("Texture data not copied", "Could not LockRect D3D9 Texture.", ELL_ERROR); return; } memcpy(lockRectangle.pBits, data, dataSize); if (Texture) { hr = Texture->UnlockRect(mipmapLevel); } else if (CubeTexture) { hr = CubeTexture->UnlockRect(static_cast<_D3DCUBEMAP_FACES>(layer), mipmapLevel); } if (FAILED(hr)) { os::Printer::log("Texture data not copied", "Could not UnlockRect D3D9 Texture.", ELL_ERROR); } } } } #endif
25.843627
189
0.663345
[ "render" ]
0da98b25ca03dcb96f9eb81b1f9bc7d5906544d0
8,733
cpp
C++
Eudora71/Eudora/PgEmbeddedObject.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Windows/Eudora71/Eudora/PgEmbeddedObject.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Windows/Eudora71/Eudora/PgEmbeddedObject.cpp
officialrafsan/EUDORA
bf43221f5663ec2338aaf90710a89d1490b92ed2
[ "MIT" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
// PgEmbeddedObject.cpp -- support for ole-based embed refs in Paige. // // Note that this does not support ole objects in *any* paige ref, but only // those with associated mfc view/doc. The doc must be derived from // COleDocument. The embed ref points to a "PgCntrItem" [PgCntrItem.cpp], // which provides a common interface for all objects. #include "stdafx.h" #include "afxole.h" #include "afxodlgs.h" #include "PaigeEdtView.h" #include "OleDoc.h" #include "PgCntrItem.h" #include "ObjectSpec.h" #include "paige.h" #include "pgembed.h" #include "pgtraps.h" #define embed_type(p) (p->type & EMBED_TYPE_MASK) #include "DebugNewHelpers.h" // called by Paige for all OBJECTs [i.e. ActiveX controls] PG_PASCAL (long) ActiveXCallbackProc( paige_rec_ptr pg, pg_embed_ptr embed_ptr, long embed_type, short command, long user_refcon, long param1, long param2 ) { long result = 0; PgCntrItem* pItem = 0; switch (command) { case EMBED_DRAW: { CRect theBox; RectangleToRect( (rectangle_ptr)param1, 0, &theBox ); HDC hdc = (HDC)pg->globals->current_port->machine_ref; CDC* pdc = CDC::FromHandle( hdc ); if ( !(pItem = (PgCntrItem*) embed_ptr->user_refcon) ) { // haven't bound to the activex control yet, so let's get busy. // if we fail we'll bind to our "something sucks" control, // which will handle ui for error conditions. HtmlObjectSpec* pSpec = (HtmlObjectSpec*) embed_ptr->user_data; pItem = PgBindToObject( pg, pSpec ); if ( pItem ) { embed_ptr->user_refcon = (long) pItem; } else { // TODO: need some way to flag the embed as dead // break out now, we're completely screwed break; } } if ( !pItem->IsInPlaceActive() ) pItem->Draw( pdc, &theBox ); pItem->activatePos = theBox; } break; case EMBED_DOUBLECLICK: case EMBED_MOUSEDOWN: { pg_embed_click_ptr click = (pg_embed_click_ptr) param1; CRect rc; RectangleToRect( &click->bounds, 0, &rc ); PgCntrItem* pItem = (PgCntrItem*) embed_ptr->user_refcon; if ( pItem ) pItem->activatePos = rc; // fall through } case EMBED_MOUSEMOVE: case EMBED_MOUSEUP: result = pgDefaultEmbedCallback( pg, embed_ptr, embed_type, command, user_refcon, param1, param2 ); break; case EMBED_DESTROY: { // smoke ole item and the object spec, let paige do the rest HtmlObjectSpec* pSpec = (HtmlObjectSpec*) embed_ptr->user_data; delete pSpec; PgCntrItem* pItem = (PgCntrItem*) embed_ptr->user_refcon; if ( pItem ) pItem->Delete(); result = pgDefaultEmbedCallback( pg, embed_ptr, embed_type, command, user_refcon, param1, param2 ); } break; default: result = pgDefaultEmbedCallback( pg, embed_ptr, embed_type, command, user_refcon, param1, param2 ); break; } return result; } /////////////////////////////////////////////////////////////////////////////// // public interfaces // force immediate loading of all items int PgLoadAllObjects( pg_ref pg ) { // might as well do this outside the loop paige_rec_ptr pgRec; if ( !(pgRec = (paige_rec_ptr) UseMemory( pg )) ) return 0; int nObjects = 0; embed_ref er; pg_embed_ptr pe; HtmlObjectSpec* pSpec; PgCntrItem* pItem; for ( long pos = 0; (er = pgFindNextEmbed( pg, &pos, 0, 0 )); pos += 2 ) { if ( er && (pe = (pg_embed_ptr)UseMemory(er)) ) { if ( embed_type(pe) != embed_url_image ) if ( pSpec = (HtmlObjectSpec*) pe->user_data ) if ( pItem = PgBindToObject( pgRec, pSpec ) ) { pe->user_refcon = (long) pItem; nObjects++; } } UnuseMemory( er ); } UnuseMemory( pg ); return nObjects; } // handy-dandy "KindOf" boogie #define is_kind_of(class_name, object) \ ((object)->IsKindOf(RUNTIME_CLASS(class_name))) // user inserts ole item from common dialog interface // // BOG: this is just some hacked up stuff used for prototyping. it does most // of what you need to do user-inserts of ole objects, but i'm thinking that's // not gonna fly for 5.0 anyway, so let's just "def" it. #if 0 bool PgUserInsertObject( CView* pView, pg_ref pg, short draw_mode ) { // - must be able to get COleDocument from view [pv->GetDocument()] // - for now we let object dictate aspect, display bounds, etc. bool bRet = false; #if 1 // Invoke the standard Insert Object dialog box to obtain information // for new PgCntrItem object. COleInsertDialog dlg; if (dlg.DoModal() != IDOK) return bRet; #endif COleDoc* pDoc = (COleDoc*) pView->GetDocument(); ASSERT_KINDOF( COleDocument, pDoc ); if ( is_kind_of(COleDoc, pDoc) ) { TRY { pView->BeginWaitCursor(); pItem = DEBUG_NEW PgCntrItem( pDoc ); #if 1 // Initialize the item from the dialog data. if (!dlg.CreateItem(pItem)) AfxThrowMemoryException(); // any exception will do ASSERT_VALID(pItem); // If item created from class list (not from file) then launch // the server to edit the item. if (dlg.GetSelectionType() == COleInsertDialog::createNewItem) pItem->m_activateNow = true; else pItem->m_activateNow = false; #else CLSID uid; USES_CONVERSION; CLSIDFromProgID( A2COLE("SNUFFLELUMPS.SnufflelumpsCtrl.1"), &uid ); // CLSIDFromProgID( A2COLE("MediaPlayer.MediaPlayer.1"), &uid ); pItem->CreateNewItem( uid ); pItem->Run(); pItem->m_activateNow = false; #endif // Create a custom ref, but if we specify embed_user_data // then OpenPaige will attach the data to the ref. paige_rec_ptr pgRec = (paige_rec_ptr) UseMemory( pg ); embed_ref ref = pgNewEmbedRef( pgRec->globals->mem_globals, embed_user_box, 0, 0, 0, 0, 0, FALSE ); UnuseMemory( pg ); // TODO: need a memory exception here // The following code is vital for a "custom" user type since // OpenPaige has no idea how tall our embed item is, nor does // it know how wide it is: CSize ext; pItem->GetExtent( &ext ); pView->GetDC()->HIMETRICtoDP( &ext ); pg_embed_ptr embed_ptr = (pg_embed_ptr) UseMemory( ref ); embed_ptr->height = ext.cy; embed_ptr->width = ext.cx; // stash a ptr to our ole object embed_ptr->user_data = (long) pItem; UnuseMemory(ref); // Insert the ref. (Also add pgPrepareUndo() here if desired). pgInsertEmbedRef( pg, ref, CURRENT_POSITION, 0, ActiveXCallbackProc, /*refCon*/0, draw_mode ); bRet = true; pView->EndWaitCursor(); } CATCH(CException, e) { if (pItem != NULL) { ASSERT_VALID(pItem); pItem->Delete(); } } END_CATCH } if ( pItem->m_activateNow ) pItem->DoVerb(OLEIVERB_SHOW, pView); pItem->m_activateNow = false; return bRet; } #endif // PgBindToObject: this tries to load and initialize an activex control based // on an HtmlObjectSpec. If we fail, we bind to our "something sucks" // activex control instead [not impl yet] // // BOG: if you don't pass this thing a paige record with a good StuffBucket, // it ain't gonna work worth stuff. in this case, "good StuffBucket" means // one with a back-ptr to a CPaigeEdtView derrived view. PgCntrItem* PgBindToObject( paige_rec_ptr ppg, HtmlObjectSpec* pSpec ) { PgCntrItem* pItem = 0; // return this CView* pView = 0; // our window on the world COleDoc* pDoc = 0; // view's doc: holds list of all embedded objects // get a good (ole) doc ptr PgStuffBucket* pSB = (PgStuffBucket*) ppg->user_refcon; assert( pSB ); if ( pSB ) { pView = (CView*) pSB->pWndOwner; ASSERT_KINDOF( CView, pView ); if ( pView ) { pDoc = (COleDoc*) pView->GetDocument(); ASSERT_KINDOF( COleDoc, pDoc ); } } // ok, provided that all went well, we'll try to load the control and add // it too the doc's container items. if ( pDoc && is_kind_of(COleDoc, pDoc) ) { pItem = DEBUG_NEW_MFCOBJ_NOTHROW PgCntrItem( pDoc ); if ( pItem ) { USES_CONVERSION; CLSID uid; CLSIDFromString( A2OLE(pSpec->classid), &uid ); if ( pItem->CreateNewItem( uid ) ) { pItem->m_activateNow = false; pItem->m_idString = pSpec->id; pItem->m_pg = ppg->doc_pg; pItem->SetFont( pDoc->GetFontDispatch() ); // if size isn't specified, let's hope the control has a clue if ( !pSpec->width || !pSpec->height ) { CSize defExt; pItem->GetExtent( &defExt ); pView->GetDC()->HIMETRICtoDP( &defExt ); if ( !pSpec->width ) pSpec->width = defExt.cx; if ( !pSpec->height ) pSpec->height = defExt.cy; } // set/reset the control's extent CSize ext( pSpec->width, pSpec->height ); pView->GetDC()->DPtoHIMETRIC( &ext ); pItem->SetExtent( ext ); } else { // TODO: bind to "default" control for error handling // for now just bail, leaving an unhandled user_box pItem->Delete(); pItem = 0; } } } return pItem; }
26.625
79
0.662888
[ "object" ]
0db0936f7762cddeb7eb597a5159680417de1724
472
cpp
C++
C++/0003.cpp
AndroAvi/DSA
5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582
[ "MIT" ]
4
2021-08-28T19:16:50.000Z
2022-03-04T19:46:31.000Z
C++/0003.cpp
AndroAvi/DSA
5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582
[ "MIT" ]
8
2021-10-29T19:10:51.000Z
2021-11-03T12:38:00.000Z
C++/0003.cpp
AndroAvi/DSA
5937ab1e98c86a1f6e6745f3ea62d45b7bdeb582
[ "MIT" ]
4
2021-09-06T05:53:07.000Z
2021-12-24T10:31:40.000Z
class Solution { public: int lengthOfLongestSubstring(string s) { vector<int>map1(256, -1); int left = 0, right = 0, n = s.size(), len = 0; while(right < n){ if(map1[s[right]] != -1) left = max(map1[s[right]] + 1, left); map1[s[right]] = right; len = max(len, right - left + 1); right++; } return len; } };
22.47619
55
0.398305
[ "vector" ]
0db9be14424c42ede39cca840116e8b8831bbff8
3,488
cpp
C++
BarcodeArrayScanner.cpp
fxnolimit/FrancoisMukabaCS300_5
6853fa72e656b9d706d4d75987ee98606ac44723
[ "MIT" ]
1
2019-07-24T02:34:52.000Z
2019-07-24T02:34:52.000Z
BarcodeArrayScanner.cpp
fxnolimit/BarcodeScanner
6853fa72e656b9d706d4d75987ee98606ac44723
[ "MIT" ]
null
null
null
BarcodeArrayScanner.cpp
fxnolimit/BarcodeScanner
6853fa72e656b9d706d4d75987ee98606ac44723
[ "MIT" ]
null
null
null
/* * BarcodeArrayScanner.cpp * * Created on: Nov 21, 2018 * Author: fxkik */ #include <iostream> #include "Item.h" #include <sstream> #include <fstream> #include <chrono> using namespace std; using namespace std::chrono; int arrayIndex = 0; const int arraySize = 2000000; void initializeArray(string fileName, Item * array) { ifstream file(fileName); // store the file in a ifstream object string line; while (getline(file, line)) { //reads line by line in the file string itemName; string temp; long long barcode; stringstream stream(line); getline(stream, temp, ','); // read from where it 'points' until it reaches a comma and store substring in temp getline(stream, itemName); // read from where it 'points' until the end of the line istringstream(temp) >> barcode; // parse/cast into long long type //create and add the item retrieved from the line Item item(itemName, barcode); if (arrayIndex < arraySize) { array[arrayIndex] = item; arrayIndex++; } } } int main() { string fileName = "upc_corpus.txt"; Item *array = new Item[arraySize]; initializeArray(fileName, array); bool flag = false; //SAMPLE RUN 1 cout << "SAMPLE RUN 1" << endl; Item target1("", 52569758373); high_resolution_clock::time_point start = high_resolution_clock::now(); for (int i = 0; i < arrayIndex; i++) { if (array[i] == target1) { flag = true; break; } } high_resolution_clock::time_point end = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(end - start).count(); cout << "time1: " << duration << " microseconds" << endl; cout << "Boolean value returned: " << flag << "\n" << endl; flag = false; //SAMPLE RUN 2 cout << "SAMPLE RUN 2" << endl; Item target2("", 52569744956); start = high_resolution_clock::now(); for (int i = 0; i < arrayIndex; i++) { if (array[i] == target2) { flag = true; break; } } end = high_resolution_clock::now(); duration = duration_cast<microseconds>(end - start).count(); cout << "time2: " << duration << " microseconds" << endl; cout << "Boolean value returned: " << flag << "\n" << endl; flag = false; //SAMPLE RUN 3 cout << "SAMPLE RUN 3" << endl; Item target3("", 23900007368); start = high_resolution_clock::now(); for (int i = 0; i < arrayIndex; i++) { if (array[i] == target3) { flag = true; break; } } end = high_resolution_clock::now(); duration = duration_cast<microseconds>(end - start).count(); cout << "time3: " << duration << " microseconds" << endl; cout << "Boolean value returned: " << flag << "\n" << endl; flag = false; //SAMPLE RUN 4 cout << "SAMPLE RUN 4" << endl; Item target4("", 11279000080); start = high_resolution_clock::now(); for (int i = 0; i < arrayIndex; i++) { if (array[i] == target4) { flag = true; break; } } end = high_resolution_clock::now(); duration = duration_cast<microseconds>(end - start).count(); cout << "time4: " << duration << " microseconds" << endl; cout << "Boolean value returned: " << flag << "\n" << endl; flag = false; //SAMPLE RUN 5 cout << "SAMPLE RUN 5" << endl; Item target5("", 99999); start = high_resolution_clock::now(); for (int i = 0; i < arrayIndex; i++) { if (array[i] == target5) { flag = true; break; } } end = high_resolution_clock::now(); duration = duration_cast<microseconds>(end - start).count(); cout << "time5: " << duration << " microseconds" << endl; cout << "Boolean value returned: " << flag << "\n" << endl; }
27.904
113
0.640195
[ "object" ]
0db9d1b19070e6cb7a20881180c3352385eb25a5
1,043
hpp
C++
src/accel/bvh/builder.hpp
jkrueger/phosphorus_mk2
f26330fc2d013ca875d68de78ea9f92f344ddf4e
[ "MIT" ]
2
2019-12-12T04:59:41.000Z
2020-09-15T12:57:35.000Z
src/accel/bvh/builder.hpp
jkrueger/phosphorus_mk2
f26330fc2d013ca875d68de78ea9f92f344ddf4e
[ "MIT" ]
1
2020-09-15T12:58:42.000Z
2020-09-15T12:58:42.000Z
src/accel/bvh/builder.hpp
jkrueger/phosphorus_mk2
f26330fc2d013ca875d68de78ea9f92f344ddf4e
[ "MIT" ]
null
null
null
#pragma once #include <ImathBox.h> #include <ImathVec.h> #include <memory> #include <vector> namespace bvh { struct primitive_t { uint32_t index; // an index into the real scene geometry Imath::Box3f bounds; // the bounding box of the primitive Imath::V3f centroid; // the center of the bounding box inline primitive_t() {} inline primitive_t(const primitive_t& cpy) : index(cpy.index), bounds(cpy.bounds), centroid(cpy.centroid) {} inline primitive_t(uint32_t index, const Imath::Box3f& bounds) : index(index), bounds(bounds), centroid(bounds.center()) {} }; template<typename Node, typename Primitive> struct builder_t { typedef std::unique_ptr<builder_t> scoped_t; virtual ~builder_t() {} virtual uint32_t make_node() = 0; virtual Node& resolve(uint32_t n) const = 0; virtual uint32_t add( uint32_t begin , uint32_t end , const std::vector<primitive_t>& primitives , const std::vector<Primitive>& tiangles) = 0; }; }
23.177778
68
0.662512
[ "geometry", "vector" ]
0dc9696bb87897cfe075b5e9f8d61718c6d9e1d9
4,004
cpp
C++
src/post/main/Assignment.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
3
2020-05-22T04:17:23.000Z
2020-07-17T04:14:25.000Z
src/post/main/Assignment.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
null
null
null
src/post/main/Assignment.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
null
null
null
#include "Assignment.hpp" #include "FindPathVisitor.hpp" #include "Path.hpp" #include "Message.hpp" MsgRef Assignment::getErrorMsg(int target, string msgcode, bool tentative) { string var = variables->getRealName(target); MsgRef msg = Message::factory(); msg->file_name = file; msg->line_number = line; string::size_type loc = var.find("__cil", 0); string type; bool pointer = false; if (variables->isPointer(target)) { pointer = true; } if (msgcode == "overwrite") { msg->target = var; if (loc == string::npos) { // only report overwrites of non-temporaries if (tentative) { if (pointer) msg->type = Message::Types::OVERWRITE_POINTER; else msg->type = Message::Types::OVERWRITE; } else { if (pointer) msg->type = Message::Types::OVERWRITE_NT_POINTER; else msg->type = Message::Types::OVERWRITE_NT; } } } else { // It is not an overwrite if (loc != string::npos) { //__cil was found // it is an unsaved error if (tentative) { msg->type = Message::Types::UNCHECK_NSAVE; } else { msg->type = Message::Types::UNCHECK_NT_NSAVE; } } else { msg->target = var; // it is an out-of-scope error if (tentative) { if (pointer) msg->type = Message::Types::UNCHECK_OUT_POINTER; else msg->type = Message::Types::UNCHECK_OUT; } else { if (pointer) msg->type = Message::Types::UNCHECK_NT_OUT_POINTER; else msg->type = Message::Types::UNCHECK_NT_OUT; } } } return msg; } void Assignment::process() { if (weight != NULL) { map<string, string>::iterator it = targets.begin(); for(; it != targets.end(); it++) { string starget = it->first; int target = variables->getIndex(starget); int source = variables->getIndex(it->second); bdd targetToAllErrors = fdd_ithvar(0, target) & bddNonTentativeErrors; bool tentative = false; bdd targetToErrors = weight->BDD & targetToAllErrors; if (report_tentative && targetToErrors == bddfalse) { //the var does not have non-tentative errors // now check for tentative errors targetToAllErrors = fdd_ithvar(0, target) & bddTentativeErrors; targetToErrors = weight->BDD & targetToAllErrors; tentative = true; //possibly, there might not be tentative errors } if (targetToErrors != bddfalse) { //the var has at least an error, priority given to non-tentatives const int error = getError(targetToErrors); if (interesting(target, source, error)) { string::size_type loc = starget.find("cabs2cil_", 0); bool report = report_temps || (loc == string::npos); if (report && line > 0) { if (print != None) { // constructing first message MsgRef msg = getErrorMsg(target, msgcode, tentative); if (msg->type != Message::Types::EMPTY) { // overwrites for temporaries are not reported // cout << "Error codes: "; vector<string> errors = getErrors(targetToErrors, target); msg->error = variables->getId(error); msg->error_codes = errors; // finding sample path Path path(msg); bool stop = false; FindPathVisitor visitor(target, error, error, path, stop); witness->accept(visitor); // printing path path.printReport(cout); } } } } } // done processing a target } // done processing all targets } } bool Assignment::interesting(int target, int source, int error) { bdd targetToError = (fdd_ithvar(0,target) & (fdd_ithvar(1,error))); if ( (weight->BDD & targetToError) != bddfalse ) { bdd sourceToAllButError = (fdd_ithvar(0, source) & bddtrue) - (fdd_ithvar(0, source) & (fdd_ithvar(1, error))); if ( (weight->BDD & sourceToAllButError) != bddfalse) { return true; } return false; } return false; }
25.666667
105
0.608392
[ "vector" ]
0dd5702335bb106701c1317774b9aeb438b7725b
2,237
cc
C++
routerNodeWaterfilling.cc
aakritanshuman/mtp
d24c09e99e01904ffc0d779c5e031bb7c03cff8e
[ "MIT" ]
11
2020-03-03T11:58:23.000Z
2021-04-20T02:01:30.000Z
routerNodeWaterfilling.cc
aakritanshuman/mtp
d24c09e99e01904ffc0d779c5e031bb7c03cff8e
[ "MIT" ]
null
null
null
routerNodeWaterfilling.cc
aakritanshuman/mtp
d24c09e99e01904ffc0d779c5e031bb7c03cff8e
[ "MIT" ]
9
2020-03-17T02:17:07.000Z
2022-02-17T16:12:31.000Z
#include "routerNodeWaterfilling.h" Define_Module(routerNodeWaterfilling); /* overall controller for handling messages that dispatches the right function * based on message type in waterfilling */ void routerNodeWaterfilling::handleMessage(cMessage *msg) { routerMsg *ttmsg = check_and_cast<routerMsg *>(msg); if (simTime() > _simulationLength){ auto encapMsg = (ttmsg->getEncapsulatedPacket()); ttmsg->decapsulate(); delete ttmsg; delete encapMsg; return; } switch(ttmsg->getMessageType()) { case PROBE_MSG: if (_loggingEnabled) cout<< "[ROUTER "<< myIndex() <<": RECEIVED PROBE MSG] "<< ttmsg->getName() << endl; handleProbeMessage(ttmsg); if (_loggingEnabled) cout<< "[AFTER HANDLING:] "<< endl; break; default: routerNodeBase::handleMessage(msg); } } /* method to receive and forward probe messages to the next node */ void routerNodeWaterfilling::handleProbeMessage(routerMsg* ttmsg){ probeMsg *pMsg = check_and_cast<probeMsg *>(ttmsg->getEncapsulatedPacket()); bool isReversed = pMsg->getIsReversed(); int nextDest = ttmsg->getRoute()[ttmsg->getHopCount()+1]; forwardProbeMessage(ttmsg); } /* forwards probe messages * after appending this channel's balances to the probe message on the * way back */ void routerNodeWaterfilling::forwardProbeMessage(routerMsg *msg){ int prevDest = msg->getRoute()[msg->getHopCount() - 1]; bool updateOnReverse = true; int nextDest = msg->getRoute()[msg->getHopCount()]; probeMsg *pMsg = check_and_cast<probeMsg *>(msg->getEncapsulatedPacket()); msg->setHopCount(msg->getHopCount()+1); if (pMsg->getIsReversed() == true && updateOnReverse == true){ vector<double> *pathBalances = & ( pMsg->getPathBalances()); (*pathBalances).push_back(nodeToPaymentChannel[prevDest].balance); } else if (pMsg->getIsReversed() == false && updateOnReverse == false) { vector<double> *pathBalances = & ( pMsg->getPathBalances()); (*pathBalances).push_back(nodeToPaymentChannel[nextDest].balance); } send(msg, nodeToPaymentChannel[nextDest].gate); }
36.672131
80
0.66473
[ "vector" ]
0de6a05385982fa26b6c8c0286fe2da2c576256a
6,383
cpp
C++
hecl/lib/Pipeline.cpp
RetroView/RetroCommon
a413a010b50a53ebc6b0c726203181fc179d3370
[ "MIT" ]
106
2021-04-09T19:42:56.000Z
2022-03-30T09:13:28.000Z
hecl/lib/Pipeline.cpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
58
2021-04-09T12:48:58.000Z
2022-03-22T00:11:42.000Z
hecl/lib/Pipeline.cpp
Austint30/metaforce
a491e2e9f229c8db92544b275cd1baa80bacfd17
[ "MIT" ]
13
2021-04-06T23:23:20.000Z
2022-03-16T02:09:48.000Z
#include "hecl/Pipeline.hpp" #include <athena/FileReader.hpp> #include <zlib.h> namespace hecl { #if HECL_RUNTIME PipelineConverterBase* conv = nullptr; class ShaderCacheZipStream : public athena::io::IStreamReader { std::unique_ptr<uint8_t[]> m_compBuf; athena::io::FileReader m_reader; z_stream m_zstrm = {}; public: explicit ShaderCacheZipStream(const char* path) : m_reader(path) { if (m_reader.hasError()) return; if (m_reader.readUint32Big() != SBIG('SHAD')) return; m_compBuf.reset(new uint8_t[4096]); m_zstrm.next_in = m_compBuf.get(); m_zstrm.avail_in = 0; inflateInit(&m_zstrm); } ~ShaderCacheZipStream() override { inflateEnd(&m_zstrm); } explicit operator bool() const { return m_compBuf.operator bool(); } atUint64 readUBytesToBuf(void* buf, atUint64 len) override { m_zstrm.next_out = (Bytef*)buf; m_zstrm.avail_out = len; m_zstrm.total_out = 0; while (m_zstrm.avail_out != 0) { if (m_zstrm.avail_in == 0) { atUint64 readSz = m_reader.readUBytesToBuf(m_compBuf.get(), 4096); m_zstrm.avail_in = readSz; m_zstrm.next_in = m_compBuf.get(); } int inflateRet = inflate(&m_zstrm, Z_NO_FLUSH); if (inflateRet != Z_OK) break; } return m_zstrm.total_out; } void seek(atInt64, athena::SeekOrigin) override {} atUint64 position() const override { return 0; } atUint64 length() const override { return 0; } }; template <typename P, typename S> void StageConverter<P, S>::loadFromStream(FactoryCtx& ctx, ShaderCacheZipStream& r) { uint32_t count = r.readUint32Big(); for (uint32_t i = 0; i < count; ++i) { uint64_t hash = r.readUint64Big(); uint32_t size = r.readUint32Big(); StageBinaryData data = MakeStageBinaryData(size); r.readUBytesToBuf(data.get(), size); m_stageCache.insert(std::make_pair(hash, Do<StageTargetTp>(ctx, StageBinary<P, S>(data, size)))); } } static boo::AdditionalPipelineInfo ReadAdditionalInfo(ShaderCacheZipStream& r) { boo::AdditionalPipelineInfo additionalInfo; additionalInfo.srcFac = boo::BlendFactor(r.readUint32Big()); additionalInfo.dstFac = boo::BlendFactor(r.readUint32Big()); additionalInfo.prim = boo::Primitive(r.readUint32Big()); additionalInfo.depthTest = boo::ZTest(r.readUint32Big()); additionalInfo.depthWrite = r.readBool(); additionalInfo.colorWrite = r.readBool(); additionalInfo.alphaWrite = r.readBool(); additionalInfo.culling = boo::CullMode(r.readUint32Big()); additionalInfo.patchSize = r.readUint32Big(); additionalInfo.overwriteAlpha = r.readBool(); additionalInfo.depthAttachment = r.readBool(); return additionalInfo; } static std::vector<boo::VertexElementDescriptor> ReadVertexFormat(ShaderCacheZipStream& r) { std::vector<boo::VertexElementDescriptor> ret; uint32_t count = r.readUint32Big(); ret.reserve(count); for (uint32_t i = 0; i < count; ++i) { ret.emplace_back(); ret.back().semantic = boo::VertexSemantic(r.readUint32Big()); ret.back().semanticIdx = int(r.readUint32Big()); } return ret; } template <typename P> bool PipelineConverter<P>::loadFromFile(FactoryCtx& ctx, const char* path) { ShaderCacheZipStream r(path); if (!r) return false; m_vertexConverter.loadFromStream(ctx, r); m_fragmentConverter.loadFromStream(ctx, r); m_geometryConverter.loadFromStream(ctx, r); m_controlConverter.loadFromStream(ctx, r); m_evaluationConverter.loadFromStream(ctx, r); uint32_t count = r.readUint32Big(); for (uint32_t i = 0; i < count; ++i) { uint64_t hash = r.readUint64Big(); StageRuntimeObject<P, PipelineStage::Vertex> vertex; StageRuntimeObject<P, PipelineStage::Fragment> fragment; StageRuntimeObject<P, PipelineStage::Geometry> geometry; StageRuntimeObject<P, PipelineStage::Control> control; StageRuntimeObject<P, PipelineStage::Evaluation> evaluation; if (uint64_t vhash = r.readUint64Big()) vertex = m_vertexConverter.m_stageCache.find(vhash)->second; if (uint64_t fhash = r.readUint64Big()) fragment = m_fragmentConverter.m_stageCache.find(fhash)->second; if (uint64_t ghash = r.readUint64Big()) geometry = m_geometryConverter.m_stageCache.find(ghash)->second; if (uint64_t chash = r.readUint64Big()) control = m_controlConverter.m_stageCache.find(chash)->second; if (uint64_t ehash = r.readUint64Big()) evaluation = m_evaluationConverter.m_stageCache.find(ehash)->second; boo::AdditionalPipelineInfo additionalInfo = ReadAdditionalInfo(r); std::vector<boo::VertexElementDescriptor> vtxFmt = ReadVertexFormat(r); m_pipelineCache.insert( std::make_pair(hash, FinalPipeline<P>(*this, ctx, StageCollection<StageRuntimeObject<P, PipelineStage::Null>>( vertex, fragment, geometry, control, evaluation, additionalInfo, boo::VertexFormatInfo(vtxFmt.size(), vtxFmt.data()))))); } return true; } #define SPECIALIZE_STAGE_CONVERTER(P) \ template class StageConverter<P, PipelineStage::Vertex>; \ template class StageConverter<P, PipelineStage::Fragment>; \ template class StageConverter<P, PipelineStage::Geometry>; \ template class StageConverter<P, PipelineStage::Control>; \ template class StageConverter<P, PipelineStage::Evaluation>; #if BOO_HAS_GL template class PipelineConverter<PlatformType::OpenGL>; SPECIALIZE_STAGE_CONVERTER(PlatformType::OpenGL) #endif #if BOO_HAS_VULKAN template class PipelineConverter<PlatformType::Vulkan>; SPECIALIZE_STAGE_CONVERTER(PlatformType::Vulkan) #endif #if _WIN32 template class PipelineConverter<PlatformType::D3D11>; SPECIALIZE_STAGE_CONVERTER(PlatformType::D3D11) #endif #if BOO_HAS_METAL template class PipelineConverter<PlatformType::Metal>; SPECIALIZE_STAGE_CONVERTER(PlatformType::Metal) #endif #if BOO_HAS_NX template class PipelineConverter<PlatformType::NX>; SPECIALIZE_STAGE_CONVERTER(PlatformType::NX) #endif #endif } // namespace hecl
37.994048
120
0.682124
[ "geometry", "vector" ]
0dee3a35f63badba772bdbbfef03f41154d5dda1
375
cc
C++
src/h5tb.cc
volodymyrmigdal/hdf5.node
2786cedc94efc921986da8f387b9c5cc5118c1c0
[ "MIT" ]
83
2016-03-29T07:54:07.000Z
2022-03-02T16:54:30.000Z
src/h5tb.cc
volodymyrmigdal/hdf5.node
2786cedc94efc921986da8f387b9c5cc5118c1c0
[ "MIT" ]
92
2016-03-07T14:09:21.000Z
2021-11-30T10:40:16.000Z
src/h5tb.cc
volodymyrmigdal/hdf5.node
2786cedc94efc921986da8f387b9c5cc5118c1c0
[ "MIT" ]
31
2016-03-23T14:18:47.000Z
2021-09-03T01:19:20.000Z
#include <node.h> #include "file.h" #include "group.h" #include "h5_tb.hpp" using namespace v8; using namespace NodeHDF5; extern "C" { static void init_tb(v8::Local<v8::Object> target) { // create local scope HandleScope scope(v8::Isolate::GetCurrent()); // initialize wrapped objects H5tb::Initialize(target); } NODE_MODULE(h5tb, init_tb) }
17.857143
52
0.672
[ "object" ]
df039bbfbfb8475073b52ca9c706c3ae8ed5f3da
537
hpp
C++
libs/media/include/sge/media/optional_extension_set_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/media/include/sge/media/optional_extension_set_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/media/include/sge/media/optional_extension_set_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_MEDIA_OPTIONAL_EXTENSION_SET_FWD_HPP_INCLUDED #define SGE_MEDIA_OPTIONAL_EXTENSION_SET_FWD_HPP_INCLUDED #include <sge/media/extension_set.hpp> #include <fcppt/optional/object_fwd.hpp> namespace sge::media { using optional_extension_set = fcppt::optional::object<sge::media::extension_set>; } #endif
26.85
82
0.767225
[ "object" ]
df07c657929474fc977a85485fe3ea741a7ebac4
1,259
cpp
C++
src/processor.cpp
jo1990/CppND-System-Monitor-Project-Updated
1bcde664f8c5938b8283ddd745432952e350333e
[ "MIT" ]
null
null
null
src/processor.cpp
jo1990/CppND-System-Monitor-Project-Updated
1bcde664f8c5938b8283ddd745432952e350333e
[ "MIT" ]
null
null
null
src/processor.cpp
jo1990/CppND-System-Monitor-Project-Updated
1bcde664f8c5938b8283ddd745432952e350333e
[ "MIT" ]
null
null
null
#include "processor.h" #include "linux_parser.h" #include <numeric> // Return the aggregate CPU utilization float Processor::Utilization() { long cpu_user; long cpu_nice; long cpu_system; long cpu_idle; long cpu_iowait; long cpu_irq; long cpu_softirq; long cpu_steal; float CPU_Percentage; std::vector<std::string> cpu_data; cpu_data = LinuxParser::CpuUtilization(); cpu_user = std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_nice = std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_system = std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_idle = std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_iowait= std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_irq = std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_softirq = std::stoi(cpu_data.back()); cpu_data.pop_back(); cpu_steal= std::stoi(cpu_data.back()); cpu_data.pop_back(); const long idle = cpu_idle + cpu_iowait; const long nonIDLE = cpu_user + cpu_nice + cpu_system + cpu_irq + cpu_softirq + cpu_steal; const long total = idle + nonIDLE; CPU_Percentage =(total - idle)/static_cast<float>( total); return CPU_Percentage; }
20.639344
94
0.658459
[ "vector" ]
df0aaea7f9f3f5c3eeb54602d8331a3753acd775
1,651
cpp
C++
Graphics/CubeMap/CubeMap.cpp
JaminGamer/CodeBank
efd70bd2f1d7a2073582093f5a86f3facba8d231
[ "BSD-3-Clause" ]
null
null
null
Graphics/CubeMap/CubeMap.cpp
JaminGamer/CodeBank
efd70bd2f1d7a2073582093f5a86f3facba8d231
[ "BSD-3-Clause" ]
null
null
null
Graphics/CubeMap/CubeMap.cpp
JaminGamer/CodeBank
efd70bd2f1d7a2073582093f5a86f3facba8d231
[ "BSD-3-Clause" ]
null
null
null
#include "stdafx.h" CubeMap::CubeMap() { glGenTextures(1, &m_TextureHandle); glBindTexture(GL_TEXTURE_CUBE_MAP, m_TextureHandle); } CubeMap::~CubeMap() { glDeleteTextures(1, &m_TextureHandle); } void CubeMap::Init() { std::vector<std::string> t_Faces; // m_TextureHandle = loadCubemap(t_Faces); /*int width, height, nrChannels; unsigned char *data; for (GLuint i = 0; i < textures_faces.size(); i++) { data = stbi_load(textures_faces[i].c_str(), &width, &height, &nrChannels, 0); glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); }*/ } GLuint CubeMap::loadCubemap(std::vector<std::string> faces) { uint textureID = -1; /* glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); int width, height, nrChannels; for (uint i = 0; i < faces.size(); i++) { unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); stbi_image_free(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); */ return textureID; }
26.629032
85
0.724409
[ "vector" ]
df124038d6bdbe9456bf4f037e1a2f6d95f720b1
12,251
cc
C++
v8_5_7/src/ic/x64/ic-x64.cc
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
v8_5_7/src/ic/x64/ic-x64.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
v8_5_7/src/ic/x64/ic-x64.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if V8_TARGET_ARCH_X64 #include "src/codegen.h" #include "src/ic/ic.h" #include "src/ic/ic-compiler.h" #include "src/ic/stub-cache.h" namespace v8 { namespace internal { // ---------------------------------------------------------------------------- // Static IC stub generators. // #define __ ACCESS_MASM(masm) // Helper function used to load a property from a dictionary backing storage. // This function may return false negatives, so miss_label // must always call a backup property load that is complete. // This function is safe to call if name is not an internalized string, // and will jump to the miss_label in that case. // The generated code assumes that the receiver has slow properties, // is not a global object and does not have interceptors. static void GenerateDictionaryLoad(MacroAssembler* masm, Label* miss_label, Register elements, Register name, Register r0, Register r1, Register result) { // Register use: // // elements - holds the property dictionary on entry and is unchanged. // // name - holds the name of the property on entry and is unchanged. // // r0 - used to hold the capacity of the property dictionary. // // r1 - used to hold the index into the property dictionary. // // result - holds the result on exit if the load succeeded. Label done; // Probe the dictionary. NameDictionaryLookupStub::GeneratePositiveLookup(masm, miss_label, &done, elements, name, r0, r1); // If probing finds an entry in the dictionary, r1 contains the // index into the dictionary. Check that the value is a normal // property. __ bind(&done); const int kElementsStartOffset = NameDictionary::kHeaderSize + NameDictionary::kElementsStartIndex * kPointerSize; const int kDetailsOffset = kElementsStartOffset + 2 * kPointerSize; __ Test(Operand(elements, r1, times_pointer_size, kDetailsOffset - kHeapObjectTag), Smi::FromInt(PropertyDetails::TypeField::kMask)); __ j(not_zero, miss_label); // Get the value at the masked, scaled index. const int kValueOffset = kElementsStartOffset + kPointerSize; __ movp(result, Operand(elements, r1, times_pointer_size, kValueOffset - kHeapObjectTag)); } // Helper function used to store a property to a dictionary backing // storage. This function may fail to store a property even though it // is in the dictionary, so code at miss_label must always call a // backup property store that is complete. This function is safe to // call if name is not an internalized string, and will jump to the miss_label // in that case. The generated code assumes that the receiver has slow // properties, is not a global object and does not have interceptors. static void GenerateDictionaryStore(MacroAssembler* masm, Label* miss_label, Register elements, Register name, Register value, Register scratch0, Register scratch1) { // Register use: // // elements - holds the property dictionary on entry and is clobbered. // // name - holds the name of the property on entry and is unchanged. // // value - holds the value to store and is unchanged. // // scratch0 - used during the positive dictionary lookup and is clobbered. // // scratch1 - used for index into the property dictionary and is clobbered. Label done; // Probe the dictionary. NameDictionaryLookupStub::GeneratePositiveLookup( masm, miss_label, &done, elements, name, scratch0, scratch1); // If probing finds an entry in the dictionary, scratch0 contains the // index into the dictionary. Check that the value is a normal // property that is not read only. __ bind(&done); const int kElementsStartOffset = NameDictionary::kHeaderSize + NameDictionary::kElementsStartIndex * kPointerSize; const int kDetailsOffset = kElementsStartOffset + 2 * kPointerSize; const int kTypeAndReadOnlyMask = PropertyDetails::TypeField::kMask | PropertyDetails::AttributesField::encode(READ_ONLY); __ Test(Operand(elements, scratch1, times_pointer_size, kDetailsOffset - kHeapObjectTag), Smi::FromInt(kTypeAndReadOnlyMask)); __ j(not_zero, miss_label); // Store the value at the masked, scaled index. const int kValueOffset = kElementsStartOffset + kPointerSize; __ leap(scratch1, Operand(elements, scratch1, times_pointer_size, kValueOffset - kHeapObjectTag)); __ movp(Operand(scratch1, 0), value); // Update write barrier. Make sure not to clobber the value. __ movp(scratch0, value); __ RecordWrite(elements, scratch1, scratch0, kDontSaveFPRegs); } void LoadIC::GenerateNormal(MacroAssembler* masm) { Register dictionary = rax; DCHECK(!dictionary.is(LoadDescriptor::ReceiverRegister())); DCHECK(!dictionary.is(LoadDescriptor::NameRegister())); Label slow; __ movp(dictionary, FieldOperand(LoadDescriptor::ReceiverRegister(), JSObject::kPropertiesOffset)); GenerateDictionaryLoad(masm, &slow, dictionary, LoadDescriptor::NameRegister(), rbx, rdi, rax); __ ret(0); // Dictionary load failed, go slow (but don't miss). __ bind(&slow); LoadIC::GenerateRuntimeGetProperty(masm); } static void LoadIC_PushArgs(MacroAssembler* masm) { Register receiver = LoadDescriptor::ReceiverRegister(); Register name = LoadDescriptor::NameRegister(); Register slot = LoadDescriptor::SlotRegister(); Register vector = LoadWithVectorDescriptor::VectorRegister(); DCHECK(!rdi.is(receiver) && !rdi.is(name) && !rdi.is(slot) && !rdi.is(vector)); __ PopReturnAddressTo(rdi); __ Push(receiver); __ Push(name); __ Push(slot); __ Push(vector); __ PushReturnAddressFrom(rdi); } void LoadIC::GenerateMiss(MacroAssembler* masm) { // The return address is on the stack. Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->ic_load_miss(), 1); LoadIC_PushArgs(masm); // Perform tail call to the entry. __ TailCallRuntime(Runtime::kLoadIC_Miss); } void LoadIC::GenerateRuntimeGetProperty(MacroAssembler* masm) { // The return address is on the stack. Register receiver = LoadDescriptor::ReceiverRegister(); Register name = LoadDescriptor::NameRegister(); DCHECK(!rbx.is(receiver) && !rbx.is(name)); __ PopReturnAddressTo(rbx); __ Push(receiver); __ Push(name); __ PushReturnAddressFrom(rbx); // Do tail-call to runtime routine. __ TailCallRuntime(Runtime::kGetProperty); } void KeyedLoadIC::GenerateMiss(MacroAssembler* masm) { // The return address is on the stack. Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->ic_keyed_load_miss(), 1); LoadIC_PushArgs(masm); // Perform tail call to the entry. __ TailCallRuntime(Runtime::kKeyedLoadIC_Miss); } void KeyedLoadIC::GenerateRuntimeGetProperty(MacroAssembler* masm) { // The return address is on the stack. Register receiver = LoadDescriptor::ReceiverRegister(); Register name = LoadDescriptor::NameRegister(); DCHECK(!rbx.is(receiver) && !rbx.is(name)); __ PopReturnAddressTo(rbx); __ Push(receiver); __ Push(name); __ PushReturnAddressFrom(rbx); // Do tail-call to runtime routine. __ TailCallRuntime(Runtime::kKeyedGetProperty); } static void StoreIC_PushArgs(MacroAssembler* masm) { Register receiver = StoreWithVectorDescriptor::ReceiverRegister(); Register name = StoreWithVectorDescriptor::NameRegister(); Register value = StoreWithVectorDescriptor::ValueRegister(); Register slot = StoreWithVectorDescriptor::SlotRegister(); Register vector = StoreWithVectorDescriptor::VectorRegister(); Register temp = r11; DCHECK(!AreAliased(receiver, name, value, slot, vector, temp)); __ PopReturnAddressTo(temp); __ Push(value); __ Push(slot); __ Push(vector); __ Push(receiver); __ Push(name); __ PushReturnAddressFrom(temp); } void StoreIC::GenerateMiss(MacroAssembler* masm) { // Return address is on the stack. StoreIC_PushArgs(masm); // Perform tail call to the entry. __ TailCallRuntime(Runtime::kStoreIC_Miss); } void StoreIC::GenerateNormal(MacroAssembler* masm) { Register receiver = StoreDescriptor::ReceiverRegister(); Register name = StoreDescriptor::NameRegister(); Register value = StoreDescriptor::ValueRegister(); Register dictionary = r11; DCHECK(!AreAliased(dictionary, StoreWithVectorDescriptor::VectorRegister(), StoreWithVectorDescriptor::SlotRegister())); Label miss; __ movp(dictionary, FieldOperand(receiver, JSObject::kPropertiesOffset)); GenerateDictionaryStore(masm, &miss, dictionary, name, value, r8, r9); Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->ic_store_normal_hit(), 1); __ ret(0); __ bind(&miss); __ IncrementCounter(counters->ic_store_normal_miss(), 1); GenerateMiss(masm); } void KeyedStoreIC::GenerateMiss(MacroAssembler* masm) { // Return address is on the stack. StoreIC_PushArgs(masm); // Do tail-call to runtime routine. __ TailCallRuntime(Runtime::kKeyedStoreIC_Miss); } void KeyedStoreIC::GenerateSlow(MacroAssembler* masm) { // Return address is on the stack. StoreIC_PushArgs(masm); // Do tail-call to runtime routine. __ TailCallRuntime(Runtime::kKeyedStoreIC_Slow); } #undef __ Condition CompareIC::ComputeCondition(Token::Value op) { switch (op) { case Token::EQ_STRICT: case Token::EQ: return equal; case Token::LT: return less; case Token::GT: return greater; case Token::LTE: return less_equal; case Token::GTE: return greater_equal; default: UNREACHABLE(); return no_condition; } } bool CompareIC::HasInlinedSmiCode(Address address) { // The address of the instruction following the call. Address test_instruction_address = address + Assembler::kCallTargetAddressOffset; // If the instruction following the call is not a test al, nothing // was inlined. return *test_instruction_address == Assembler::kTestAlByte; } void PatchInlinedSmiCode(Isolate* isolate, Address address, InlinedSmiCheck check) { // The address of the instruction following the call. Address test_instruction_address = address + Assembler::kCallTargetAddressOffset; // If the instruction following the call is not a test al, nothing // was inlined. if (*test_instruction_address != Assembler::kTestAlByte) { DCHECK(*test_instruction_address == Assembler::kNopByte); return; } Address delta_address = test_instruction_address + 1; // The delta to the start of the map check instruction and the // condition code uses at the patched jump. uint8_t delta = *reinterpret_cast<uint8_t*>(delta_address); if (FLAG_trace_ic) { PrintF("[ patching ic at %p, test=%p, delta=%d\n", static_cast<void*>(address), static_cast<void*>(test_instruction_address), delta); } // Patch with a short conditional jump. Enabling means switching from a short // jump-if-carry/not-carry to jump-if-zero/not-zero, whereas disabling is the // reverse operation of that. Address jmp_address = test_instruction_address - delta; DCHECK((check == ENABLE_INLINED_SMI_CHECK) ? (*jmp_address == Assembler::kJncShortOpcode || *jmp_address == Assembler::kJcShortOpcode) : (*jmp_address == Assembler::kJnzShortOpcode || *jmp_address == Assembler::kJzShortOpcode)); Condition cc = (check == ENABLE_INLINED_SMI_CHECK) ? (*jmp_address == Assembler::kJncShortOpcode ? not_zero : zero) : (*jmp_address == Assembler::kJnzShortOpcode ? not_carry : carry); *jmp_address = static_cast<byte>(Assembler::kJccShortPrefix | cc); } } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_X64
34.22067
79
0.700514
[ "object", "vector" ]
df1a0f721ce9bda447c040385633838e8fb41273
2,755
cpp
C++
LeetCode/C++/1524. Number of Sub-arrays With Odd Sum.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/1524. Number of Sub-arrays With Odd Sum.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/1524. Number of Sub-arrays With Odd Sum.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//TLE //131 / 151 test cases passed. class Solution { public: int numOfSubarrays(vector<int>& arr) { int MOD = 1e9+7; int n = arr.size(); if(all_of(arr.begin(), arr.end(), [](int& e){return !(e&1);})){ return 0; } if(all_of(arr.begin(), arr.end(), [&n](int& e){return e&1;})){ int ans = 0; while(n > 0){ ans += n; n -= 2; } return ans; } int ans = 0; for(int i = 0; i < n; ++i){ int subsum = 0; for(int j = i; j < n; ++j){ subsum += arr[j]; if(subsum&1){ ++ans; if(ans > MOD) ans -= MOD; } } } return ans; } }; //DP //https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/discuss/754702/Some-hints-to-help-you-solve-this-problem-on-your-own //Runtime: 392 ms, faster than 67.62% of C++ online submissions for Number of Sub-arrays With Odd Sum. //Memory Usage: 122.9 MB, less than 100.00% of C++ online submissions for Number of Sub-arrays With Odd Sum. class Solution { public: int numOfSubarrays(vector<int>& arr) { int n = arr.size(); int MOD = 1e9+7; //padding ahead arr.insert(arr.begin(), 0); //dp[i]: dp value of arr[0...i] vector<int> zeroCounts(n+1); vector<int> oneCounts(n+1); vector<int> cumsums(n+1); for(int i = 1; i <= n; ++i){ cumsums[i] = (cumsums[i-1] + arr[i])&1; if(!(arr[i]&1)) zeroCounts[i] = 1; else oneCounts[i] = 1; //arr[1...i] = arr[1...i-1] + arr[i] if(!(arr[i]&1)){ zeroCounts[i] = (zeroCounts[i]+zeroCounts[i-1])%MOD; oneCounts[i] = (oneCounts[i]+oneCounts[i-1])%MOD; }else if(arr[i]){ zeroCounts[i] = (zeroCounts[i]+oneCounts[i-1])%MOD; oneCounts[i] = (oneCounts[i]+zeroCounts[i-1])%MOD; } } // for(int i = 0; i <= n; ++i){ // cout << cumsums[i] << " "; // } // cout << endl; // for(int i = 0; i <= n; ++i){ // cout << zeroCounts[i] << " "; // } // cout << endl; // for(int i = 0; i <= n; ++i){ // cout << oneCounts[i] << " "; // } // cout << endl; //use custom add function to avoid overflow return accumulate(oneCounts.begin(), oneCounts.end(), 0 ,[&MOD](int& a, int& b){return (a+b)%MOD;}); } };
29.623656
134
0.421416
[ "vector" ]
b30903ac89c804a405297760cf089ecbfb862f99
10,456
cc
C++
ray_tracing.cc
adamantine-sim/ray_tracing
9a135e778dfcd3825e8d4809297ce3149a16a5db
[ "BSD-3-Clause" ]
1
2021-06-22T13:18:53.000Z
2021-06-22T13:18:53.000Z
ray_tracing.cc
adamantine-sim/ray_tracing
9a135e778dfcd3825e8d4809297ce3149a16a5db
[ "BSD-3-Clause" ]
null
null
null
ray_tracing.cc
adamantine-sim/ray_tracing
9a135e778dfcd3825e8d4809297ce3149a16a5db
[ "BSD-3-Clause" ]
1
2021-06-16T19:59:21.000Z
2021-06-16T19:59:21.000Z
/* Copyright (c) 2021, the adamantine authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #include <ArborX.hpp> #include <ArborX_Ray.hpp> #include <Kokkos_Core.hpp> #include <boost/program_options.hpp> #include <fstream> template <typename MemorySpace> struct TriangleBoundingVolume { Kokkos::View<ArborX::Experimental::Triangle *, MemorySpace> triangles; }; template <typename MemorySpace> struct ArborX::AccessTraits<TriangleBoundingVolume<MemorySpace>, ArborX::PrimitivesTag> { using memory_space = MemorySpace; KOKKOS_FUNCTION static std::size_t size(const TriangleBoundingVolume<MemorySpace> &tbv) { return tbv.triangles.extent(0); } KOKKOS_FUNCTION static ArborX::Box get(TriangleBoundingVolume<MemorySpace> const &tbv, std::size_t const i) { auto const &triangle = tbv.triangles(i); float max_coord[3] = {triangle.a[0], triangle.a[1], triangle.a[2]}; float min_coord[3] = {triangle.a[0], triangle.a[1], triangle.a[2]}; for (int i = 0; i < 3; ++i) { // Max if (triangle.b[i] > max_coord[i]) max_coord[i] = triangle.b[i]; if (triangle.c[i] > max_coord[i]) max_coord[i] = triangle.c[i]; // Min if (triangle.b[i] < min_coord[i]) min_coord[i] = triangle.b[i]; if (triangle.c[i] < min_coord[i]) min_coord[i] = triangle.c[i]; } return {{min_coord[0], min_coord[1], min_coord[2]}, {max_coord[0], max_coord[1], max_coord[2]}}; } }; template <typename MemorySpace> struct Rays { Kokkos::View<ArborX::Experimental::Ray *, MemorySpace> _rays; }; template <typename MemorySpace> struct ArborX::AccessTraits<Rays<MemorySpace>, ArborX::PredicatesTag> { using memory_space = MemorySpace; KOKKOS_FUNCTION static std::size_t size(const Rays<MemorySpace> &rays) { return rays._rays.extent(0); } KOKKOS_FUNCTION static auto get(Rays<MemorySpace> const &rays, std::size_t i) { return attach(intersects(rays._rays(i)), (int)i); } }; template <typename MemorySpace> struct ProjectPointDistance { Kokkos::View<ArborX::Experimental::Triangle *, MemorySpace> triangles; Kokkos::View<float *, MemorySpace> distance; template <typename Predicate> KOKKOS_FUNCTION void operator()(Predicate const &predicate, int const primitive_index) const { auto const &ray = ArborX::getGeometry(predicate); float t; float u; float v; int const i = getData(predicate); if (rayTriangleIntersect(ray, triangles(primitive_index), t, u, v)) { distance(i) = t; } } }; ArborX::Point read_point(char *facet) { char f1[4] = {facet[0], facet[1], facet[2], facet[3]}; char f2[4] = {facet[4], facet[5], facet[6], facet[7]}; char f3[4] = {facet[8], facet[9], facet[10], facet[11]}; ArborX::Point vertex; vertex[0] = *(reinterpret_cast<float *>(f1)); vertex[1] = *(reinterpret_cast<float *>(f2)); vertex[2] = *(reinterpret_cast<float *>(f3)); return vertex; } // Algorithm to read STL is based on http://www.sgh1.net/posts/read-stl-file.md template <typename MemorySpace> Kokkos::View<ArborX::Experimental::Triangle *, MemorySpace> read_stl(std::string const &filename) { std::ifstream file(filename.c_str(), std::ios::binary); ARBORX_ASSERT(file.good()); // read 80 byte header char header_info[80] = ""; file.read(header_info, 80); // Read the number of Triangle unsigned long long int n_triangles = 0; { char n_tri[4]; file.read(n_tri, 4); n_triangles = *(reinterpret_cast<unsigned long long *>(n_tri)); } Kokkos::View<ArborX::Experimental::Triangle *, MemorySpace> triangles( Kokkos::view_alloc(Kokkos::WithoutInitializing, "triangles"), n_triangles); auto triangles_host = Kokkos::create_mirror_view(triangles); for (unsigned int i = 0; i < n_triangles; ++i) { char facet[50]; // read one 50-byte triangle file.read(facet, 50); // populate each point of the triangle // facet + 12 skips the triangle's unit normal auto p1 = read_point(facet + 12); auto p2 = read_point(facet + 24); auto p3 = read_point(facet + 36); // add a new triangle to the View triangles_host(i) = {p1, p2, p3}; } file.close(); Kokkos::deep_copy(triangles, triangles_host); return triangles; } template <typename MemorySpace> Kokkos::View<ArborX::Experimental::Ray *, MemorySpace> read_ray_file(std::string const &filename) { std::ifstream file(filename.c_str()); ARBORX_ASSERT(file.good()); int n_rays = 0; file >> n_rays; Kokkos::View<ArborX::Experimental::Ray *, MemorySpace> rays( Kokkos::view_alloc(Kokkos::WithoutInitializing, "rays"), n_rays); auto rays_host = Kokkos::create_mirror_view(rays); for (int i = 0; i < n_rays; ++i) { float x, y, z, dir_x, dir_y, dir_z; file >> x >> y >> z >> dir_x >> dir_y >> dir_z; rays_host(i) = {{x, y, z}, {dir_x, dir_y, dir_z}}; } file.close(); Kokkos::deep_copy(rays, rays_host); return rays; } void outputTXT(Kokkos::View<ArborX::Point *, Kokkos::HostSpace> point_cloud, std::ostream &file, std::string const &delimiter) { int const n_points = point_cloud.extent(0); for (int i = 0; i < n_points; ++i) { file << point_cloud(i)[0] << delimiter << point_cloud(i)[1] << delimiter << point_cloud(i)[2] << "\n"; } } void outputVTK( Kokkos::View<ArborX::Point *, Kokkos::HostSpace> full_point_cloud, std::ostream &file) { // For the vtk output, we remove all the points that are at infinity std::vector<ArborX::Point> point_cloud; for (unsigned int i = 0; i < full_point_cloud.extent(0); ++i) { if (full_point_cloud(i)[0] < KokkosExt::ArithmeticTraits::max<float>::value) { point_cloud.emplace_back(full_point_cloud(i)[0], full_point_cloud(i)[1], full_point_cloud(i)[2]); } } // Write the header file << "# vtk DataFile Version 2.0\n"; file << "Ray tracing\n"; file << "ASCII\n"; file << "DATASET POLYDATA\n"; int const n_points = point_cloud.size(); file << "POINTS " << n_points << " float\n"; for (int i = 0; i < n_points; ++i) { file << point_cloud[i][0] << " " << point_cloud[i][1] << " " << point_cloud[i][2] << "\n"; } // We need to associate a value to each point. We arbitrarly choose 1. file << "POINT_DATA " << n_points << "\n"; file << "SCALARS value float 1\n"; file << "LOOKUP_TABLE table\n"; for (int i = 0; i < n_points; ++i) { file << "1.0\n"; } } int main(int argc, char *argv[]) { using ExecutionSpace = Kokkos::DefaultExecutionSpace; using MemorySpace = ExecutionSpace::memory_space; Kokkos::ScopeGuard guard(argc, argv); namespace bpo = boost::program_options; std::string stl_filename; std::string ray_filename; std::string output_filename; std::string output_type; int n_ray_files; bpo::options_description desc("Allowed options"); // clang-format off desc.add_options() ("help,h", "help message" ) ("stl_file,s", bpo::value<std::string>(&stl_filename), "name of the STL file") ("ray_files,r", bpo::value<std::string>(&ray_filename), "name of the ray file") ("n_ray_files,n", bpo::value<int>(&n_ray_files), "number of ray files") ("output_files,o", bpo::value<std::string>(&output_filename), "name of the output file") ("output_type,t", bpo::value<std::string>(&output_type), "type of the output: csv, numpy, or vtk") ; // clang-format on bpo::variables_map vm; bpo::store(bpo::command_line_parser(argc, argv).options(desc).run(), vm); bpo::notify(vm); if (vm.count("help") > 0) { std::cout << desc << '\n'; return 1; } // Read the STL file Kokkos::Profiling::pushRegion("ArborX::read_stl"); auto triangles = read_stl<MemorySpace>(stl_filename); Kokkos::Profiling::popRegion(); // Build the BVH ExecutionSpace exec_space; ArborX::BVH<MemorySpace> bvh(exec_space, TriangleBoundingVolume<MemorySpace>{triangles}); for (int i = 0; i < n_ray_files; ++i) { // Read the ray file std::string current_ray_filename = ray_filename + "-" + std::to_string(i) + ".txt"; Kokkos::Profiling::pushRegion("ArborX::read_ray_files"); auto rays = read_ray_file<MemorySpace>(current_ray_filename); Kokkos::Profiling::popRegion(); unsigned int n_rays = rays.extent(0); Kokkos::View<float *, MemorySpace> distance( Kokkos::view_alloc(Kokkos::WithoutInitializing, "distance"), n_rays); Kokkos::deep_copy(distance, -1.); bvh.query(exec_space, Rays<MemorySpace>{rays}, ProjectPointDistance<MemorySpace>{triangles, distance}); Kokkos::View<ArborX::Point *, MemorySpace> point_cloud("point_cloud", n_rays); Kokkos::parallel_for( "project_points", Kokkos::RangePolicy<ExecutionSpace>(0, n_rays), KOKKOS_LAMBDA(int i) { if (distance(i) >= 0) { point_cloud(i) = { rays(i)._origin[0] + distance(i) * rays(i)._direction[0], rays(i)._origin[1] + distance(i) * rays(i)._direction[1], rays(i)._origin[2] + distance(i) * rays(i)._direction[2]}; } else { float max_value = KokkosExt::ArithmeticTraits::max<float>::value; point_cloud(i) = {max_value, max_value, max_value}; } }); auto point_cloud_host = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace{}, point_cloud); // Write results to file Kokkos::Profiling::pushRegion("ArborX::write_results"); if ((output_type == "csv") || (output_type == "numpy")) { std::string delimiter = " "; if (output_type == "csv") delimiter = ","; else delimiter = " "; std::ofstream file; file.open(output_filename + "-" + std::to_string(i) + ".txt"); outputTXT(point_cloud_host, file, delimiter); file.close(); } else { std::ofstream file; file.open(output_filename + "-" + std::to_string(i) + ".vtk"); outputVTK(point_cloud_host, file); file.close(); } Kokkos::Profiling::popRegion(); } }
29.370787
92
0.633321
[ "vector" ]
b312c9da460f4580078e04671f377ef157f8c8e7
880
hpp
C++
tensor/util.hpp
leanil/LambdaGen
aff49962759c1ce1fcfb2a1cc4a9a11d78e713a9
[ "BSD-3-Clause" ]
9
2017-04-25T11:28:01.000Z
2019-07-11T13:53:27.000Z
tensor/util.hpp
leanil/LambdaGen
aff49962759c1ce1fcfb2a1cc4a9a11d78e713a9
[ "BSD-3-Clause" ]
16
2018-03-21T20:41:14.000Z
2019-06-25T16:25:35.000Z
tensor/util.hpp
leanil/LambdaGen
aff49962759c1ce1fcfb2a1cc4a9a11d78e713a9
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <algorithm> #include <cmath> #include <map> #include <numeric> #include <sstream> #include <string> #include <vector> double* init_data(int a, int n) { double* seq = new double[n]; std::iota(seq, seq + n, a); return seq; } void free_data(const std::map<std::string, double*>& userData) { for (const auto& elem : userData) delete[] elem.second; } template<typename View> bool check(View const& view, std::string expect) { std::stringstream ss; ss << view; return ss.str() == expect; } template<typename View> bool viewEq(View const& a, View const& b) { return a == b; } bool viewEq(double a, double b) { double abs_err = std::abs(a - b), rel_err = abs_err / a; return std::min(abs_err, rel_err) < 1e-6; } double min_time(const std::vector<double>& v) { return *std::min_element(v.begin(), v.end()); }
21.463415
64
0.640909
[ "vector" ]
b31ac9005e26e6fc572d29a19c8e8a79cb9202c3
1,622
cpp
C++
GY/P1198.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
GY/P1198.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
GY/P1198.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<cctype> #include<ctime> #include<iostream> #include<string> #include<map> #include<queue> #include<stack> #include<set> #include<vector> #include<iomanip> #include<list> #include<bitset> #include<sstream> #include<fstream> #include<complex> #include<algorithm> #if __cplusplus >= 201103L #include <unordered_map> #include <unordered_set> #endif #define int long long using namespace std; const int INF = 0x3f3f3f3f3f3f3f3f; int tree[800010]; int mod; void update(int l1,int r1,int add,int x,int s){ if(l1==r1){ tree[x]=add; return; } int mid=(l1+r1)>>1; if(mid>=s) update(l1,mid,add,x<<1,s); if(mid<s) update(mid+1,r1,add,x<<1|1,s); tree[x]=max(tree[x<<1],tree[x<<1|1])%mod; } int query(int ll,int rr,int o,int l,int r) { if(ll<=l&&rr>=r) return tree[o]; int mid=(l+r)>>1; int a=INF,b=INF; if(mid>=ll) a=query(ll,rr,o<<1,l,mid); if(mid<rr) b=query(ll,rr,o<<1|1,mid+1,r); return max(a,b); } int cnt,t; signed main(){ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #ifdef WindCry1 freopen("C:/Users/LENOVO/Desktop/in.txt","r",stdin); #endif int n; scanf("%lld%lld",&n,&mod); //memset(tree,0,sizeof tree); int t1=n; while(t1--){ char s[2];int x; scanf("%s %lld",s,&x); if(s[0]=='A'){ update(1,n,(x+t)%mod,1,cnt+1); cnt++; } cout<<query(1,1,1,1,n)<<endl; if(s[0]=='Q'){ if(x==0) t=0; else t=query(cnt-x+1,cnt,1,1,n)%mod; //for(int i=1;i<=n;i++) printf("%lld\n",tree[i]); //printf("%lld %lld\n",t,cnt); } cout<<t<<endl; } return 0; }
20.794872
53
0.612207
[ "vector" ]
b32361748cca9dce6503c263a4539e35d30e6916
642
cpp
C++
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_property/property_identifiable.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
5
2020-03-11T14:36:13.000Z
2021-09-09T09:01:15.000Z
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_property/property_identifiable.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
1
2020-06-07T17:25:04.000Z
2020-07-15T07:36:10.000Z
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_property/property_identifiable.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
2
2020-11-30T08:17:53.000Z
2021-06-19T05:07:07.000Z
#include "property_identifiable.h" namespace srrg2_core { bool PropertyIdentifiablePtrVectorInterface::pushBack(Identifiable* id) { if (!canAssign(id)) return false; resize(size() + 1); return assign(size() - 1, id); } bool PropertyIdentifiablePtrVectorInterface::pushBack(std::shared_ptr<Identifiable> id) { if (!canAssign(id)) { std::cerr << "PropertyIdentifiablePtrVectorInterface::pushBack|warning, cannot assign object " "with ID [" << id << "]\n"; return false; } resize(size() + 1); return assign(size() - 1, id); } } // namespace srrg2_core
26.75
100
0.627726
[ "object" ]
b336333ba891fdf2e9c71d4cef83cd3320057f5d
14,395
hpp
C++
sparse2d/python/deconvolve.hpp
starcksophie/pysap
c50b128039a54b6b26dcc3c7bd13fda304b8388c
[ "CECILL-B" ]
46
2018-03-16T14:36:53.000Z
2022-03-15T21:46:16.000Z
sparse2d/python/deconvolve.hpp
starcksophie/pysap
c50b128039a54b6b26dcc3c7bd13fda304b8388c
[ "CECILL-B" ]
139
2018-03-02T10:06:50.000Z
2022-03-08T08:57:37.000Z
sparse2d/python/deconvolve.hpp
starcksophie/pysap
c50b128039a54b6b26dcc3c7bd13fda304b8388c
[ "CECILL-B" ]
17
2018-04-03T11:25:59.000Z
2021-06-15T14:32:09.000Z
#ifndef DECONVOLVE_H_ #define DECONVOLVE_H_ #include <iostream> #include "sparse2d/IM_Obj.h" #include "sparse2d/IM_IO.h" #include "sparse2d/MR_Obj.h" #include "sparse2d/IM_Deconv.h" #include "sparse2d/MR_Deconv.h" #include "sparse2d/MR_Sigma.h" #include "sparse2d/MR_Sigma.h" #include "filter.hpp" #define NBR_OK_METHOD 5 class MRDeconvolve { public: MRDeconvolve(int type_of_deconvolution = 3, int type_of_multiresolution_transform = 2, int type_of_filters = 1, int number_of_undecimated_scales = -1, float sigma_noise = 0., int type_of_noise = 1, int number_of_scales = DEFAULT_NBR_SCALE, float nsigma = DEFAULT_N_SIGMA, int number_of_iterations = DEFAULT_MAX_ITER_DECONV, float epsilon = DEFAULT_EPSILON_DECONV, bool psf_max_shift = true, bool verbose = false, bool optimization=false, float fwhm_param = 0., float convergence_param = 1., float regul_param = 0., std::string first_guess = "", std::string icf_filename = "", std::string rms_map = "", bool kill_last_scale=false, bool positive_constraint=true, bool keep_positiv_sup=false, bool sup_isol=false, float pas_codeur = 1, float sigma_gauss = 0, float mean_gauss = 0); void Info(); py::array_t<float> Deconvolve(py::array_t<float>& arr, py::array_t<float>& psf); void DeconvInit(); void NoiseModelInit(); private: float convergence_param; float regul_param; int number_of_undecimated_scales; std::string first_guess; std::string icf_filename; std::string rms_map; bool kill_last_scale; bool positive_constraint; bool keep_positiv_sup; bool sup_isol; float sigma_noise; float nsigma; int number_of_iterations; bool psf_max_shift; bool verbose; bool optimization; float fwhm_param; float pas_codeur; float sigma_gauss; float mean_gauss; int number_of_scales; float epsilon; MRDeconv CDec; MRNoiseModel model_data; bool gauss_conv = false; bool use_nsigma = false; type_sb_filter sb_filter = F_MALLAT_7_9; type_noise stat_noise = DEFAULT_STAT_NOISE; type_transform transform = DEFAULT_TRANSFORM; type_deconv deconv = DEFAULT_DECONV; type_deconv TabMethod[NBR_OK_METHOD] = {DEC_MR_CITTERT,DEC_MR_GRADIENT, DEC_MR_LUCY, DEC_MR_MAP,DEC_MR_VAGUELET}; }; MRDeconvolve::MRDeconvolve(int type_of_deconvolution, int type_of_multiresolution_transform, int type_of_filters, int number_of_undecimated_scales, float sigma_noise, int type_of_noise, int number_of_scales, float nsigma, int number_of_iterations, float epsilon, bool psf_max_shift, bool verbose, bool optimization, float fwhm_param, float convergence_param, float regul_param, std::string first_guess, std::string icf_filename, std::string rms_map, bool kill_last_scale, bool positive_constraint, bool keep_positiv_sup, bool sup_isol, float pas_codeur, float sigma_gauss, float mean_gauss) { this->convergence_param = convergence_param; this->regul_param = regul_param; this->number_of_undecimated_scales = number_of_undecimated_scales; this->first_guess = first_guess; this->icf_filename = icf_filename; this->rms_map =rms_map; this->kill_last_scale = kill_last_scale; this->positive_constraint = positive_constraint; this->keep_positiv_sup = keep_positiv_sup; this->sup_isol = sup_isol; this->sigma_noise = sigma_noise; this->nsigma = nsigma; this->number_of_iterations = number_of_iterations; this->psf_max_shift = psf_max_shift; this->optimization = optimization; this->verbose = verbose; this->number_of_scales = number_of_scales; this->fwhm_param = fwhm_param; this->pas_codeur = pas_codeur; this->sigma_gauss = sigma_gauss; this->mean_gauss = mean_gauss; if (this->fwhm_param > 0) this->gauss_conv = True; if (this->gauss_conv && this->icf_filename != "") throw std::invalid_argument("Error: icf_filename and fwhm_param options are not compatible .."); if ((epsilon < 0) || (epsilon > 1.)) this->epsilon = DEFAULT_EPSILON_DECONV; else this->epsilon = epsilon; if (type_of_deconvolution <= 0 || type_of_deconvolution > NBR_OK_METHOD) throw std::invalid_argument("Error: bad type of deconvolution: " + std::to_string(type_of_deconvolution)); else if (type_of_deconvolution != 3) this->deconv = (type_deconv) (TabMethod[type_of_deconvolution-1]); if (type_of_noise > 0 && type_of_noise < NBR_NOISE && type_of_noise != 1) this->stat_noise = (type_noise) (type_of_noise-1); else if (type_of_noise != 1) throw std::invalid_argument("Error: bad type of noise: " + std::to_string(type_of_noise)); if (type_of_multiresolution_transform != 2 && type_of_multiresolution_transform > 0 && type_of_multiresolution_transform <= NBR_TRANSFORM) this->transform = (type_transform)(type_of_multiresolution_transform-1); else if (type_of_multiresolution_transform != 2) throw std::invalid_argument("Error: bad type of transform: " + std::to_string(type_of_multiresolution_transform)); if (type_of_filters != 1) this->sb_filter = get_filter_bank(int_to_char(type_of_filters)); if (sigma_noise != 0.) this->stat_noise = NOISE_GAUSSIAN; if (this->sigma_gauss != 0 && this->pas_codeur != 1 && this->mean_gauss != 0) { this->stat_noise = NOISE_POISSON; this->sigma_noise = 1.; } if ((number_of_scales <= 1 || number_of_scales > MAX_SCALE) && number_of_scales != DEFAULT_NBR_SCALE) throw std::invalid_argument("Error: bad number of scales: ]1; " + std::to_string(MAX_SCALE) + "]"); if (this->nsigma != DEFAULT_N_SIGMA) { this->use_nsigma = true; if (nsigma <= 0.) this->nsigma = DEFAULT_N_SIGMA; } if (number_of_iterations <= 0) this->number_of_iterations = DEFAULT_MAX_ITER_DECONV; if (this->regul_param < 0.) this->regul_param = 0.1; if (type_of_deconvolution <= 0 || type_of_deconvolution > NBR_OK_METHOD) throw std::invalid_argument("Error: bad type of deconvolution: " + std::to_string(type_of_deconvolution)); if ((this->rms_map != "") && (this->stat_noise != NOISE_NON_UNI_ADD) && (this->stat_noise != NOISE_CORREL)) throw std::invalid_argument(std::string("Error: this noise model is not correct when RMS map option is set.\n Valid models are: \n ") + + StringNoise(NOISE_NON_UNI_ADD) + " " + StringNoise(NOISE_CORREL)); if ((this->stat_noise == NOISE_CORREL) && (this->rms_map == "")) throw std::invalid_argument("Error: this noise model needs a noise map (rms_map option) "); if ((isotrop(transform) == False) && ((this->stat_noise == NOISE_NON_UNI_ADD) || (this->stat_noise == NOISE_NON_UNI_MULT))) throw std::invalid_argument(std::string("Error: with this transform, non stationary noise models are not valid : ") + StringFilter(FILTER_THRESHOLD)); if (this->kill_last_scale && this->optimization) throw std::invalid_argument("Error: kill_last_scale and optimization options are not compatible ... "); if (this->kill_last_scale && ((this->deconv == DEC_MR_LUCY) || (this->deconv ==DEC_MR_MAP))) throw std::invalid_argument("Error: kill_last_scale option cannot be used with this deconvolution method ... "); if ((this->number_of_iterations == DEFAULT_MAX_ITER_DECONV) && (this->deconv == DEC_MR_VAGUELET)) this->number_of_iterations = 10; if ((this->transform != TO_UNDECIMATED_MALLAT) && (this->transform != TO_MALLAT) && (type_of_filters != 1)) throw std::invalid_argument("Error: option type_of_filters is only valid with Mallat transform ..."); if ((convergence_param == 1.) && (this->regul_param > 1.)) this->convergence_param = 1. / (2. * this->regul_param); } void MRDeconvolve::Info() { cout << endl << endl << "PARAMETERS: " << endl << endl; cout << "Transform = " << StringTransform(this->transform) << endl; cout << "Number of scales = " << this->number_of_scales << endl; if (this->stat_noise == NOISE_GAUSSIAN) { cout << "Type of Noise = GAUSSIAN" << endl; if (this->sigma_noise > 0) cout << "Sigma Noise = " << this->sigma_noise << endl; } else { cout << "Type of Noise = POISSON" << endl; cout << " Gain = " << this->pas_codeur << endl; cout << " Read-out Noise Sigma = " << this->sigma_gauss << endl; cout << " Read-out Mean = " << this->mean_gauss << endl; } cout << "Deconv = " << StringDeconv(this->deconv) << endl; cout << "N_Sigma = " << this->nsigma << endl; cout << "Epsilon = " << this->epsilon << endl; cout << "Max_Iter = " << this->number_of_iterations << endl; cout << "Convergence paramter = " << this->convergence_param << endl; if (this->kill_last_scale) cout << "Kill last scale " << endl; cout << "Fwhm = " << this->fwhm_param << endl; } void MRDeconvolve::DeconvInit() { this->CDec.KillLastScale = (Bool)this->kill_last_scale; this->CDec.PositivConstraint = (Bool)this->positive_constraint; this->CDec.DecMethod = this->deconv; this->CDec.PsfMaxShift = (Bool)this->psf_max_shift; this->CDec.Noise_Ima = this->sigma_noise; this->CDec.MaxIter = this->number_of_iterations; this->CDec.EpsCvg = this->epsilon; this->CDec.IterCvg = this->convergence_param; this->CDec.GaussConv = (Bool)this->gauss_conv; this->CDec.Fwhm = this->fwhm_param; this->CDec.OptimParam = (Bool)this->optimization; this->CDec.Verbose = (Bool)this->verbose; this->CDec.RegulParam = this->regul_param; this->CDec.StatNoise = this->stat_noise; } void MRDeconvolve::NoiseModelInit() { int nbr_band = model_data.nbr_band(); model_data.OnlyPositivDetect = (Bool)this->keep_positiv_sup; if (this->sigma_noise > FLOAT_EPSILON) model_data.SigmaNoise = this->sigma_noise; if (this->nsigma != DEFAULT_N_SIGMA) { for (int b = 0; b < nbr_band; b++) model_data.NSigma[b] = this->nsigma; } model_data.NiterSigmaClip = 1; model_data.SizeBlockSigmaNoise = DEFAULT_SIZE_BLOCK_SIG; model_data.CCD_Gain = this->pas_codeur; model_data.CCD_ReadOutSigma = this->sigma_gauss; model_data.CCD_ReadOutMean = this->mean_gauss; if (this->sup_isol) model_data.SupIsol = True; if (this->rms_map != "") { model_data.UseRmsMap = True; io_read_ima_float(to_char(this->rms_map), model_data.RmsMap); } } py::array_t<float> MRDeconvolve::Deconvolve(py::array_t<float>& arr, py::array_t<float>& psf) { Ifloat Guess, Ima_ICF; Ifloat *Pt_G = NULL; Ifloat *Pt_ICF = NULL; //outputs information if (this->verbose) Info(); //read input image this->CDec.Imag = array2image_2d(arr); this->CDec.Psf = array2image_2d(psf); //read additional files if (this->first_guess != "") { io_read_ima_float(to_char(this->first_guess), Guess); if (this->first_guess != "") Pt_G = &Guess; } if (this->icf_filename != "") { io_read_ima_float(to_char(this->icf_filename), Ima_ICF); Pt_ICF = &Ima_ICF; } //deconvolution class initialization DeconvInit(); if (this->verbose) cout << " Start the deconvolution ... " << endl; //noise model class initialization FilterAnaSynt FAS; FilterAnaSynt *PtrFAS = NULL; if ((this->transform == TO_MALLAT) || (this->transform == TO_UNDECIMATED_MALLAT)) { FAS.Verbose = (Bool)this->verbose; FAS.alloc(this->sb_filter); PtrFAS = &FAS; } model_data.alloc(this->stat_noise, CDec.Imag.nl(), CDec.Imag.nc(),this->number_of_scales, this->transform, PtrFAS, NORM_L1, this->number_of_undecimated_scales); NoiseModelInit(); this->CDec.ModelData = &model_data; //deconvolution this->CDec.im_deconv(Pt_G, Pt_ICF); return image2array_2d(this->CDec.Obj); } #endif
43.358434
174
0.567002
[ "model", "transform" ]
b33e8ffe04d5a3dbcf369d019aedad0ea9fa2aed
3,362
hpp
C++
sdm/defaults.hpp
dougalsutherland/sdm
2f6a57c5b337649a64f899dd5acba6e4eb35dff9
[ "BSD-3-Clause" ]
5
2015-04-03T11:49:19.000Z
2017-12-22T12:08:02.000Z
sdm/defaults.hpp
dougalsutherland/sdm
2f6a57c5b337649a64f899dd5acba6e4eb35dff9
[ "BSD-3-Clause" ]
1
2020-07-05T00:02:54.000Z
2020-07-05T00:02:54.000Z
sdm/defaults.hpp
dougalsutherland/sdm
2f6a57c5b337649a64f899dd5acba6e4eb35dff9
[ "BSD-3-Clause" ]
4
2016-05-20T10:40:40.000Z
2018-05-21T15:50:32.000Z
/******************************************************************************* * Copyright (c) 2012, Dougal J. Sutherland (dsutherl@cs.cmu.edu). * * 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 Carnegie Mellon University nor the * * names of the contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #ifndef SDM_DEFAULTS_HPP_ #define SDM_DEFAULTS_HPP_ #include "sdm/basics.hpp" #include <svm.h> namespace sdm { namespace detail { const double cvals[10] = { // 2^-9, 2^-6, ..., 2^18 1./512., 1./64., 1./8., 1, 1<<3, 1<<6, 1<<9, 1<<12, 1<<15, 1<<18 }; } const std::vector<double> default_c_vals(detail::cvals, detail::cvals + 10); const svm_parameter default_svm_params = { C_SVC, // svm_type PRECOMPUTED, // kernel_type 0, // degree - not used 0, // gamma - not used 0, // coef0 - not used 1024, // cache_size, in MB 1e-3, // eps - stopping condition tolerance 1, // C - tuned in CV for both classification and regression 0, // nr_weight NULL, // weight_label NULL, // weight 0, // nu - not used 0.1, // p - epsilon for regression, not currently tuned 1, // use shrinking heuristics 0 // do probability estimates }; } #endif
50.179104
80
0.532719
[ "vector" ]
b351543791ed1af3bf32bb74586437ad242e88d5
1,522
cpp
C++
src/chrono_vehicle/wheeled_vehicle/tire/ChForceElementTire.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/chrono_vehicle/wheeled_vehicle/tire/ChForceElementTire.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/chrono_vehicle/wheeled_vehicle/tire/ChForceElementTire.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2022 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Base class for a force element tire model // // ============================================================================= #include "chrono_vehicle/wheeled_vehicle/tire/ChForceElementTire.h" namespace chrono { namespace vehicle { ChForceElementTire::ChForceElementTire(const std::string& name) : ChTire(name) {} void ChForceElementTire::InitializeInertiaProperties() { m_mass = GetTireMass(); m_inertia.setZero(); m_inertia.diagonal() = GetTireInertia().eigen(); m_com = ChFrame<>(); } void ChForceElementTire::UpdateInertiaProperties() { auto spindle = m_wheel->GetSpindle(); m_xform = ChFrame<>(spindle->TransformPointLocalToParent(ChVector<>(0, GetOffset(), 0)), spindle->GetRot()); } double ChForceElementTire::GetAddedMass() const { return GetTireMass(); } ChVector<> ChForceElementTire::GetAddedInertia() const { return GetTireInertia(); } } // namespace vehicle } // namespace chrono
31.708333
112
0.572273
[ "model" ]
b35d0c185b7ac9ffc3bac93db36437b4262b2880
15,902
cpp
C++
src/core/cpu/gte.cpp
KieronJ/btpsx
d2b968750bcbe1a2fe700783186c5eacd54fd93a
[ "MIT" ]
2
2022-03-14T11:04:40.000Z
2022-03-19T23:02:32.000Z
src/core/cpu/gte.cpp
KieronJ/btpsx
d2b968750bcbe1a2fe700783186c5eacd54fd93a
[ "MIT" ]
null
null
null
src/core/cpu/gte.cpp
KieronJ/btpsx
d2b968750bcbe1a2fe700783186c5eacd54fd93a
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstddef> #include <common/bitrange.hpp> #include <common/signextend.hpp> #include <common/types.hpp> #include <spdlog/spdlog.h> #include "../error.hpp" #include "gte.hpp" namespace Cpu { void Gte::Execute(u32 i) { Command command; command.raw = i; m_lm = command.lm ? 0 : -0x8000; m_tv = command.tv; m_mv = command.mv; m_mx = command.mx; m_sf = command.sf ? 12 : 0; m_flags.raw = 0; switch (command.op) { case 0x06: Nclip(); break; case 0x10: Dpc<false>(); break; case 0x12: Mvmva(); break; case 0x13: Ncd<0>(); break; case 0x2d: Avsz3(); break; case 0x30: Rtp<0, false>(); Rtp<1, false>(); Rtp<2, true>(); break; default: spdlog::warn("unknown gte command 0x{:x}", command.op); } m_flags.checksum = (m_flags.raw & 0x7f87e000) != 0; } u32 Gte::DecompressColour() const { s32 irx = m_ir.x; s32 iry = m_ir.y; s32 irz = m_ir.z; irx = std::clamp(irx, 0, 0xf80) >> 7; iry = std::clamp(iry, 0, 0xf80) >> 2; irz = std::clamp(irz, 0, 0xf80) << 3; return irx | iry | irz; } u32 Gte::ReadData(std::size_t index) const { switch (index) { case 0: return static_cast<u16>(m_v[0].x) | m_v[0].y << 16; case 1: return static_cast<u16>(m_v[0].z); case 2: return static_cast<u16>(m_v[1].x) | m_v[1].y << 16; case 3: return static_cast<u16>(m_v[1].z); case 4: return static_cast<u16>(m_v[2].x) | m_v[2].y << 16; case 5: return static_cast<u16>(m_v[2].z); case 6: return m_colour.raw; case 7: return m_otz; case 8: return m_ir0; case 9: return m_ir.x; case 10: return m_ir.y; case 11: return m_ir.z; case 12: return static_cast<u16>(m_sx[0]) | m_sy[0] << 16; case 13: return static_cast<u16>(m_sx[1]) | m_sy[1] << 16; case 14: case 15: return static_cast<u16>(m_sx[2]) | m_sy[2] << 16; case 16: return m_sz[0]; case 17: return m_sz[1]; case 18: return m_sz[2]; case 19: return m_sz[3]; case 20: return m_rgb[0].raw; case 21: return m_rgb[1].raw; case 22: return m_rgb[2].raw; case 23: return m_res; case 24: return m_mac0; case 25: return m_mac.x; case 26: return m_mac.y; case 27: return m_mac.z; case 28: case 29: return DecompressColour(); case 30: return m_lzcs; case 31: return m_lzcr; default: Error("read from unknown gte reg {}", index); } } static inline std::size_t CountLeadingOnes(s32 value) { std::size_t count = 0; while (value < 0) { ++count; value <<= 1; } return count; } void Gte::WriteData(std::size_t index, u32 value) { switch (index) { case 0: m_v[0].x = value; m_v[0].y = value >> 16; break; case 1: m_v[0].z = value; break; case 2: m_v[1].x = value; m_v[1].y = value >> 16; break; case 3: m_v[1].z = value; break; case 4: m_v[2].x = value; m_v[2].y = value >> 16; break; case 5: m_v[2].z = value; break; case 6: m_colour.raw = value; break; case 7: m_otz = value; break; case 8: m_ir0 = value; break; case 9: m_ir.x = value; break; case 10: m_ir.y = value; break; case 11: m_ir.z = value; break; case 12: m_sx[0] = value; m_sy[0] = value >> 16; break; case 13: m_sx[1] = value; m_sy[1] = value >> 16; break; case 14: m_sx[2] = value; m_sy[2] = value >> 16; break; case 15: m_sx[0] = m_sx[1]; m_sx[1] = m_sx[2]; m_sx[2] = value; m_sy[0] = m_sy[1]; m_sy[1] = m_sy[2]; m_sy[2] = value >> 16; break; case 16: m_sz[0] = value; break; case 17: m_sz[1] = value; break; case 18: m_sz[2] = value; break; case 19: m_sz[3] = value; break; case 20: m_rgb[0].raw = value; break; case 21: m_rgb[1].raw = value; break; case 22: m_rgb[2].raw = value; break; case 23: m_res = value; break; case 24: m_mac0 = value; break; case 25: m_mac.x = value; break; case 26: m_mac.y = value; break; case 27: m_mac.z = value; break; case 28: m_ir.x = (value & 0x1f) << 7; m_ir.y = (value & 0x3e0) << 2; m_ir.z = (value & 0x7c00) >> 3; break; case 29: break; case 30: m_lzcs = value; if (value == 0) { m_lzcr = 32; break; } m_lzcr = (value > 0) ? __builtin_clz(value) : CountLeadingOnes(value); break; case 31: break; default: Error("write to unknown gte reg {}", index); } } u32 Gte::ReadControl(std::size_t index) const { switch (index) { case 0: return static_cast<u16>(m_rt.m[0][0]) | m_rt.m[0][1] << 16; case 1: return static_cast<u16>(m_rt.m[0][2]) | m_rt.m[1][0] << 16; case 2: return static_cast<u16>(m_rt.m[1][1]) | m_rt.m[1][2] << 16; case 3: return static_cast<u16>(m_rt.m[2][0]) | m_rt.m[2][1] << 16; case 4: return static_cast<u16>(m_rt.m[2][2]); case 5: return m_tr.x; case 6: return m_tr.y; case 7: return m_tr.z; case 8: return static_cast<u16>(m_llm.m[0][0]) | m_llm.m[0][1] << 16; case 9: return static_cast<u16>(m_llm.m[0][2]) | m_llm.m[1][0] << 16; case 10: return static_cast<u16>(m_llm.m[1][1]) | m_llm.m[1][2] << 16; case 11: return static_cast<u16>(m_llm.m[2][0]) | m_llm.m[2][1] << 16; case 12: return static_cast<u16>(m_llm.m[2][2]); case 13: return m_bk.r; case 14: return m_bk.g; case 15: return m_bk.b; case 16: return static_cast<u16>(m_lcm.m[0][0]) | m_lcm.m[0][1] << 16; case 17: return static_cast<u16>(m_lcm.m[0][2]) | m_lcm.m[1][0] << 16; case 18: return static_cast<u16>(m_lcm.m[1][1]) | m_lcm.m[1][2] << 16; case 19: return static_cast<u16>(m_lcm.m[2][0]) | m_lcm.m[2][1] << 16; case 20: return static_cast<u16>(m_lcm.m[2][2]); case 21: return m_fc.r; case 22: return m_fc.g; case 23: return m_fc.b; case 24: return m_ofx; case 25: return m_ofy; case 26: return static_cast<s16>(m_h); case 27: return m_dqa; case 28: return m_dqb; case 29: return m_zsf3; case 30: return m_zsf4; case 31: return m_flags.raw; default: Error("read from unknown gte reg {}", 32 + index); } } void Gte::WriteControl(std::size_t index, u32 value) { switch (index) { case 0: m_rt.m[0][0] = value; m_rt.m[0][1] = value >> 16; break; case 1: m_rt.m[0][2] = value; m_rt.m[1][0] = value >> 16; break; case 2: m_rt.m[1][1] = value; m_rt.m[1][2] = value >> 16; break; case 3: m_rt.m[2][0] = value; m_rt.m[2][1] = value >> 16; break; case 4: m_rt.m[2][2] = value; break; case 5: m_tr.x = value; break; case 6: m_tr.y = value; break; case 7: m_tr.z = value; break; case 8: m_llm.m[0][0] = value; m_llm.m[0][1] = value >> 16; break; case 9: m_llm.m[0][2] = value; m_llm.m[1][0] = value >> 16; break; case 10: m_llm.m[1][1] = value; m_llm.m[1][2] = value >> 16; break; case 11: m_llm.m[2][0] = value; m_llm.m[2][1] = value >> 16; break; case 12: m_llm.m[2][2] = value; break; case 13: m_bk.r = value; break; case 14: m_bk.g = value; break; case 15: m_bk.b = value; break; case 16: m_lcm.m[0][0] = value; m_lcm.m[0][1] = value >> 16; break; case 17: m_lcm.m[0][2] = value; m_lcm.m[1][0] = value >> 16; break; case 18: m_lcm.m[1][1] = value; m_lcm.m[1][2] = value >> 16; break; case 19: m_lcm.m[2][0] = value; m_lcm.m[2][1] = value >> 16; break; case 20: m_lcm.m[2][2] = value; break; case 21: m_fc.r = value; break; case 22: m_fc.g = value; break; case 23: m_fc.b = value; break; case 24: m_ofx = value; break; case 25: m_ofy = value; break; case 26: m_h = value; break; case 27: m_dqa = value; break; case 28: m_dqb = value; break; case 29: m_zsf3 = value; break; case 30: m_zsf4 = value; break; case 31: m_flags.raw = value & 0x7ffff000; if ((m_flags.raw & 0x7f87e000) != 0) { m_flags.checksum = true; } break; default: Error("write to unknown gte reg {}", 32 + index); } } void Gte::Nclip() { const s64 x0 = m_sx[0]; const s64 x1 = m_sx[1]; const s64 x2 = m_sx[2]; const s64 y0 = m_sy[0]; const s64 y1 = m_sy[1]; const s64 y2 = m_sy[2]; SetMac<0>(x0 * y1 + x1 * y2 + x2 * y0 - x0 * y2 - x1 * y0 - x2 * y1); } template <bool T> void Gte::Dpc() { const s64 vx = m_v[0].x; const s64 vy = m_v[0].y; const s64 vz = m_v[0].z; const s64 ir1 = m_ir.x; const s64 ir2 = m_ir.y; const s64 ir3 = m_ir.z; const s64 llm11 = m_llm.m[0][0]; const s64 llm12 = m_llm.m[0][1]; const s64 llm13 = m_llm.m[0][2]; const s64 llm21 = m_llm.m[1][0]; const s64 llm22 = m_llm.m[1][1]; const s64 llm23 = m_llm.m[1][2]; const s64 llm31 = m_llm.m[2][0]; const s64 llm32 = m_llm.m[2][1]; const s64 llm33 = m_llm.m[2][2]; const s64 lcm11 = m_lcm.m[0][0]; const s64 lcm12 = m_lcm.m[0][1]; const s64 lcm13 = m_lcm.m[0][2]; const s64 lcm21 = m_lcm.m[1][0]; const s64 lcm22 = m_lcm.m[1][1]; const s64 lcm23 = m_lcm.m[1][2]; const s64 lcm31 = m_lcm.m[2][0]; const s64 lcm32 = m_lcm.m[2][1]; const s64 lcm33 = m_lcm.m[2][2]; SetIr<1>(SetMac<1>(vx * llm11 + vy * llm12 + vz * llm13)); SetIr<2>(SetMac<2>(vx * llm21 + vy * llm22 + vz * llm23)); SetIr<3>(SetMac<3>(vx * llm31 + vy * llm32 + vz * llm33)); SetIr<1>(SetMac<1>(vx * lcm11 + vy * lcm12 + vz * lcm13)); SetIr<2>(SetMac<2>(vx * lcm21 + vy * lcm22 + vz * lcm23)); SetIr<3>(SetMac<3>(vx * lcm31 + vy * lcm32 + vz * lcm33)); PushRgb(m_colour.r, m_colour.g, m_colour.b, m_colour.c); } void Gte::Mvmva() { s64 tx; s64 ty; s64 tz; s64 vx; s64 vy; s64 vz; s64 m11; s64 m12; s64 m13; s64 m21; s64 m22; s64 m23; s64 m31; s64 m32; s64 m33; switch (m_tv) { case TranslationSel::TR: tx = m_tr.x; ty = m_tr.y; tz = m_tr.z; break; case TranslationSel::BK: tx = m_bk.r; ty = m_bk.g; tz = m_bk.b; break; case TranslationSel::None: tx = 0; ty = 0; tz = 0; break; default: Error("invalid translation vector specifier"); } switch (m_mv) { case VectorSel::V0: vx = m_v[0].x; vy = m_v[0].y; vz = m_v[0].z; break; case VectorSel::V1: vx = m_v[1].x; vy = m_v[1].y; vz = m_v[1].z; break; case VectorSel::V2: vx = m_v[2].x; vy = m_v[2].y; vz = m_v[2].z; break; case VectorSel::IR: vx = m_ir.x; vy = m_ir.y; vz = m_ir.z; break; default: Error("invalid multiplication vector specifier"); } switch (m_mx) { case MatrixSel::RT: m11 = m_rt.m[0][0]; m12 = m_rt.m[0][1]; m13 = m_rt.m[0][2]; m21 = m_rt.m[1][0]; m22 = m_rt.m[1][1]; m23 = m_rt.m[1][2]; m31 = m_rt.m[2][0]; m32 = m_rt.m[2][1]; m33 = m_rt.m[2][2]; break; case MatrixSel::LLM: m11 = m_llm.m[0][0]; m12 = m_llm.m[0][1]; m13 = m_llm.m[0][2]; m21 = m_llm.m[1][0]; m22 = m_llm.m[1][1]; m23 = m_llm.m[1][2]; m31 = m_llm.m[2][0]; m32 = m_llm.m[2][1]; m33 = m_llm.m[2][2]; break; case MatrixSel::LCM: m11 = m_lcm.m[0][0]; m12 = m_lcm.m[0][1]; m13 = m_lcm.m[0][2]; m21 = m_lcm.m[1][0]; m22 = m_lcm.m[1][1]; m23 = m_lcm.m[1][2]; m31 = m_lcm.m[2][0]; m32 = m_lcm.m[2][1]; m33 = m_lcm.m[2][2]; break; default: Error("invalid multiplication matrix specifier"); } SetIr<1>(SetMac<1>((tx << 12) + vx * m11 + vy * m12 + vz * m13)); SetIr<2>(SetMac<2>((ty << 12) + vx * m21 + vy * m22 + vz * m23)); SetIr<3>(SetMac<3>((tz << 12) + vx * m31 + vy * m32 + vz * m33)); } template <std::size_t V> void Gte::Ncd() { /* TODO */ m_rgb[0].raw = m_rgb[1].raw; m_rgb[1].raw = m_rgb[2].raw; m_rgb[2].raw = m_colour.raw; } void Gte::Avsz3() { const s64 zsf3 = m_zsf3; const s64 sz1 = m_sz[1]; const s64 sz2 = m_sz[2]; const s64 sz3 = m_sz[3]; SetMac<0>((zsf3 * (sz1 + sz2 + sz3)) >> 12); m_flags.d = m_mac0 > 0xffff || m_mac0 < 0; m_otz = std::clamp(m_mac0, 0, 0xffff); } template <std::size_t V, bool Depth> void Gte::Rtp() { const s64 tx = m_tr.x; const s64 ty = m_tr.y; const s64 tz = m_tr.z; const s64 vx = m_v[V].x; const s64 vy = m_v[V].y; const s64 vz = m_v[V].z; const s64 rt11 = m_rt.m[0][0]; const s64 rt12 = m_rt.m[0][1]; const s64 rt13 = m_rt.m[0][2]; const s64 rt21 = m_rt.m[1][0]; const s64 rt22 = m_rt.m[1][1]; const s64 rt23 = m_rt.m[1][2]; const s64 rt31 = m_rt.m[2][0]; const s64 rt32 = m_rt.m[2][1]; const s64 rt33 = m_rt.m[2][2]; SetIr<1>(SetMac<1>((tx << 12) + vx * rt11 + vy * rt12 + vz * rt13)); SetIr<2>(SetMac<2>((ty << 12) + vx * rt21 + vy * rt22 + vz * rt23)); SetIr<3>(SetMac<3>((tz << 12) + vx * rt31 + vy * rt32 + vz * rt33)); PushSz(m_mac.z); const s64 division = RtpUnrDivide(m_h, m_sz[3]); PushSx(SetMac<0>(division * m_ir.x + m_ofx) >> 16); PushSy(SetMac<0>(division * m_ir.y + m_ofy) >> 16); if constexpr (Depth) { SetIr<0>(SetMac<0>(division * m_dqa + m_dqb) >> 12); } } u32 Gte::RtpUnrDivide(u32 h, u32 sz3) { if (2 * sz3 <= h) { m_flags.e = true; return 0x1ffff; } const std::size_t z = __builtin_clz(sz3 & 0xffff) - 16; h <<= z; sz3 <<= z; const u16 u = RtpUnrTable[(sz3 - 0x7fc0) >> 7] + 0x101; sz3 = (0x2000080 - sz3 * u) >> 8; sz3 = (0x80 + sz3 * u) >> 8; return std::min(0x1ffffu, (0x8000 + h * sz3) >> 16); } template <std::size_t Mac> s32 Gte::SetMac(s64 value) { if constexpr (Mac == 0) { m_flags.fp = value > 0x7fffffff; m_flags.fn = value < -0x80000000; m_mac0 = value; return m_mac0; } if constexpr (Mac == 1) { m_flags.ap1 = value > 0x7ffffffffff; m_flags.an1 = value < -0x80000000000; m_mac.x = value >> m_sf; return m_mac.x; } if constexpr (Mac == 2) { m_flags.ap2 = value > 0x7ffffffffff; m_flags.an2 = value < -0x80000000000; m_mac.y = value >> m_sf; return m_mac.y; } if constexpr (Mac == 3) { m_flags.ap3 = value > 0x7ffffffffff; m_flags.an3 = value < -0x80000000000; m_mac.z = value >> m_sf; return m_mac.z; } Error("invalid mac specified"); } template <std::size_t Ir> void Gte::SetIr(s32 value) { if constexpr (Ir == 0) { m_flags.h = value > 0xfff || value < 0; m_ir0 = std::clamp(value, 0, 0xfff); return; } if constexpr (Ir == 1) { m_flags.b1 = value > 0x7fff || value < m_lm; m_ir.x = std::clamp(value, m_lm, 0x7fff); return; } if constexpr (Ir == 2) { m_flags.b2 = value > 0x7fff || value < m_lm; m_ir.y = std::clamp(value, m_lm, 0x7fff); return; } if constexpr (Ir == 3) { m_flags.b3 = value > 0x7fff || value < m_lm; m_ir.z = std::clamp(value, m_lm, 0x7fff); return; } Error("invalid ir specified"); } void Gte::PushSx(s32 value) { m_flags.g1 = value > 0x3ff || value < -0x400; m_sx[0] = m_sx[1]; m_sx[1] = m_sx[2]; m_sx[2] = std::clamp(value, -0x400, 0x3ff); } void Gte::PushSy(s32 value) { m_flags.g2 = value > 0x3ff || value < -0x400; m_sy[0] = m_sy[1]; m_sy[1] = m_sy[2]; m_sy[2] = std::clamp(value, -0x400, 0x3ff); } void Gte::PushSz(s32 value) { m_flags.d = value > 0xffff || value < 0; m_sz[0] = m_sz[1]; m_sz[1] = m_sz[2]; m_sz[2] = m_sz[3]; m_sz[3] = std::clamp(value, 0, 0xffff); } void Gte::PushRgb(u8 r, u8 g, u8 b, u8 c) { m_rgb[0] = m_rgb[1]; m_rgb[1] = m_rgb[2]; m_rgb[2].r = r; m_rgb[2].g = g; m_rgb[2].b = b; m_rgb[2].c = c; } }
27.898246
78
0.542951
[ "vector" ]
b362e56fd84ea8f6c42a01883173fbc3f6b7d97f
26,364
cpp
C++
test/test_hri.cpp
ros4hri/libhri
4e58ac56485319ad7daa46b0a8386961d2f3be90
[ "BSD-3-Clause" ]
null
null
null
test/test_hri.cpp
ros4hri/libhri
4e58ac56485319ad7daa46b0a8386961d2f3be90
[ "BSD-3-Clause" ]
null
null
null
test/test_hri.cpp
ros4hri/libhri
4e58ac56485319ad7daa46b0a8386961d2f3be90
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 PAL Robotics S.L. // // 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 PAL Robotics S.L. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <gtest/gtest.h> #include <gmock/gmock.h> #include <hri/hri.h> #include <ros/ros.h> #include <thread> #include <chrono> #include <memory> #include "hri/face.h" #include "hri/person.h" #include "hri_msgs/EngagementLevel.h" #include "hri_msgs/IdsList.h" #include "hri_msgs/SoftBiometrics.h" #include "std_msgs/Float32.h" #include "std_msgs/String.h" #include "std_msgs/Bool.h" #include "sensor_msgs/RegionOfInterest.h" #include <tf2_ros/static_transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> using namespace std; using namespace ros; using namespace hri; // waiting time for the libhri callback to process their inputs #define WAIT std::this_thread::sleep_for(std::chrono::milliseconds(30)) #define WAIT_DEBUG \ { \ WAIT; \ cout << "waiting..." << endl; \ } TEST(libhri, GetFaces) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); Publisher pub; { HRIListener hri_listener; pub = nh.advertise<hri_msgs::IdsList>("/humans/faces/tracked", 1); ASSERT_EQ(pub.getNumSubscribers(), 1U); ASSERT_EQ(hri_listener.getFaces().size(), 0); auto ids = hri_msgs::IdsList(); ROS_INFO("[A]"); ids.ids = { "A" }; pub.publish(ids); WAIT; auto faces = hri_listener.getFaces(); EXPECT_EQ(faces.size(), 1U); ASSERT_TRUE(faces.find("A") != faces.end()); EXPECT_TRUE(faces["A"].lock()->id() == "A"); ROS_INFO("[A]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getFaces().size(), 1U); ROS_INFO("[A,B]"); ids.ids = { "A", "B" }; pub.publish(ids); WAIT; faces = hri_listener.getFaces(); EXPECT_EQ(faces.size(), 2U); EXPECT_TRUE(faces.find("A") != faces.end()); EXPECT_TRUE(faces.find("B") != faces.end()); ROS_INFO("[A,B]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getFaces().size(), 2U); ROS_INFO("[B]"); ids.ids = { "B" }; pub.publish(ids); WAIT; faces = hri_listener.getFaces(); EXPECT_EQ(faces.size(), 1U); EXPECT_TRUE(faces.find("A") == faces.end()); ASSERT_TRUE(faces.find("B") != faces.end()); weak_ptr<const Face> face_b = faces["B"]; EXPECT_FALSE(face_b.expired()); // face B exists! ROS_INFO("[]"); ids.ids = {}; pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getFaces().size(), 0U); EXPECT_TRUE(face_b.expired()); // face B does not exist anymore! } EXPECT_EQ(pub.getNumSubscribers(), 0); spinner.stop(); } TEST(libhri, GetFacesRoi) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; auto pub = nh.advertise<hri_msgs::IdsList>("/humans/faces/tracked", 1); auto pub_r1 = nh.advertise<sensor_msgs::RegionOfInterest>("/humans/faces/A/roi", 1, true); // /roi topic is latched auto pub_r2 = nh.advertise<sensor_msgs::RegionOfInterest>("/humans/faces/B/roi", 1, true); // /roi topic is latched auto ids = hri_msgs::IdsList(); ids.ids = { "A" }; pub.publish(ids); WAIT; EXPECT_EQ(pub_r1.getNumSubscribers(), 1U) << "Face A should have subscribed to /humans/faces/A/roi"; ids.ids = { "B" }; pub.publish(ids); WAIT; EXPECT_EQ(pub_r1.getNumSubscribers(), 0U) << "Face A is deleted. No one should be subscribed to /humans/faces/A/roi anymore"; EXPECT_EQ(pub_r2.getNumSubscribers(), 1U) << "Face B should have subscribed to /humans/faces/B/roi"; auto faces = hri_listener.getFaces(); ASSERT_FALSE(faces["B"].expired()); // face B still exists! auto roi = sensor_msgs::RegionOfInterest(); { auto face = faces["B"].lock(); EXPECT_FALSE(face == nullptr); EXPECT_EQ(face->ns(), "/humans/faces/B"); EXPECT_EQ(face->roi().width, 0); roi.width = 10; pub_r2.publish(roi); WAIT; EXPECT_EQ(face->roi().width, 10); roi.width = 20; pub_r2.publish(roi); WAIT; EXPECT_EQ(face->roi().width, 20); } // RoI of face A published *before* face A is published in /faces/tracked, // but should still get its RoI, as /roi is latched. pub_r1.publish(roi); ids.ids = { "B", "A" }; pub.publish(ids); WAIT; faces = hri_listener.getFaces(); { auto face_a = faces["A"].lock(); ASSERT_FALSE(face_a == nullptr); auto face_b = faces["B"].lock(); ASSERT_FALSE(face_b == nullptr); EXPECT_EQ(face_a->ns(), "/humans/faces/A"); EXPECT_EQ(face_a->roi().width, 20); EXPECT_EQ(face_b->ns(), "/humans/faces/B"); EXPECT_EQ(face_b->roi().width, 20); } spinner.stop(); } TEST(libhri, GetBodies) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); Publisher pub; { HRIListener hri_listener; pub = nh.advertise<hri_msgs::IdsList>("/humans/bodies/tracked", 1); ASSERT_EQ(pub.getNumSubscribers(), 1U); auto ids = hri_msgs::IdsList(); ROS_INFO("[A]"); ids.ids = { "A" }; pub.publish(ids); WAIT; auto bodies = hri_listener.getBodies(); EXPECT_EQ(bodies.size(), 1U); ASSERT_TRUE(bodies.find("A") != bodies.end()); EXPECT_TRUE(bodies["A"].lock()->id() == "A"); ROS_INFO("[A]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getBodies().size(), 1U); ROS_INFO("[A,B]"); ids.ids = { "A", "B" }; pub.publish(ids); WAIT; bodies = hri_listener.getBodies(); EXPECT_EQ(bodies.size(), 2U); EXPECT_TRUE(bodies.find("A") != bodies.end()); EXPECT_TRUE(bodies.find("B") != bodies.end()); ROS_INFO("[A,B]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getBodies().size(), 2U); ROS_INFO("[B]"); ids.ids = { "B" }; pub.publish(ids); WAIT; bodies = hri_listener.getBodies(); EXPECT_EQ(bodies.size(), 1U); EXPECT_TRUE(bodies.find("A") == bodies.end()); ASSERT_TRUE(bodies.find("B") != bodies.end()); weak_ptr<const Body> body_b = bodies["B"]; EXPECT_FALSE(body_b.expired()); // body B exists! ROS_INFO("[]"); ids.ids = {}; pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getBodies().size(), 0U); EXPECT_TRUE(body_b.expired()); // body B does not exist anymore! } EXPECT_EQ(pub.getNumSubscribers(), 0); spinner.stop(); } TEST(libhri, GetVoices) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); Publisher pub; { HRIListener hri_listener; pub = nh.advertise<hri_msgs::IdsList>("/humans/voices/tracked", 1); ASSERT_EQ(pub.getNumSubscribers(), 1U); auto ids = hri_msgs::IdsList(); ROS_INFO("[A]"); ids.ids = { "A" }; pub.publish(ids); WAIT; auto voices = hri_listener.getVoices(); EXPECT_EQ(voices.size(), 1U); ASSERT_TRUE(voices.find("A") != voices.end()); EXPECT_TRUE(voices["A"].lock()->id() == "A"); ROS_INFO("[A]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getVoices().size(), 1U); ROS_INFO("[A,B]"); ids.ids = { "A", "B" }; pub.publish(ids); WAIT; voices = hri_listener.getVoices(); EXPECT_EQ(voices.size(), 2U); EXPECT_TRUE(voices.find("A") != voices.end()); EXPECT_TRUE(voices.find("B") != voices.end()); ROS_INFO("[A,B]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getVoices().size(), 2U); ROS_INFO("[B]"); ids.ids = { "B" }; pub.publish(ids); WAIT; voices = hri_listener.getVoices(); EXPECT_EQ(voices.size(), 1U); EXPECT_TRUE(voices.find("A") == voices.end()); ASSERT_TRUE(voices.find("B") != voices.end()); weak_ptr<const Voice> voice_b = voices["B"]; EXPECT_FALSE(voice_b.expired()); // voice B exists! ROS_INFO("[]"); ids.ids = {}; pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getVoices().size(), 0U); EXPECT_TRUE(voice_b.expired()); // voice B does not exist anymore! } EXPECT_EQ(pub.getNumSubscribers(), 0); spinner.stop(); } TEST(libhri, GetKnownPersons) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); Publisher pub; { HRIListener hri_listener; pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/known", 1); ASSERT_EQ(pub.getNumSubscribers(), 1U); auto ids = hri_msgs::IdsList(); ROS_INFO("[A]"); ids.ids = { "A" }; pub.publish(ids); WAIT; auto persons = hri_listener.getPersons(); EXPECT_EQ(persons.size(), 1U); ASSERT_TRUE(persons.find("A") != persons.end()); EXPECT_TRUE(persons["A"].lock()->id() == "A"); ROS_INFO("[A]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getPersons().size(), 1U); ROS_INFO("[A,B]"); ids.ids = { "A", "B" }; pub.publish(ids); WAIT; persons = hri_listener.getPersons(); EXPECT_EQ(persons.size(), 2U); EXPECT_TRUE(persons.find("A") != persons.end()); EXPECT_TRUE(persons.find("B") != persons.end()); ROS_INFO("[A,B]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getPersons().size(), 2U); ROS_INFO("[B]"); ids.ids = { "B" }; pub.publish(ids); WAIT; persons = hri_listener.getPersons(); EXPECT_EQ(persons.size(), 1U) << "known persons can go down in case of eg an anonymous person"; EXPECT_TRUE(persons.find("A") == persons.end()); ASSERT_TRUE(persons.find("B") != persons.end()); shared_ptr<const Person> person_b = persons["B"].lock(); EXPECT_TRUE(person_b != nullptr); // person B exists! ROS_INFO("[]"); ids.ids = {}; pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getPersons().size(), 0U); EXPECT_TRUE(person_b != nullptr); // person B still exists! } EXPECT_EQ(pub.getNumSubscribers(), 0); spinner.stop(); } TEST(libhri, GetTrackedPersons) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); Publisher pub; { HRIListener hri_listener; pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); ASSERT_EQ(pub.getNumSubscribers(), 1U); auto ids = hri_msgs::IdsList(); ROS_INFO("[A]"); ids.ids = { "A" }; pub.publish(ids); WAIT; auto known_persons = hri_listener.getPersons(); EXPECT_EQ(known_persons.size(), 0U); auto persons = hri_listener.getTrackedPersons(); EXPECT_EQ(persons.size(), 1U); ASSERT_TRUE(persons.find("A") != persons.end()); EXPECT_TRUE(persons["A"].lock()->id() == "A"); ROS_INFO("[A]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getTrackedPersons().size(), 1U); ROS_INFO("[A,B]"); ids.ids = { "A", "B" }; pub.publish(ids); WAIT; persons = hri_listener.getTrackedPersons(); EXPECT_EQ(persons.size(), 2U); EXPECT_TRUE(persons.find("A") != persons.end()); EXPECT_TRUE(persons.find("B") != persons.end()); ROS_INFO("[A,B]"); pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getTrackedPersons().size(), 2U); ROS_INFO("[B]"); ids.ids = { "B" }; pub.publish(ids); WAIT; persons = hri_listener.getTrackedPersons(); EXPECT_EQ(persons.size(), 1U); EXPECT_TRUE(persons.find("A") == persons.end()); ASSERT_TRUE(persons.find("B") != persons.end()); shared_ptr<const Person> person_b = persons["B"].lock(); EXPECT_TRUE(person_b != nullptr); // person B exists! ROS_INFO("[]"); ids.ids = {}; pub.publish(ids); WAIT; EXPECT_EQ(hri_listener.getTrackedPersons().size(), 0U); EXPECT_TRUE(person_b != nullptr); // person B still exists! } EXPECT_EQ(pub.getNumSubscribers(), 0); spinner.stop(); } TEST(libhri, PersonAttributes) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; auto person_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); auto face_pub = nh.advertise<hri_msgs::IdsList>("/humans/faces/tracked", 1); auto person_face_pub = nh.advertise<std_msgs::String>("/humans/persons/p1/face_id", 1); auto person_ids = hri_msgs::IdsList(); person_ids.ids = { "p1" }; person_pub.publish(person_ids); auto face_ids = hri_msgs::IdsList(); face_ids.ids = { "f1", "f2" }; face_pub.publish(face_ids); WAIT; auto p1 = hri_listener.getTrackedPersons()["p1"].lock(); ASSERT_FALSE(p1->anonymous()) << "by default, persons are not supposed to be anonymous"; auto face0 = p1->face(); ASSERT_EQ(face0.lock(), nullptr); ASSERT_TRUE(face0.expired()); auto face_id = std_msgs::String(); face_id.data = "f1"; person_face_pub.publish(face_id); WAIT; auto face1 = hri_listener.getTrackedPersons()["p1"].lock()->face(); ASSERT_NE(face1.lock(), nullptr); ASSERT_FALSE(face1.expired()); ASSERT_EQ(face1.lock()->id(), "f1"); spinner.stop(); } TEST(libhri, AnonymousPersonsAndAliases) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; auto person_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); auto p1_anon_pub = nh.advertise<std_msgs::Bool>("/humans/persons/p1/anonymous", 1); auto p2_anon_pub = nh.advertise<std_msgs::Bool>("/humans/persons/p2/anonymous", 1); auto face_pub = nh.advertise<hri_msgs::IdsList>("/humans/faces/tracked", 1); auto p1_face_pub = nh.advertise<std_msgs::String>("/humans/persons/p1/face_id", 1); auto p2_face_pub = nh.advertise<std_msgs::String>("/humans/persons/p2/face_id", 1); auto p2_alias_pub = nh.advertise<std_msgs::String>("/humans/persons/p2/alias", 1); auto person_ids = hri_msgs::IdsList(); person_ids.ids = { "p1", "p2" }; person_pub.publish(person_ids); auto face_ids = hri_msgs::IdsList(); face_ids.ids = { "f1", "f2" }; face_pub.publish(face_ids); WAIT; // each person is associated to a face auto face_id = std_msgs::String(); face_id.data = "f1"; p1_face_pub.publish(face_id); face_id.data = "f2"; p2_face_pub.publish(face_id); WAIT; std_msgs::Bool msg; msg.data = false; p1_anon_pub.publish(msg); msg.data = true; p2_anon_pub.publish(msg); WAIT; ASSERT_EQ(hri_listener.getTrackedPersons().size(), 2); auto p1 = hri_listener.getTrackedPersons()["p1"].lock(); { auto p2 = hri_listener.getTrackedPersons()["p2"].lock(); ASSERT_FALSE(p1->anonymous()); ASSERT_TRUE(p2->anonymous()); // being anonymous or not should have no impact on face associations ASSERT_EQ(p1->face().lock()->id(), "f1"); ASSERT_EQ(p2->face().lock()->id(), "f2"); } ///////////// ALIASES /////////////////////////// // set p2 as an alias of p1 auto alias_id = std_msgs::String(); alias_id.data = "p1"; p2_alias_pub.publish(alias_id); WAIT; ASSERT_EQ(hri_listener.getTrackedPersons().size(), 2U); { auto p2 = hri_listener.getTrackedPersons()["p2"].lock(); ASSERT_EQ(p1, p2) << "p2 should now point to the same person as p1"; ASSERT_EQ(p2->face().lock()->id(), "f1") << "p2's face now points to f1"; } // remove the alias alias_id.data = ""; p2_alias_pub.publish(alias_id); WAIT; { auto p2 = hri_listener.getTrackedPersons()["p2"].lock(); ASSERT_NE(p1, p2) << "p2 is not anymore the same person as p1"; ASSERT_EQ(p2->face().lock()->id(), "f2") << "p2's face should still points to its former f2 face"; } // republish the alias alias_id.data = "p1"; p2_alias_pub.publish(alias_id); WAIT; auto p2 = hri_listener.getTrackedPersons()["p2"].lock(); ASSERT_EQ(p1, p2) << "p2 is again the same person as p1"; // delete p1 -> p2 should be deleted as well person_ids.ids = { "p2" }; person_pub.publish(person_ids); WAIT; ASSERT_EQ(hri_listener.getTrackedPersons().size(), 0U) << "the aliased person should have been deleted with its alias"; spinner.stop(); } TEST(libhri, Callbacks) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; // create mock callbacks testing::MockFunction<void(FaceWeakConstPtr)> face_callback; hri_listener.onFace(face_callback.AsStdFunction()); testing::MockFunction<void(ID)> face_lost_callback; hri_listener.onFaceLost(face_lost_callback.AsStdFunction()); testing::MockFunction<void(BodyWeakConstPtr)> body_callback; hri_listener.onBody(body_callback.AsStdFunction()); testing::MockFunction<void(ID)> body_lost_callback; hri_listener.onBodyLost(body_lost_callback.AsStdFunction()); testing::MockFunction<void(VoiceWeakConstPtr)> voice_callback; hri_listener.onVoice(voice_callback.AsStdFunction()); testing::MockFunction<void(ID)> voice_lost_callback; hri_listener.onVoiceLost(voice_lost_callback.AsStdFunction()); testing::MockFunction<void(PersonWeakConstPtr)> person_callback; hri_listener.onPerson(person_callback.AsStdFunction()); testing::MockFunction<void(PersonWeakConstPtr)> person_tracked_callback; hri_listener.onTrackedPerson(person_tracked_callback.AsStdFunction()); testing::MockFunction<void(ID)> person_tracked_lost_callback; hri_listener.onTrackedPersonLost(person_tracked_lost_callback.AsStdFunction()); auto ids = hri_msgs::IdsList(); auto face_pub = nh.advertise<hri_msgs::IdsList>("/humans/faces/tracked", 1); auto body_pub = nh.advertise<hri_msgs::IdsList>("/humans/bodies/tracked", 1); auto voice_pub = nh.advertise<hri_msgs::IdsList>("/humans/voices/tracked", 1); auto person_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/known", 1); auto person_tracked_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); EXPECT_CALL(face_callback, Call(testing::_)).Times(1); EXPECT_CALL(face_lost_callback, Call(testing::_)).Times(0); ids.ids = { "id1" }; face_pub.publish(ids); WAIT; EXPECT_CALL(face_callback, Call(testing::_)).Times(1); EXPECT_CALL(face_lost_callback, Call(testing::_)).Times(0); ids.ids = { "id1", "id2" }; face_pub.publish(ids); WAIT; EXPECT_CALL(face_callback, Call(testing::_)).Times(2); EXPECT_CALL(face_lost_callback, Call(testing::_)).Times(2); ids.ids = { "id3", "id4" }; face_pub.publish(ids); WAIT; EXPECT_CALL(body_callback, Call(testing::_)).Times(2); EXPECT_CALL(body_lost_callback, Call(testing::_)).Times(0); ids.ids = { "id1", "id2" }; body_pub.publish(ids); WAIT; EXPECT_CALL(face_callback, Call(testing::_)).Times(2); EXPECT_CALL(face_lost_callback, Call(testing::_)).Times(1); EXPECT_CALL(body_callback, Call(testing::_)).Times(1); EXPECT_CALL(body_lost_callback, Call(testing::_)).Times(0); ids.ids = { "id1", "id2", "id3" }; face_pub.publish(ids); body_pub.publish(ids); WAIT; EXPECT_CALL(face_callback, Call(testing::_)).Times(3); EXPECT_CALL(face_lost_callback, Call(testing::_)).Times(3); EXPECT_CALL(body_callback, Call(testing::_)).Times(3); EXPECT_CALL(body_lost_callback, Call(testing::_)).Times(3); ids.ids = { "id5", "id6", "id7" }; face_pub.publish(ids); body_pub.publish(ids); WAIT; EXPECT_CALL(voice_callback, Call(testing::_)).Times(2); EXPECT_CALL(person_callback, Call(testing::_)).Times(2); EXPECT_CALL(person_tracked_callback, Call(testing::_)).Times(2); ids.ids = { "id1", "id2" }; voice_pub.publish(ids); person_pub.publish(ids); person_tracked_pub.publish(ids); WAIT; spinner.stop(); } TEST(libhri, SoftBiometrics) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; auto person_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); auto face_pub = nh.advertise<hri_msgs::IdsList>("/humans/faces/tracked", 1); auto person_face_pub = nh.advertise<std_msgs::String>("/humans/persons/p1/face_id", 1); auto softbiometrics_pub = nh.advertise<hri_msgs::SoftBiometrics>("/humans/faces/f1/softbiometrics", 1); auto person_ids = hri_msgs::IdsList(); person_ids.ids = { "p1" }; person_pub.publish(person_ids); auto face_ids = hri_msgs::IdsList(); face_ids.ids = { "f1" }; face_pub.publish(face_ids); WAIT; auto softbiometrics_msg = hri_msgs::SoftBiometrics(); softbiometrics_msg.age = 45; softbiometrics_msg.age_confidence = 0.8; softbiometrics_msg.gender = hri_msgs::SoftBiometrics::FEMALE; softbiometrics_msg.gender_confidence = 0.7; softbiometrics_pub.publish(softbiometrics_msg); auto face_id = std_msgs::String(); face_id.data = "f1"; person_face_pub.publish(face_id); WAIT; auto face = hri_listener.getTrackedPersons()["p1"].lock()->face().lock(); ASSERT_EQ(face->id(), "f1"); ASSERT_TRUE(face->age()); ASSERT_EQ(*(face->age()), 45); ASSERT_TRUE(face->gender()); ASSERT_EQ(*(face->gender()), hri::FEMALE); softbiometrics_msg.gender = hri_msgs::SoftBiometrics::OTHER; softbiometrics_pub.publish(softbiometrics_msg); WAIT; ASSERT_EQ(*(face->gender()), hri::OTHER); softbiometrics_msg.gender = hri_msgs::SoftBiometrics::UNDEFINED; softbiometrics_pub.publish(softbiometrics_msg); WAIT; ASSERT_FALSE(face->gender()); spinner.stop(); } TEST(libhri, EngagementLevel) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; auto person_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); auto engagement_pub = nh.advertise<hri_msgs::EngagementLevel>("/humans/persons/p1/engagement_status", 1); auto person_ids = hri_msgs::IdsList(); person_ids.ids = { "p1" }; person_pub.publish(person_ids); WAIT; auto msg = hri_msgs::EngagementLevel(); msg.level = hri_msgs::EngagementLevel::DISENGAGED; engagement_pub.publish(msg); WAIT; auto p = hri_listener.getTrackedPersons()["p1"].lock(); ASSERT_TRUE(p->engagement_status()); ASSERT_EQ(*(p->engagement_status()), hri::DISENGAGED); msg.level = hri_msgs::EngagementLevel::ENGAGED; engagement_pub.publish(msg); WAIT; ASSERT_EQ(*(p->engagement_status()), hri::ENGAGED); msg.level = hri_msgs::EngagementLevel::UNKNOWN; engagement_pub.publish(msg); WAIT; ASSERT_FALSE(p->engagement_status()); spinner.stop(); } TEST(libhri, PeopleLocation) { NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); HRIListener hri_listener; hri_listener.setReferenceFrame("base_link"); tf2_ros::StaticTransformBroadcaster static_broadcaster; geometry_msgs::TransformStamped world_transform; world_transform.header.stamp = ros::Time::now(); world_transform.header.frame_id = "world"; world_transform.child_frame_id = "base_link"; world_transform.transform.translation.x = -1.0; world_transform.transform.translation.y = 0.0; world_transform.transform.translation.z = 0.0; world_transform.transform.rotation.w = 1.0; static_broadcaster.sendTransform(world_transform); geometry_msgs::TransformStamped p1_transform; p1_transform.header.stamp = ros::Time::now(); p1_transform.header.frame_id = "world"; p1_transform.child_frame_id = "person_p1"; p1_transform.transform.translation.x = 1.0; p1_transform.transform.translation.y = 0.0; p1_transform.transform.translation.z = 0.0; p1_transform.transform.rotation.w = 1.0; auto person_pub = nh.advertise<hri_msgs::IdsList>("/humans/persons/tracked", 1); auto loc_confidence_pub = nh.advertise<std_msgs::Float32>("/humans/persons/p1/location_confidence", 1); auto person_ids = hri_msgs::IdsList(); person_ids.ids = { "p1" }; person_pub.publish(person_ids); WAIT; auto p = hri_listener.getTrackedPersons()["p1"].lock(); auto msg = std_msgs::Float32(); msg.data = 0.; loc_confidence_pub.publish(msg); WAIT; ASSERT_EQ(p->location_confidence(), 0.); ASSERT_FALSE(p->transform()) << "location confidence at 0, no transform should be available"; msg.data = 0.5; loc_confidence_pub.publish(msg); WAIT; ASSERT_EQ(p->location_confidence(), 0.5); p->transform(); ASSERT_FALSE(p->transform()) << "location confidence > 0 but no transform published yet -> no transform should be returned"; static_broadcaster.sendTransform(p1_transform); WAIT; ASSERT_EQ(p->location_confidence(), 0.5); ASSERT_TRUE(p->transform()) << "location confidence > 0 => a transform should be available"; auto t = *(p->transform()); ASSERT_EQ(t.child_frame_id, "person_p1"); ASSERT_EQ(t.header.frame_id, "base_link"); ASSERT_EQ(t.transform.translation.x, 2.0); msg.data = 1.0; loc_confidence_pub.publish(msg); WAIT; ASSERT_EQ(p->location_confidence(), 1.); ASSERT_TRUE(p->transform()) << "location confidence > 0 => a transform should be available"; spinner.stop(); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::Time::init(); // needed for ros::Time::now() ros::init(argc, argv, "test_hri"); ros::NodeHandle nh; ROS_INFO("Starting HRI tests"); return RUN_ALL_TESTS(); }
26.738337
126
0.66276
[ "transform" ]
b367e740c81d388a3c044d223332ac6d2ab3bfce
2,218
hxx
C++
include/GenericTSPSolver.hxx
Redchards/CVRP
f372f2fa06cb374ebdac2f6eee7e6fe297d94103
[ "MIT" ]
2
2019-09-01T14:40:11.000Z
2020-08-15T05:01:23.000Z
include/GenericTSPSolver.hxx
Redchards/CVRP
f372f2fa06cb374ebdac2f6eee7e6fe297d94103
[ "MIT" ]
null
null
null
include/GenericTSPSolver.hxx
Redchards/CVRP
f372f2fa06cb374ebdac2f6eee7e6fe297d94103
[ "MIT" ]
2
2019-08-02T17:50:23.000Z
2019-12-26T08:25:35.000Z
#ifndef GENERIC_TSP_SOLVER_HXX #define GENERIC_TSP_SOLVER_HXX #include <vector> #include <CVRPInstance.hxx> #include <Meta.hxx> #include <lemon/christofides_tsp.h> #include <lemon/greedy_tsp.h> #include <lemon/insertion_tsp.h> #include <lemon/nearest_neighbor_tsp.h> #include <lemon/opt2_tsp.h> namespace Solver { using TSPResult = std::vector<Data::CVRPInstance::GraphType::Node>; template<class Derived> class GenericTSPSolver { protected: using CVRPInstance = Data::CVRPInstance; using CostMap = CVRPInstance::CostMap; private: template<class T, class = void> struct is_solve_implemented_in : std::false_type {}; template<class T> struct is_solve_implemented_in<T, Meta::void_t<decltype(std::declval<std::decay_t<T>>().solve(std::declval<CVRPInstance::GraphType>(), std::declval<CostMap>()))>> : std::true_type {}; public: GenericTSPSolver() { static_assert(is_solve_implemented_in<Derived>::value, "Invalid derived class : must implement the method 'solve'"); } TSPResult solve(const CVRPInstance::GraphType&, const CostMap&); }; template<class Solver> class LemonTSPSolverAdaptor : GenericTSPSolver<LemonTSPSolverAdaptor<Solver>> { private: using CVRPInstance = Data::CVRPInstance; using CostMap = CVRPInstance::CostMap; public: using GenericTSPSolver<LemonTSPSolverAdaptor>::GenericTSPSolver; TSPResult solve(const CVRPInstance::GraphType& graph, const CostMap& costMap) { Solver solver(graph, costMap); solver.run(); // std::cout << solver.tourCost() << std::endl; return solver.tourNodes(); } }; using ChristofidesTSPSolver = LemonTSPSolverAdaptor<lemon::ChristofidesTsp<Data::CVRPInstance::CostMap>>; using GreedyTSPSolver = LemonTSPSolverAdaptor<lemon::GreedyTsp<Data::CVRPInstance::CostMap>>; using InsertionTSPSolver = LemonTSPSolverAdaptor<lemon::InsertionTsp<Data::CVRPInstance::CostMap>>; using NearestNeighbourTSPSolver = LemonTSPSolverAdaptor<lemon::NearestNeighborTsp<Data::CVRPInstance::CostMap>>; using TwoOptTSPSolver = LemonTSPSolverAdaptor<lemon::Opt2Tsp<Data::CVRPInstance::CostMap>>; } #endif // GENERIC_TSP_SOLVER_HXX
31.239437
187
0.733544
[ "vector" ]
b3689bda948be9f227d99b406e863263cfb563d3
4,645
cpp
C++
MathTL/tests/test_infinite_vector.cpp
kedingagnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
3
2018-05-20T15:25:58.000Z
2021-01-19T18:46:48.000Z
MathTL/tests/test_infinite_vector.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
null
null
null
MathTL/tests/test_infinite_vector.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
2
2019-04-24T18:23:26.000Z
2020-09-17T10:00:27.000Z
#include <cstdlib> #include <cmath> #include <set> #include <iostream> #include <algebra/infinite_vector.h> using std::cout; using std::endl; using namespace MathTL; class Squares : public InfiniteDiagonalMatrix<float> { public: double diag(const int& i) const { return i*i; } }; class SquaresPlusOne : public InfiniteDiagonalMatrix<float> { public: double diag(const int& i) const { return i*i+1.; } }; int main() { cout << "Testing the InfiniteVector class ..." << endl; InfiniteVector<float,long int> s; cout << "- a zero vector:" << endl << s << endl; cout << "- writing access on s:" << endl; s[1] = 2; cout << " (size after writing the first element: " << s.size() << ")" << endl; s[3] = 42; cout << " (size after writing the second element: " << s.size() << ")" << endl; cout << s; cout << "- copy constructor t(s):" << endl; InfiniteVector<float,long int> t(s); cout << t; cout << "- are the two vectors equal?" << endl; if (t == s) cout << " ... yes!" << endl; else cout << " ... no!" << endl; cout << "- are the two vectors inequal?" << endl; if (t != s) cout << " ... yes!" << endl; else cout << " ... no!" << endl; cout << "- in place summation s+=t:" << endl; s += t; cout << s; cout << "- in place subtraction t-=s:" << endl; t -= s; cout << t; cout << "- in place multiplication s*=2:" << endl; s *= 2; cout << s; cout << "- in place division s/=3:" << endl; s /= 3; cout << s; cout << "- ell_p norms of s:" << endl; cout << " ||x||_2 = " << l2_norm(s) << ", ||x||_1 = " << l1_norm(s) << ", ||x||_infinity = " << linfty_norm(s) << endl; cout << "- external arithmetic functionality:" << endl; InfiniteVector<float,long int> sa, sb; sa[1] = 23; sa[2] = sa[3] = 10; sb[1] = -1.5; sb[3] = 3; sb[4] = 8; cout << " a=" << endl << sa << " b=" << endl << sb; swap(sa,sb); cout << " after swapping, a=" << endl << sa << " b=" << endl << sb; cout << " a+b=" << endl << sa+sb << " a-b=" << endl << sa-sb; cout << " a*b=" << sa*sb << endl; cout << " mean value of a: " << mean_value(sa) << endl; cout << "- preparing a large random vector for the NCOARSE routine with size "; InfiniteVector<float> v, w; for (unsigned int i=0; i < 1000; i++) { v[i] = (float)rand()/(double)RAND_MAX; } cout << v.size() << " and ||v||_2=" << l2_norm(v) << endl; double eps = 0.1; cout << "- COARSE(" << eps << ",w) yields w with "; v.COARSE(eps,w); cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl; eps = 1.0; cout << "- COARSE(" << eps << ",w) yields w with "; v.COARSE(eps,w); cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl; eps = 10.0; cout << "- COARSE(" << eps << ",w) yields w with "; v.COARSE(eps,w); cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl; cout << "- some weak \\ell_\\tau norms of v:" << endl; for (double tau(1.8); tau >= 0.2; tau -= 0.2) { cout << " tau=" << tau << ", ||v||_{\\ell^w_\\tau}=" << v.weak_norm(tau) << endl; } v.clear(); v[0] = 1e-10; v[1] = 0.5; v[2] = -1e-5; cout << "- another vector v:" << endl << v; v.compress(1e-2); cout << "- compressing with eta=1e-2:" << endl << v; v.clear(); v[0] = 123; v[2] = 345; v[4] = -678; cout << "- another vector v:" << endl << v; std::set<int> supp; v.support(supp); cout << "- v has the support" << endl; for (std::set<int>::const_iterator it = supp.begin(); it != supp.end(); ++it) cout << *it << endl; std::set<int> Lambda; Lambda.insert(2); Lambda.insert(0); Lambda.insert(-1); v.clip(Lambda); cout << "- v clipped to an index set:" << endl << v; v.add_coefficient(0, 1.5); cout << "- added something to the first coefficient of v:" << endl << v; v.add_coefficient(2, -345); cout << "- added something to the second coefficient of v:" << endl << v; v.clear(); v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; w.clear(); w[0] = 1; w[1] = -1; w[2] = -1; w[3] = 1; const double atol = 1; const double rtol = 1; cout << "- vectors v=" << endl << v << " and w=" << endl << w; cout << " weighted root mean square norm of v (" << "atol=" << atol << ", rtol=" << rtol << "): " << v.wrmsqr_norm(atol, rtol, w, w) << endl; Squares S; w.scale(&S); cout << "w weighted with an instance of Squares: " << endl << w; SquaresPlusOne S1; w.scale(&S1, -1); cout << "w weighted with an instance of SquaresPlusOne, exponent -1: " << endl << w; return 0; }
25.662983
88
0.514316
[ "vector" ]
b377ee0c3b965f2e0d6c195e969742573d6dd227
4,207
cc
C++
local-update-pv.cc
lemrobotry/thesis
14ad489e8f04cb957707b89c454ee7d81ec672ad
[ "MIT" ]
null
null
null
local-update-pv.cc
lemrobotry/thesis
14ad489e8f04cb957707b89c454ee7d81ec672ad
[ "MIT" ]
null
null
null
local-update-pv.cc
lemrobotry/thesis
14ad489e8f04cb957707b89c454ee7d81ec672ad
[ "MIT" ]
null
null
null
#include "Application.hh" #include "BleuScore.hh" #include "ChartFactory.hh" #include "InputData.hh" #include "LOPChart.hh" #include "PV.hh" #include "PrintTimer.hh" APPLICATION using namespace Permute; class SmoothedBleu : public std::unary_function <const ConstPathRef &, double> { private: const BleuScoreAgainst & bleu_; Permutation & pi_; public: SmoothedBleu (const BleuScoreAgainst & bleu, Permutation & pi) : bleu_ (bleu), pi_ (pi) {} double operator () (const ConstPathRef & path) { pi_.reorder (path); return bleu_.compute (pi_).smoothed (); } }; /**********************************************************************/ class LocalUpdate : public Application { private: static Core::ParameterFloat paramLearningRate; double LEARNING_RATE; static Core::ParameterInt paramK; int K; PrintTimer timer_; public: LocalUpdate () : Application ("local-update-pv"), timer_ (std::cerr) {} virtual void printParameterDescription (std::ostream & out) const { paramLearningRate.printShortHelp (out); paramK.printShortHelp (out); } virtual void getParameters () { Application::getParameters (); LEARNING_RATE = paramLearningRate (config); K = paramK (config); } int main (const std::vector <std::string> & args) { this -> getParameters (); timer_.start ("Reading PV: ", LOP_FILE); PV pv; if (! this -> readPV (pv)) { return EXIT_FAILURE; } timer_.stop ("Reading PV: ", LOP_FILE); std::vector <WRef> weights (pv.size ()); std::transform (pv.begin (), pv.end (), weights.begin (), std::select2nd <PV::value_type> ()); std::vector <double> weightSum (pv.size (), 0.0), values (pv.size ()); double N = 0.0; int iteration = 0; InputData data (DEPENDENCY); ParseControllerRef controller = this -> parseController (data.source ()); do { std::istream & input = this -> input (); timer_.start ("Processing Data"); for (int sentence = 0; sentence < SENTENCES && input >> data; ++ sentence) { // timer_.start ("Sentence ", sentence); SumBeforeCostRef bc (new SumBeforeCost (data.source ().size (), "LocalUpdate")); ScorerRef scorer = this -> sumBeforeScorer (bc, pv, data); LOPkBestChart kbc (data.source ()); // timer_.start ("Best Paths: ", K); kbc.permute (controller, scorer); std::vector <ConstPathRef> paths; kbc.getBestPaths (paths, K); // timer_.stop ("Best Paths: ", K); // timer_.start ("BLEU Score: ", paths.size ()); BleuScoreAgainst bleu (data.target ()); SmoothedBleu smoothedBleu (bleu, data.source ()); std::vector <double> smoothed (paths.size ()); std::transform (paths.begin (), paths.end (), smoothed.begin (), smoothedBleu); // timer_.stop ("BLEU Score: ", paths.size ()); // timer_.start ("Max"); std::vector <double>::const_iterator it = std::max_element (smoothed.begin (), smoothed.end ()); // timer_.stop ("Max"); // timer_.start ("Update"); if (it != smoothed.begin ()) { data.source ().reorder (paths [it - smoothed.begin ()]); this -> perceptronUpdate (bc, data.source (), LEARNING_RATE); data.source ().reorder (paths [0]); this -> perceptronUpdate (bc, data.source (), - LEARNING_RATE); } // timer_.stop ("Update"); update (weightSum, weights); ++ N; // timer_.stop ("Sentence ", sentence); } timer_.stop ("Processing Data"); // Store current weights in values. std::copy (weights.begin (), weights.end (), values.begin ()); std::transform (weightSum.begin (), weightSum.end (), weights.begin (), std::bind2nd (std::divides <double> (), N)); timer_.start ("Decode Dev"); this -> decodeDev (pv); timer_.stop ("Decode Dev"); timer_.start ("Write PV"); this -> writePV (pv, ++ iteration); timer_.stop ("Write PV"); std::copy (values.begin (), values.end (), weights.begin ()); } while (! this -> converged ()); return EXIT_SUCCESS; } } app; Core::ParameterFloat LocalUpdate::paramLearningRate ("rate", "the learning rate for the perceptron", 1.0, 0.0); Core::ParameterInt LocalUpdate::paramK ("k", "the size of the k-best list", 1, 1);
27.860927
111
0.623247
[ "vector", "transform" ]
b3784b120ff0b988823cc40f06caab48d760f79f
13,122
cc
C++
src/tests/palm_system_blink_test.cc
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
12
2018-03-22T18:51:21.000Z
2020-07-18T03:57:53.000Z
src/tests/palm_system_blink_test.cc
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
24
2018-10-30T10:33:03.000Z
2020-06-02T19:59:29.000Z
src/tests/palm_system_blink_test.cc
webosose/wam
5d3eb5d50a176fb82c1fa5564655277181c9235a
[ "Apache-2.0" ]
17
2018-03-22T18:51:24.000Z
2021-11-19T13:03:43.000Z
// (c) 2021 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <json/json.h> #include "platform_module_factory_impl.h" #include "utils.h" #include "web_app_factory_manager_mock.h" #include "web_app_manager.h" #include "web_app_manager_service_luna.h" #include "web_app_wayland.h" #include "web_app_window_factory_mock.h" #include "web_app_window_mock.h" #include "web_page_blink_delegate.h" #include "web_view_factory_mock.h" #include "web_view_mock.h" #include "webos/window_group_configuration.h" namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Eq; using ::testing::Invoke; using ::testing::Return; using ::testing::ReturnRef; using ::testing::StrEq; // TODO: Move it to separate file. static constexpr char kLaunchBareAppJsonBody[] = R"({ "launchingAppId": "com.webos.app.home", "appDesc": { "defaultWindowType": "card", "uiRevision": "2", "systemApp": true, "version": "1.0.1", "vendor": "LG Electronics, Inc.", "miniicon": "icon.png", "hasPromotion": false, "tileSize": "normal", "icons": [], "launchPointId": "bareapp_default", "largeIcon": "/usr/palm/applications/bareapp/icon.png", "lockable": true, "transparent": false, "icon": "/usr/palm/applications/bareapp/icon.png", "checkUpdateOnLaunch": true, "imageForRecents": "", "spinnerOnLaunch": true, "handlesRelaunch": false, "unmovable": false, "id": "bareapp", "inspectable": false, "noSplashOnLaunch": false, "privilegedJail": false, "trustLevel": "default", "title": "Bare App", "deeplinkingParams": "", "lptype": "default", "inAppSetting": false, "favicon": "", "visible": true, "accessibility": { "supportsAudioGuidance": false }, "folderPath": "/usr/palm/applications/bareapp", "main": "index.html", "removable": true, "type": "web", "disableBackHistoryAPI": false, "bgImage": "", "windowGroup":{ "name":"Window group name", "owner":false, "ownerInfo":{ "allowAnonymous":false, "layers":[ {"name":"Owner layer name", "z":111} ] }, "clientInfo":{ "layer":"Client layer name", "hint":"Client layer hint" } } }, "appId": "bareapp", "parameters": { "displayAffinity": 0 }, "reason": "com.webos.app.home", "launchingProcId": "", "instanceId": "188f99b7-1e1a-489f-8e3d-56844a7713030" })"; static constexpr char kLocaleInfo[] = R"({ "subscribed": false, "returnValue": true, "method": "getSystemSettings", "settings": { "localeInfo": { "keyboards": [ "en" ], "locales": { "UI": "en-US", "FMT": "en-US", "NLP": "en-US", "AUD": "en-US", "AUD2": "en-US", "STT": "en-US" }, "clock": "locale", "timezone": "" } } })"; } // namespace class PalmSystemBlinkTestSuite : public ::testing::Test { public: PalmSystemBlinkTestSuite() = default; ~PalmSystemBlinkTestSuite() override = default; void SetUp() override; void TearDown() override; WebAppWindowFactoryMock* web_app_window_factory_ = nullptr; WebAppWindowMock* web_app_window_ = nullptr; WebViewFactoryMock* web_view_factory_ = nullptr; WebViewMock* web_view_ = nullptr; WebPageBlinkDelegate* web_view_delegate_ = nullptr; WebAppWayland* web_app_ = nullptr; std::string view_url_; }; void PalmSystemBlinkTestSuite::SetUp() { WebAppManager::Instance()->SetPlatformModules( std::make_unique<PlatformModuleFactoryImpl>()); web_view_factory_ = new WebViewFactoryMock(); web_app_window_factory_ = new WebAppWindowFactoryMock(); web_view_ = new NiceWebViewMock(); web_app_window_ = new NiceWebAppWindowMock(); auto web_app_factory_manager = std::make_unique<WebAppFactoryManagerMock>(); web_app_factory_manager->SetWebViewFactory(web_view_factory_); web_app_factory_manager->SetWebAppWindowFactory(web_app_window_factory_); web_view_factory_->SetWebView(web_view_); web_app_window_factory_->SetWebAppWindow(web_app_window_); WebAppManager::Instance()->SetWebAppFactory( std::move(web_app_factory_manager)); ON_CALL(*web_app_window_, SetWebApp(_)) .WillByDefault(Invoke([&](WebAppWayland* app) { web_app_ = app; })); ON_CALL(*web_view_, GetUrl()).WillByDefault(ReturnRef(view_url_)); ON_CALL(*web_view_, SetDelegate(_)) .WillByDefault(Invoke([&](WebPageBlinkDelegate* delegate) { web_view_delegate_ = delegate; })); ON_CALL(*web_view_, LoadUrl(_)) .WillByDefault(Invoke([&](const std::string& url) { view_url_ = url; if (!web_view_delegate_) { return; } web_view_delegate_->LoadStarted(); web_view_delegate_->LoadProgressChanged(100.0); web_view_delegate_->LoadVisuallyCommitted(); web_view_delegate_->LoadFinished(url); })); Json::Value reuest; ASSERT_TRUE(util::StringToJson(kLocaleInfo, reuest)); WebAppManagerServiceLuna::Instance()->GetSystemLocalePreferencesCallback( reuest); reuest.clear(); ASSERT_TRUE(util::StringToJson(kLaunchBareAppJsonBody, reuest)); const auto& result = WebAppManagerServiceLuna::Instance()->launchApp(reuest); ASSERT_TRUE(result.isObject()); ASSERT_TRUE(result.isMember("instanceId")); ASSERT_TRUE(web_view_delegate_); ASSERT_TRUE(web_app_); } void PalmSystemBlinkTestSuite::TearDown() { WebAppManager::Instance()->CloseAllApps(); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_initialize) { std::string return_value; web_view_delegate_->HandleBrowserControlFunction( "initialize", std::vector<std::string>(), &return_value); Json::Value init_value; ASSERT_TRUE(util::StringToJson(return_value, init_value)); ASSERT_TRUE(init_value.isObject()); ASSERT_TRUE(init_value.isMember("folderPath")); EXPECT_STREQ(init_value["folderPath"].asString().c_str(), "/usr/palm/applications/bareapp"); ASSERT_TRUE(init_value.isMember("identifier")); EXPECT_STREQ(init_value["identifier"].asString().c_str(), "bareapp"); ASSERT_TRUE(init_value.isMember("trustLevel")); EXPECT_STREQ(init_value["trustLevel"].asString().c_str(), "default"); ASSERT_TRUE(init_value.isMember("launchParams")); EXPECT_TRUE(init_value["launchParams"].asString().find("displayAffinity") != std::string::npos); ASSERT_TRUE(init_value.isMember("locale")); EXPECT_TRUE(init_value["locale"].asString().find("en-US") != std::string::npos); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_isKeyboardVisible) { EXPECT_CALL(*web_app_window_, IsKeyboardVisible()).WillOnce(Return(false)); std::string return_value; web_view_delegate_->HandleBrowserControlFunction( "isKeyboardVisible", std::vector<std::string>(), &return_value); EXPECT_STREQ(return_value.c_str(), "false"); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_getIdentifier) { std::string return_value; web_view_delegate_->HandleBrowserControlFunction( "getIdentifier", std::vector<std::string>(), &return_value); EXPECT_STREQ(return_value.c_str(), "bareapp"); web_view_delegate_->HandleBrowserControlFunction( "identifier", std::vector<std::string>(), &return_value); EXPECT_STREQ(return_value.c_str(), "bareapp"); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_isActivated) { std::string return_value; web_app_->Unfocus(); web_view_delegate_->HandleBrowserControlFunction( "isActivated", std::vector<std::string>(), &return_value); EXPECT_STREQ(return_value.c_str(), "false"); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setWindowProperty) { std::string return_value; std::vector<std::string> params; params.reserve(2); params.emplace_back("TestProperty"); params.emplace_back("TestValue"); EXPECT_CALL(*web_app_window_, SetWindowProperty(StrEq("TestProperty"), StrEq("TestValue"))); web_view_delegate_->HandleBrowserControlFunction("setWindowProperty", params, &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setCursor) { std::string return_value; std::vector<std::string> params; params.reserve(3); params.emplace_back("Cursor"); params.emplace_back(std::to_string(1)); params.emplace_back(std::to_string(2)); EXPECT_CALL(*web_app_window_, SetCursor(std::string("Cursor"), 1, 2)); web_view_delegate_->HandleBrowserControlFunction("setCursor", params, &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_platformBack) { std::string return_value; EXPECT_CALL(*web_app_window_, PlatformBack()); web_view_delegate_->HandleBrowserControlFunction( "platformBack", std::vector<std::string>(), &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setKeyMask_Home) { std::string return_value; std::vector<std::string> params; params.reserve(1); params.emplace_back(R"(["KeyMaskHome"])"); EXPECT_CALL(*web_app_window_, SetKeyMask(webos::WebOSKeyMask::KEY_MASK_HOME)); web_view_delegate_->HandleBrowserControlFunction("setKeyMask", params, &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setKeyMask_Back) { std::string return_value; std::vector<std::string> params; params.reserve(1); params.emplace_back(R"(["KeyMaskBack"])"); EXPECT_CALL(*web_app_window_, SetKeyMask(webos::WebOSKeyMask::KEY_MASK_BACK)); web_view_delegate_->HandleBrowserControlFunction("setKeyMask", params, &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setKeyMask_Exit) { std::string return_value; std::vector<std::string> params; params.reserve(1); params.emplace_back(R"(["KeyMaskExit"])"); EXPECT_CALL(*web_app_window_, SetKeyMask(webos::WebOSKeyMask::KEY_MASK_EXIT)); web_view_delegate_->HandleBrowserControlFunction("setKeyMask", params, &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setKeyMask_Incorrect) { std::string return_value; std::vector<std::string> params; params.reserve(1); params.emplace_back(R"(["Incorrect value"])"); EXPECT_CALL(*web_app_window_, SetKeyMask(static_cast<webos::WebOSKeyMask>(0))); web_view_delegate_->HandleBrowserControlFunction("setKeyMask", params, &return_value); } TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_setKeyMask_Combination) { std::string return_value; std::vector<std::string> params; params.reserve(1); params.emplace_back(R"(["KeyMaskExit", "KeyMaskBack"])"); int keymask = 0; keymask |= webos::WebOSKeyMask::KEY_MASK_EXIT; keymask |= webos::WebOSKeyMask::KEY_MASK_BACK; EXPECT_CALL(*web_app_window_, SetKeyMask(static_cast<webos::WebOSKeyMask>(keymask))); web_view_delegate_->HandleBrowserControlFunction("setKeyMask", params, &return_value); } // NOTE: just ensure that we will not crash on this call TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_PmLogInfoWithClock) { std::string return_value; std::vector<std::string> params; params.reserve(3); params.emplace_back(""); params.emplace_back(""); params.emplace_back(""); web_view_delegate_->HandleBrowserControlFunction("PmLogInfoWithClock", params, &return_value); } // NOTE: just ensure that we will not crash on this call TEST_F(PalmSystemBlinkTestSuite, handleBrowserControlMessage_PmLogString) { std::string return_value; std::vector<std::string> params; params.reserve(4); params.emplace_back(std::to_string(7)); params.emplace_back(""); params.emplace_back(""); params.emplace_back(""); web_view_delegate_->HandleBrowserControlFunction("PmLogString", params, &return_value); }
33.052897
80
0.681756
[ "vector" ]
b37f0ec66ff19e7470a86f285eca5a1371a066a3
905
cpp
C++
C++Tut/HelloWorld_1.cpp
dedhun/Ded_CP
593abfbf703199f748633600041c251c39d76cfe
[ "MIT" ]
1
2020-06-25T00:32:20.000Z
2020-06-25T00:32:20.000Z
C++Tut/HelloWorld_1.cpp
dedhun/Ded_CP
593abfbf703199f748633600041c251c39d76cfe
[ "MIT" ]
null
null
null
C++Tut/HelloWorld_1.cpp
dedhun/Ded_CP
593abfbf703199f748633600041c251c39d76cfe
[ "MIT" ]
null
null
null
// This is a preprocessor directive. // We are going to be including a file i/o stream in this program // that we are going to be using later. // Therefore, we are including a file i/o stream that we didn't make // but it is needed to run this program later. // This is called a header file. #include <iostream> //std is a standard library. // If you are not using namespace std, it means that u have to add std::cout and std::endl for every object/variable using namespace std; // this is a function. // main is where it is going to start the program // integers main always works with integers. int main() { // statements // cout is an output stream object. // << This is a stream insertion operator // (This prints it on the screen) // endl is endline. cout << "Hello, World!" << endl; // return 0 means ur program is successful. return 0; }
34.807692
117
0.671823
[ "object" ]
b3891b32496d563489351f3ef0bfdbeb82913675
3,560
hpp
C++
platforms/linux/src/Application/Packets/AbstractPacket.hpp
iotile/baBLE-linux
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
[ "MIT" ]
13
2018-07-04T16:35:37.000Z
2021-03-03T10:41:07.000Z
platforms/linux/src/Application/Packets/AbstractPacket.hpp
iotile/baBLE
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
[ "MIT" ]
11
2018-06-01T20:32:32.000Z
2019-01-21T17:03:47.000Z
platforms/linux/src/Application/Packets/AbstractPacket.hpp
iotile/baBLE-linux
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
[ "MIT" ]
null
null
null
#ifndef BABLE_ABSTRACTPACKET_HPP #define BABLE_ABSTRACTPACKET_HPP #include "PacketUuid.hpp" #include "Log/Loggable.hpp" #include "Format/HCI/HCIFormat.hpp" #include "Format/MGMT/MGMTFormat.hpp" #include "Format/Flatbuffers/FlatbuffersFormat.hpp" #include "Transport/AbstractSocket.hpp" // FIXME: Need it to avoid cyclic dependency... class PacketRouter; namespace Packet { class AbstractPacket : public Loggable, public std::enable_shared_from_this<AbstractPacket> { public: std::vector<uint8_t> to_bytes() const; virtual std::vector<uint8_t> serialize(MGMTFormatBuilder& builder) const { throw std::runtime_error("serialize(MGMTFormatBuilder&) not defined."); }; virtual std::vector<uint8_t> serialize(HCIFormatBuilder& builder) const { throw std::runtime_error("serialize(HCIFormatBuilder&) not defined."); }; virtual std::vector<uint8_t> serialize(FlatbuffersFormatBuilder& builder) const { throw std::runtime_error("serialize(FlatbuffersFormatBuilder&) not defined."); }; void from_bytes(const std::shared_ptr<AbstractExtractor>& extractor); virtual void unserialize(MGMTFormatExtractor& extractor) { throw std::runtime_error("unserialize() not defined for MGMTFormatExtractor."); }; virtual void unserialize(HCIFormatExtractor& extractor) { throw std::runtime_error("unserialize() not defined for HCIFormatExtractor."); }; virtual void unserialize(FlatbuffersFormatExtractor& extractor) { throw std::runtime_error("unserialize() not defined for FlatbuffersFormatExtractor."); }; inline const Packet::Type get_type() const { return m_current_type; }; inline const std::string get_uuid_request() const { return m_uuid_request; }; inline const uint16_t get_controller_id() const { return m_controller_id; }; inline const uint16_t get_connection_handle() const { return m_connection_handle; }; inline const bool get_routable() const { return m_routable; } void set_routable(bool routable) { m_routable = routable; } inline const BaBLE::StatusCode get_status() const { return m_status; }; virtual const PacketUuid get_uuid() const; inline const Packet::Id get_id() const { return m_id; }; void set_uuid_request(const std::string& uuid_request); void set_controller_id(uint16_t controller_id); void set_connection_handle(uint16_t connection_handle); void set_status(uint8_t native_status, bool compute_status = true, const std::string& native_class = ""); virtual void set_socket(AbstractSocket* socket) {}; void translate(); virtual void prepare(const std::shared_ptr<PacketRouter>& router) = 0; void import_status(const std::shared_ptr<AbstractPacket>& packet); const std::string stringify() const override; protected: AbstractPacket(Packet::Id id, Packet::Type initial_type, Packet::Type final_type, uint16_t packet_code); template <class T> inline std::shared_ptr<T> shared_from(T* that) { return std::static_pointer_cast<T>(shared_from_this()); } Packet::Id m_id; Packet::Type m_final_type; Packet::Type m_current_type; uint16_t m_packet_code; uint16_t m_controller_id; uint16_t m_connection_handle; std::string m_uuid_request; std::string m_native_class; BaBLE::StatusCode m_status; private: void compute_bable_status(); uint8_t m_native_status; bool m_routable; }; } #endif //BABLE_ABSTRACTPACKET_HPP
29.915966
109
0.721348
[ "vector" ]
b38a61f885708807714737a26fc79ae246e09732
12,501
cpp
C++
src/frameworks/av/media/libeffects/factory/EffectsXmlConfigLoader.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/av/media/libeffects/factory/EffectsXmlConfigLoader.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/av/media/libeffects/factory/EffectsXmlConfigLoader.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "EffectsFactoryConfigLoader" //#define LOG_NDEBUG 0 #include <dlfcn.h> #include <set> #include <stdlib.h> #include <string> #include <log/log.h> #include <media/EffectsConfig.h> #include "EffectsConfigLoader.h" #include "EffectsFactoryState.h" #include "EffectsXmlConfigLoader.h" #if defined(_MSC_VER) // M3E: #include <windows.h> // for strdup #endif namespace android { using namespace effectsConfig; ///////////////////////////////////////////////// // Local functions ///////////////////////////////////////////////// namespace { /** Similarly to dlopen, looks for the provided path in LD_EFFECT_LIBRARY_PATH. * @return true if the library is found and set resolvedPath to its absolute path. * false if not found */ bool resolveLibrary(const std::string& path, std::string* resolvedPath) { for (auto* libraryDirectory : LD_EFFECT_LIBRARY_PATH) { std::string candidatePath = std::string(libraryDirectory) + '/' + path; if (access(candidatePath.c_str(), R_OK) == 0) { *resolvedPath = std::move(candidatePath); return true; } } return false; } /** Loads a library given its relative path and stores the result in libEntry. * @return true on success with libEntry's path, handle and desc filled * false on success with libEntry's path filled with the path of the failed lib * The caller MUST free the resources path (free) and handle (dlclose) if filled. */ bool loadLibrary(const char* relativePath, lib_entry_t* libEntry) noexcept { #if TODO // M3E: std::string absolutePath; if (!resolveLibrary(relativePath, &absolutePath)) { ALOGE("Could not find library in effect directories: %s", relativePath); libEntry->path = strdup(relativePath); return false; } const char* path = absolutePath.c_str(); libEntry->path = strdup(path); // Make sure the lib is closed on early return std::unique_ptr<void, decltype(dlclose)*> libHandle(dlopen(path, RTLD_NOW), dlclose); if (libHandle == nullptr) { ALOGE("Could not dlopen library %s: %s", path, dlerror()); return false; } auto* description = static_cast<audio_effect_library_t*>( dlsym(libHandle.get(), AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR)); if (description == nullptr) { ALOGE("Invalid effect library, failed not find symbol '%s' in %s: %s", AUDIO_EFFECT_LIBRARY_INFO_SYM_AS_STR, path, dlerror()); return false; } if (description->tag != AUDIO_EFFECT_LIBRARY_TAG) { ALOGE("Bad tag %#08x in description structure, expected %#08x for library %s", description->tag, AUDIO_EFFECT_LIBRARY_TAG, path); return false; } uint32_t majorVersion = EFFECT_API_VERSION_MAJOR(description->version); uint32_t expectedMajorVersion = EFFECT_API_VERSION_MAJOR(EFFECT_LIBRARY_API_VERSION); if (majorVersion != expectedMajorVersion) { ALOGE("Unsupported major version %#08x, expected %#08x for library %s", majorVersion, expectedMajorVersion, path); return false; } libEntry->handle = libHandle.release(); libEntry->desc = description; return true; #else return false; #endif } /** Because the structures will be destroyed by c code, using new to allocate shared structure * is not possible. Provide a equivalent of unique_ptr for malloc/freed structure to make sure * they are not leaked in the c++ code. @{ */ struct FreeDeleter { void operator()(void* p) { free(p); } }; /** unique_ptr for object created with malloc. */ template <class T> using UniqueCPtr = std::unique_ptr<T, FreeDeleter>; /** c version of std::make_unique. Uses malloc and free. */ template <class T> UniqueCPtr<T> makeUniqueC() { T* ptr = new (malloc(sizeof(T))) T{}; // Use placement new to initialize the structure return UniqueCPtr<T>{ptr}; } /** @} */ /** Push an not owned element in a list_elem link list with an optional lock. */ template <class T, class ListElem> void listPush(T* object, ListElem** list, pthread_mutex_t* mutex = nullptr) noexcept { auto listElem = makeUniqueC<ListElem>(); listElem->object = object; if (mutex != nullptr) { pthread_mutex_lock(mutex); } listElem->next = *list; *list = listElem.release(); if (mutex != nullptr) { pthread_mutex_unlock(mutex); } } /** Push an owned element in a list_elem link list with an optional lock. */ template <class T, class ListElem> void listPush(UniqueCPtr<T>&& object, ListElem** list, pthread_mutex_t* mutex = nullptr) noexcept { listPush(object.release(), list, mutex); } size_t loadLibraries(const effectsConfig::Libraries& libs, list_elem_t** libList, pthread_mutex_t* libListLock, list_elem_t** libFailedList) { size_t nbSkippedElement = 0; for (auto& library : libs) { // Construct a lib entry auto libEntry = makeUniqueC<lib_entry_t>(); libEntry->name = strdup(library.name.c_str()); libEntry->effects = nullptr; pthread_mutex_init(&libEntry->lock, nullptr); if (!loadLibrary(library.path.c_str(), libEntry.get())) { // Register library load failure listPush(std::move(libEntry), libFailedList); ++nbSkippedElement; continue; } listPush(std::move(libEntry), libList, libListLock); } return nbSkippedElement; } /** Find a library with the given name in the given list. */ lib_entry_t* findLibrary(const char* name, list_elem_t* list) { while (list != nullptr) { auto* object = static_cast<lib_entry_t*>(list->object); if (strcmp(object->name, name) == 0) { return object; } list = list->next; } return nullptr; } struct UuidStr { /** Length of an uuid represented as string. @TODO: use a constant instead of 40. */ char buff[40]; }; /** @return a string representing the provided uuid. * By not providing an output buffer, it is implicitly created in the caller context. * In such case the return pointer has the same lifetime as the expression containing uuidToString() */ char* uuidToString(const effect_uuid_t& uuid, UuidStr&& str = {}) { uuidToString(&uuid, str.buff, sizeof(str.buff)); return str.buff; } struct LoadEffectResult { /** true if the effect is usable (aka, existing lib, desc, right version, unique uuid) */ bool success = false; /** Set if the effect lib was found*/ lib_entry_t* lib = nullptr; //* Set if the description was successfuly retrieved from the lib */ UniqueCPtr<effect_descriptor_t> effectDesc; }; LoadEffectResult loadEffect(const EffectImpl& effect, const std::string& name, list_elem_t* libList) { LoadEffectResult result; // Find the effect library result.lib = findLibrary(effect.library->name.c_str(), libList); if (result.lib == nullptr) { ALOGE("Could not find library %s to load effect %s", effect.library->name.c_str(), name.c_str()); return result; } result.effectDesc = makeUniqueC<effect_descriptor_t>(); // Get the effect descriptor if (result.lib->desc->get_descriptor(&effect.uuid, result.effectDesc.get()) != 0) { ALOGE("Error querying effect %s on lib %s", uuidToString(effect.uuid), result.lib->name); result.effectDesc.reset(); return result; } // Dump effect for debug #if (LOG_NDEBUG==0) char s[512]; dumpEffectDescriptor(result.effectDesc.get(), s, sizeof(s), 0 /* indent */); ALOGV("loadEffect() read descriptor %p:%s", result.effectDesc.get(), s); #endif // Check effect is supported uint32_t expectedMajorVersion = EFFECT_API_VERSION_MAJOR(EFFECT_CONTROL_API_VERSION); if (EFFECT_API_VERSION_MAJOR(result.effectDesc->apiVersion) != expectedMajorVersion) { ALOGE("Bad API version %#08x for effect %s in lib %s, expected major %#08x", result.effectDesc->apiVersion, name.c_str(), result.lib->name, expectedMajorVersion); return result; } lib_entry_t *_; if (findEffect(nullptr, &effect.uuid, &_, nullptr) == 0) { ALOGE("Effect %s uuid %s already exist", uuidToString(effect.uuid), name.c_str()); return result; } result.success = true; return result; } size_t loadEffects(const Effects& effects, list_elem_t* libList, list_elem_t** skippedEffects, list_sub_elem_t** subEffectList) { size_t nbSkippedElement = 0; for (auto& effect : effects) { auto effectLoadResult = loadEffect(effect, effect.name, libList); if (!effectLoadResult.success) { if (effectLoadResult.effectDesc != nullptr) { listPush(std::move(effectLoadResult.effectDesc), skippedEffects); } ++nbSkippedElement; continue; } if (effect.isProxy) { auto swEffectLoadResult = loadEffect(effect.libSw, effect.name + " libsw", libList); auto hwEffectLoadResult = loadEffect(effect.libHw, effect.name + " libhw", libList); if (!swEffectLoadResult.success || !hwEffectLoadResult.success) { // Push the main effect in the skipped list even if only a subeffect is invalid // as the main effect is not usable without its subeffects. listPush(std::move(effectLoadResult.effectDesc), skippedEffects); ++nbSkippedElement; continue; } listPush(effectLoadResult.effectDesc.get(), subEffectList); // Since we return a dummy descriptor for the proxy during // get_descriptor call, we replace it with the corresponding // sw effect descriptor, but keep the Proxy UUID *effectLoadResult.effectDesc = *swEffectLoadResult.effectDesc; effectLoadResult.effectDesc->uuid = effect.uuid; effectLoadResult.effectDesc->flags |= EFFECT_FLAG_OFFLOAD_SUPPORTED; auto registerSubEffect = [subEffectList](auto&& result) { auto entry = makeUniqueC<sub_effect_entry_t>(); entry->object = result.effectDesc.release(); // lib_entry_t is stored since the sub effects are not linked to the library entry->lib = result.lib; listPush(std::move(entry), &(*subEffectList)->sub_elem); }; registerSubEffect(std::move(swEffectLoadResult)); registerSubEffect(std::move(hwEffectLoadResult)); } listPush(std::move(effectLoadResult.effectDesc), &effectLoadResult.lib->effects); } return nbSkippedElement; } } // namespace ///////////////////////////////////////////////// // Interface function ///////////////////////////////////////////////// extern "C" ssize_t EffectLoadXmlEffectConfig(const char* path) { #if TODO // M3E: using effectsConfig::parse; auto result = path ? parse(path) : parse(); if (result.parsedConfig == nullptr) { ALOGE("Failed to parse XML configuration file"); return -1; } result.nbSkippedElement += loadLibraries(result.parsedConfig->libraries, &gLibraryList, &gLibLock, &gLibraryFailedList) + loadEffects(result.parsedConfig->effects, gLibraryList, &gSkippedEffects, &gSubEffectList); ALOGE_IF(result.nbSkippedElement != 0, "%zu errors during loading of configuration: %s", result.nbSkippedElement, result.configPath ?: "No config file found"); return result.nbSkippedElement; #else return -1; #endif } } // namespace android
35.922414
100
0.642109
[ "object" ]
b39062a6efec905b9e748c97788c582562449373
10,350
cpp
C++
consai_vision_tracker/src/robot_tracker.cpp
SSL-Roots/consai_ros2
7191c1805679387b4b2cf6d6fe838a064b538736
[ "Apache-2.0" ]
6
2021-11-27T09:21:34.000Z
2022-03-05T03:25:12.000Z
consai_vision_tracker/src/robot_tracker.cpp
SSL-Roots/consai_ros2
7191c1805679387b4b2cf6d6fe838a064b538736
[ "Apache-2.0" ]
null
null
null
consai_vision_tracker/src/robot_tracker.cpp
SSL-Roots/consai_ros2
7191c1805679387b4b2cf6d6fe838a064b538736
[ "Apache-2.0" ]
1
2022-03-08T04:59:46.000Z
2022-03-08T04:59:46.000Z
// Copyright 2021 Roots // // 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 <cmath> #include <iostream> #include <memory> #include <vector> #include "consai_vision_tracker/robot_tracker.hpp" #include "robocup_ssl_msgs/msg/vector2.hpp" namespace consai_vision_tracker { using ColumnVector = BFL::ColumnVector; using Matrix = BFL::Matrix; using MatrixWrapper = BFL::Matrix_Wrapper; using SymmetricMatrix = BFL::SymmetricMatrix; using Vector2 = robocup_ssl_msgs::msg::Vector2; // visibilityの操作量 // 追跡対象の情報が来ないとき、この操作量だけvisibilityを小さくする // 操作量 = 1.0 / (trackerの更新周波数 * 消失判定までに掛ける時間) // 例:trackerが100Hzで更新されるとき、操作量が0.002であれば、 // 追跡対象が消失してから5秒かけてvisibilityが1.0から0.0になる static const double VISIBILITY_CONTROL_VALUE = 0.005; RobotTracker::RobotTracker(const int team_color, const int id, const double dt) { prev_tracked_robot_.robot_id.team_color = team_color; prev_tracked_robot_.robot_id.id = id; // visibilityはoptionalなので、ここでデフォルト値を設定しておく prev_tracked_robot_.visibility.push_back(1.0); // velocityはoptionalなので、ここでデフォルト値を設定しておく prev_tracked_robot_.vel.push_back(Vector2()); prev_tracked_robot_.vel_angular.push_back(0.0); // システムモデル // pos(t+1) = pos(t) + vel(t)*dt + undefined_input(t) + noise // pos = (x, y, theta) Matrix A(6, 6); A(1, 1) = 1.0; A(1, 2) = 0.0; A(1, 3) = 0.0; A(1, 4) = dt; A(1, 5) = 0.0; A(1, 6) = 0.0; A(2, 1) = 0.0; A(2, 2) = 1.0; A(2, 3) = 0.0; A(2, 4) = 0.0; A(2, 5) = dt; A(2, 6) = 0.0; A(3, 1) = 0.0; A(3, 2) = 0.0; A(3, 3) = 1.0; A(3, 4) = 0.0; A(3, 5) = 0.0; A(3, 6) = dt; A(4, 1) = 0.0; A(4, 2) = 0.0; A(4, 3) = 0.0; A(4, 4) = 1.0; A(4, 5) = 0.0; A(4, 6) = 0.0; A(5, 1) = 0.0; A(5, 2) = 0.0; A(5, 3) = 0.0; A(5, 4) = 0.0; A(5, 5) = 1.0; A(5, 6) = 0.0; A(6, 1) = 0.0; A(6, 2) = 0.0; A(6, 3) = 0.0; A(6, 4) = 0.0; A(6, 5) = 0.0; A(6, 6) = 1.0; // 入力は未実装 Matrix B(6, 3); B(1, 1) = 0.0; B(1, 2) = 0.0; B(1, 3) = 0.0; B(2, 1) = 0.0; B(2, 2) = 0.0; B(2, 3) = 0.0; B(3, 1) = 0.0; B(3, 2) = 0.0; B(3, 3) = 0.0; B(4, 1) = 0.0; B(4, 2) = 0.0; B(4, 3) = 0.0; B(5, 1) = 0.0; B(5, 2) = 0.0; B(5, 3) = 0.0; B(6, 1) = 0.0; B(6, 2) = 0.0; B(6, 3) = 0.0; std::vector<Matrix> AB(2); AB[0] = A; AB[1] = B; // システムノイズの平均値 ColumnVector sys_noise_mu(6); sys_noise_mu = 0.0; // 位置、速度の変化をのシステムノイズで表現する(つまりめちゃくちゃノイズがでかい) // 0 m/s から、いきなり1.0 m/sに変化しうる、ということ // 例:1.0[m/s] / 0.001[s] = 100 [m/ss] const double MAX_LINEAR_ACC_MPS = 0.1 * 1.0 / dt; // 例:1.0[rad/s] / 0.001[s] = 100 [rad/ss] const double MAX_ANGULAR_ACC_RADPS = 0.05 * M_PI / dt; const double MAX_LINEAR_ACCEL_IN_DT = MAX_LINEAR_ACC_MPS * dt; // [m/s] const double MAX_ANGULAR_ACCEL_IN_DT = MAX_ANGULAR_ACC_RADPS * dt; // [rad/s] const double MAX_LINEAR_MOVEMENT_IN_DT = MAX_LINEAR_ACC_MPS / 2 * std::pow(dt, 2); // [m] const double MAX_ANGULAR_MOVEMENT_IN_DT = MAX_ANGULAR_ACC_RADPS / 2 * std::pow(dt, 2); // [rad] // システムノイズの分散 SymmetricMatrix sys_noise_cov(6); sys_noise_cov = 0.0; sys_noise_cov(1, 1) = std::pow(MAX_LINEAR_MOVEMENT_IN_DT, 2); sys_noise_cov(2, 2) = std::pow(MAX_LINEAR_MOVEMENT_IN_DT, 2); sys_noise_cov(3, 3) = std::pow(MAX_ANGULAR_MOVEMENT_IN_DT, 2); sys_noise_cov(4, 4) = std::pow(MAX_LINEAR_ACCEL_IN_DT, 2); sys_noise_cov(5, 5) = std::pow(MAX_LINEAR_ACCEL_IN_DT, 2); sys_noise_cov(6, 6) = std::pow(MAX_ANGULAR_ACCEL_IN_DT, 2); Gaussian system_uncertainty(sys_noise_mu, sys_noise_cov); sys_pdf_ = std::make_shared<ConditionalGaussian>(AB, system_uncertainty); sys_model_ = std::make_shared<SystemModelGaussianUncertainty>(sys_pdf_.get()); // 観測モデル // ~pos(t) = pos(t) + noise // pos = (x, y, theta) Matrix H(3, 6); H = 0.0; H(1, 1) = 1.0; H(2, 2) = 1.0; H(3, 3) = 1.0; // 観測ノイズの平均値 ColumnVector meas_noise_mu(3); meas_noise_mu = 0.0; // 観測ノイズの分散 SymmetricMatrix meas_noise_cov(3); meas_noise_cov(1, 1) = std::pow(0.02, 2); meas_noise_cov(2, 2) = std::pow(0.02, 2); meas_noise_cov(3, 3) = std::pow(0.02 * M_PI, 2); Gaussian measurement_uncertainty(meas_noise_mu, meas_noise_cov); meas_pdf_ = std::make_shared<ConditionalGaussian>(H, measurement_uncertainty); meas_model_ = std::make_shared<MeasurementModelGaussianUncertainty>(meas_pdf_.get()); // 事前分布 ColumnVector prior_mu(6); prior_mu = 0.0; SymmetricMatrix prior_cov(6); prior_cov = 0.0; prior_cov(1, 1) = 100.0; prior_cov(2, 2) = 100.0; prior_cov(3, 3) = 100.0; prior_cov(4, 4) = 100.0; prior_cov(5, 5) = 100.0; prior_cov(6, 6) = 100.0; prior_ = std::make_shared<Gaussian>(prior_mu, prior_cov); // カルマンフィルタの生成 filter_ = std::make_shared<ExtendedKalmanFilter>(prior_.get()); } void RobotTracker::push_back_observation(const DetectionRobot & robot) { // 角度データを含まない場合は、そのデータを参照しない if (robot.orientation.size() == 0) { return; } TrackedRobot observation; observation.pos.x = robot.x * 0.001; // mm to meters observation.pos.y = robot.y * 0.001; // mm to meters observation.orientation = robot.orientation[0]; robot_observations_.push_back(observation); } TrackedRobot RobotTracker::update() { // 観測値から外れ値を取り除く for (auto it = robot_observations_.begin(); it != robot_observations_.end(); ) { if (is_outlier(*it)) { it = robot_observations_.erase(it); } else { ++it; } } auto size = robot_observations_.size(); if (size == 0) { // 観測値が無い場合の処理 // visibilityを下げる prev_tracked_robot_.visibility[0] -= VISIBILITY_CONTROL_VALUE; if (prev_tracked_robot_.visibility[0] <= 0) { // visibilityが0になったらカルマンフィルタの演算を実行しない prev_tracked_robot_.visibility[0] = 0.0; reset_prior(); return prev_tracked_robot_; } } else { // 観測値があればvisibilityをn倍のレートで上げる prev_tracked_robot_.visibility[0] += VISIBILITY_CONTROL_VALUE * 5.0; if (prev_tracked_robot_.visibility[0] > 1.0) { prev_tracked_robot_.visibility[0] = 1.0; } // 観測値が複数ある場合は、その平均値をもとめる // この処理で観測値を全て削除する ColumnVector mean_observation(3); mean_observation(1) = 0.0; mean_observation(2) = 0.0; double sum_x = 0.0; double sum_y = 0.0; for (auto it = robot_observations_.begin(); it != robot_observations_.end(); ) { mean_observation(1) += it->pos.x; mean_observation(2) += it->pos.y; // 角度は-pi ~ piの範囲なので、2次元ベクトルに変換してから平均値を求める sum_x += std::cos(it->orientation); sum_y += std::sin(it->orientation); it = robot_observations_.erase(it); } mean_observation(1) /= size; mean_observation(2) /= size; sum_x /= size; sum_y /= size; mean_observation(3) = std::fmod(std::atan2(sum_y, sum_x), M_PI); // 観測値と前回の予測値がpi, -pi付近にあるとき、 // 2つの角度の差分が大きくならないように、観測値の符号と値を調節する mean_observation(3) = normalize_orientation( filter_->PostGet()->ExpectedValueGet()(3), mean_observation(3)); filter_->Update(meas_model_.get(), mean_observation); correct_orientation_overflow_of_prior(); } // 事後分布から予測値を取得 auto expected_value = filter_->PostGet()->ExpectedValueGet(); prev_tracked_robot_.pos.x = expected_value(1); prev_tracked_robot_.pos.y = expected_value(2); prev_tracked_robot_.orientation = expected_value(3); prev_tracked_robot_.vel[0].x = expected_value(4); prev_tracked_robot_.vel[0].y = expected_value(5); prev_tracked_robot_.vel_angular[0] = expected_value(6); // 次の状態を予測する // 例えば、ロボットの加速度が入力値になる // 入力値は未実装なので0とする ColumnVector input(3); input(1) = 0; input(2) = 0; input(3) = 0; filter_->Update(sys_model_.get(), input); correct_orientation_overflow_of_prior(); return prev_tracked_robot_; } void RobotTracker::reset_prior() { // 事前分布を初期化する ColumnVector prior_mu(6); prior_mu = 0.0; SymmetricMatrix prior_cov(6); prior_cov = 0.0; prior_cov(1, 1) = 100.0; prior_cov(2, 2) = 100.0; prior_cov(3, 3) = 100.0; prior_cov(4, 4) = 100.0; prior_cov(5, 5) = 100.0; prior_cov(6, 6) = 100.0; prior_->ExpectedValueSet(prior_mu); prior_->CovarianceSet(prior_cov); filter_->Reset(prior_.get()); } bool RobotTracker::is_outlier(const TrackedRobot & observation) const { // 観測が外れ値かどうか判定する // Reference: https://myenigma.hatenablog.com/entry/20140825/1408975706 const double THRESHOLD = 5.99; // 自由度2、棄却率5%のしきい値 auto expected_value = filter_->PostGet()->ExpectedValueGet(); auto covariance = filter_->PostGet()->CovarianceGet(); // マハラノビス距離を求める double diff_x = observation.pos.x - expected_value(1); double diff_y = observation.pos.y - expected_value(2); double covariance_x = covariance(1, 1); double covariance_y = covariance(2, 2); // 0 除算を避ける if (std::fabs(covariance_x) < 1E-15 || std::fabs(covariance_y) < 1E-15) { return false; } double mahalanobis = std::sqrt( std::pow(diff_x, 2) / covariance_x + std::pow( diff_y, 2) / covariance_y); if (mahalanobis > THRESHOLD) { return true; } return false; } void RobotTracker::correct_orientation_overflow_of_prior() { // 事後分布の角度を取得し、-pi ~ piの範囲に収め、事前分布にセットする auto expected_value = filter_->PostGet()->ExpectedValueGet(); auto covariance = filter_->PostGet()->CovarianceGet(); if (expected_value(3) < -M_PI || expected_value(3) > M_PI) { expected_value(3) = normalize_orientation(expected_value(3)); prior_->ExpectedValueSet(expected_value); prior_->CovarianceSet(covariance); filter_->Reset(prior_.get()); } } double RobotTracker::normalize_orientation(double orientation) const { // 角度を-pi ~ piの範囲に収める while (orientation >= M_PI) {orientation -= 2.0 * M_PI;} while (orientation <= -M_PI) {orientation += 2.0 * M_PI;} return orientation; } double RobotTracker::normalize_orientation(const double from, const double to) const { // fromからtoへ連続に角度が変化するようにtoの符号と大きさを変更する // from(150 deg) -> to(-150 deg) => from(150 deg) -> to(210 deg) return from + normalize_orientation(to - from); } } // namespace consai_vision_tracker
31.944444
98
0.667923
[ "vector" ]
b3963ab0eb968e7f821a3946e21c028b3dc015ed
4,234
cpp
C++
src/IntrospectionView/ProgramManagerWindow.cpp
kyle-piddington/ShaderTool
c753a53bde6eab942da617adab9483c945f27f51
[ "MIT" ]
2
2016-03-11T00:07:33.000Z
2016-04-14T22:35:44.000Z
src/IntrospectionView/ProgramManagerWindow.cpp
kyle-piddington/ShaderTool
c753a53bde6eab942da617adab9483c945f27f51
[ "MIT" ]
null
null
null
src/IntrospectionView/ProgramManagerWindow.cpp
kyle-piddington/ShaderTool
c753a53bde6eab942da617adab9483c945f27f51
[ "MIT" ]
1
2021-02-18T14:42:03.000Z
2021-02-18T14:42:03.000Z
#include "ProgramManagerWindow.h" #include "imgui.h" #include "ProgramManagerElementFactory.h" ProgramManagerWindow::ProgramManagerWindow(): manager(nullptr), modelMgr(nullptr) { } ProgramManagerWindow::~ProgramManagerWindow() { } void ProgramManagerWindow::setProgramManager(ToolSceneProgramManager * mgr) { this->manager = mgr; refresh(); } void ProgramManagerWindow::setModelManager(ModelManager * mgr) { this->modelMgr = mgr; } void ProgramManagerWindow::refresh() { /** * First, clear out the old windows */ elements.clear(); modelElement = nullptr; /** * Get all the uniforms in the program. */ if(this->manager != nullptr) { /** Get model manager*/ std::shared_ptr<UniformObjectController> modelCtrl = manager->getModelUniformController(); if(modelCtrl != nullptr) { modelElement = std::make_shared<TransformMatrixElement>( std::static_pointer_cast<TransformController>(modelCtrl)); } auto uniforms = manager->getExposedUniformControllers(); for(auto uniformObject : uniforms) { std::shared_ptr<ProgramManagerElement> element = ProgramManagerElementFactory::Create(uniformObject); if(element != nullptr) { elements.push_back(element); } } } /** * Sort the element list */ std::sort(elements.begin(),elements.end(), [](std::shared_ptr<ProgramManagerElement> a, std::shared_ptr<ProgramManagerElement> b) { return a->getName() < b->getName(); }); } void ProgramManagerWindow::render() { if(manager != nullptr) { ImGui::Begin("Program Management"); renderProgramManager(); if(ImGui::Button("Recompile")) { if(manager->reload()) { refresh(); }; } if(ImGui::CollapsingHeader("Model Management")) { renderModelManager(); if(modelElement != nullptr) { modelElement->render(); } } if(ImGui::CollapsingHeader("Uniforms",NULL,true,true)) { for(auto element : elements) { element->render(); } } ImGui::End(); } } void ProgramManagerWindow::renderModelManager() { //Get the current list of avaliable models: if(modelMgr != nullptr) { std::vector<std::string> models = modelMgr->getModelNames(); std::string cModel = modelMgr->getActiveModelName(); int selected = std::find(models.begin(),models.end(), cModel) - models.begin(); /** * Build char ** ptr */ const char * mNames[models.size()]; for(int i = 0; i < models.size(); i++) { mNames[i] = models[i].c_str(); } if(ImGui::Combo("Model",&selected, mNames, models.size())) { modelMgr->load(models[selected]); } } } void ProgramManagerWindow::renderProgramManager() { //Get the current list of avaliable shaders: if(manager != nullptr) { std::vector<std::string> vertShaders = manager->getVertexShaderNames(); std::string cVertShader = manager->getVertexName(); int vSelected = std::find(vertShaders.begin(),vertShaders.end(), cVertShader) - vertShaders.begin(); /** * Build char ** ptr */ const char * vNames[vertShaders.size()]; for(int i = 0; i < vertShaders.size(); i++) { vNames[i] = vertShaders[i].c_str(); } if(ImGui::Combo("Vertex Shader",&vSelected, vNames, vertShaders.size())) { manager->setVertexShader(vertShaders[vSelected]); } //Do same thing for frag shader. // std::vector<std::string> fragShaders = manager->getFragmentShaderNames(); std::string cFragShader = manager->getFragmentName(); int fSelected = std::find(fragShaders.begin(),fragShaders.end(), cFragShader) - fragShaders.begin(); /** * Build char ** ptr */ const char * fNames[fragShaders.size()]; for(int i = 0; i < fragShaders.size(); i++) { fNames[i] = fragShaders[i].c_str(); } if(ImGui::Combo("Fragment Shader",&fSelected, fNames, fragShaders.size())) { manager->setFragmentShader(fragShaders[fSelected]); } } }
24.473988
110
0.6077
[ "render", "vector", "model" ]
b399640506229c43cbe97b7313d7c41c3248f6bd
3,132
cpp
C++
deps/CustomOps/SparseFactorizationSolve/Factorization/SparseFactorization.cpp
ziyiyin97/ADCME.jl
1c9b2c1ae63059d79a5a6a7b86eee64796868755
[ "MIT" ]
202
2019-06-12T18:42:20.000Z
2022-03-24T16:56:46.000Z
deps/CustomOps/SparseFactorizationSolve/Factorization/SparseFactorization.cpp
banren456/ADCME.jl
2ed7a0801b6ed90f2236c3cde7a1dca825cbe897
[ "MIT" ]
46
2019-08-19T19:37:52.000Z
2022-03-27T11:17:50.000Z
deps/CustomOps/SparseFactorizationSolve/Factorization/SparseFactorization.cpp
banren456/ADCME.jl
2ed7a0801b6ed90f2236c3cde7a1dca825cbe897
[ "MIT" ]
56
2019-07-30T05:50:55.000Z
2022-03-28T02:41:07.000Z
#include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/platform/default/logging.h" #include "tensorflow/core/framework/shape_inference.h" #include<cmath> #ifdef USE_GPU #include "tensorflow/core/util/gpu_kernel_helper.h" namespace tensorflow{ typedef Eigen::GpuDevice GPUDevice; void forwardGPU(const GPUDevice &d); void backwardGPU(const GPUDevice &d); } #endif using namespace tensorflow; #include "SparseFactorization.h" REGISTER_OP("SparseFactorization") .Input("ii : int64") .Input("jj : int64") .Input("vv : double") .Input("d : int64") .Input("s : int64") .Output("o : int64") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { shape_inference::ShapeHandle ii_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &ii_shape)); shape_inference::ShapeHandle jj_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &jj_shape)); shape_inference::ShapeHandle vv_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 1, &vv_shape)); shape_inference::ShapeHandle d_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &d_shape)); shape_inference::ShapeHandle s_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 0, &s_shape)); c->set_output(0, c->Scalar()); return Status::OK(); }); class SparseFactorizationOp : public OpKernel { private: public: explicit SparseFactorizationOp(OpKernelConstruction* context) : OpKernel(context) { } void Compute(OpKernelContext* context) override { DCHECK_EQ(5, context->num_inputs()); const Tensor& ii = context->input(0); const Tensor& jj = context->input(1); const Tensor& vv = context->input(2); const Tensor& d = context->input(3); const Tensor& s = context->input(4); const TensorShape& ii_shape = ii.shape(); const TensorShape& jj_shape = jj.shape(); const TensorShape& vv_shape = vv.shape(); const TensorShape& d_shape = d.shape(); const TensorShape& s_shape = s.shape(); DCHECK_EQ(ii_shape.dims(), 1); DCHECK_EQ(jj_shape.dims(), 1); DCHECK_EQ(vv_shape.dims(), 1); DCHECK_EQ(d_shape.dims(), 0); DCHECK_EQ(s_shape.dims(), 0); // extra check // create output shape int N = vv_shape.dim_size(0); TensorShape o_shape({}); // create output tensor Tensor* o = NULL; OP_REQUIRES_OK(context, context->allocate_output(0, o_shape, &o)); // get the corresponding Eigen tensors for data access auto ii_tensor = ii.flat<int64>().data(); auto jj_tensor = jj.flat<int64>().data(); auto vv_tensor = vv.flat<double>().data(); auto d_tensor = d.flat<int64>().data(); auto s_tensor = s.flat<int64>().data(); auto o_tensor = o->flat<int64>().data(); // implement your forward function here // TODO: forward(o_tensor, ii_tensor, jj_tensor, vv_tensor, N, *d_tensor, *s_tensor); } }; REGISTER_KERNEL_BUILDER(Name("SparseFactorization").Device(DEVICE_CPU), SparseFactorizationOp);
29
95
0.664751
[ "shape" ]
b39a57bbf12194f04356dba13d6c23d96b40d94b
2,646
cpp
C++
week5/code/set_binary_search_vector.cpp
hj02/Vor2015
675641f12773229e242c6e0bde290bdd537bf830
[ "MIT" ]
null
null
null
week5/code/set_binary_search_vector.cpp
hj02/Vor2015
675641f12773229e242c6e0bde290bdd537bf830
[ "MIT" ]
null
null
null
week5/code/set_binary_search_vector.cpp
hj02/Vor2015
675641f12773229e242c6e0bde290bdd537bf830
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cstdlib> using namespace std; class IntSet { public: // Contstructs a new set IntSet(); // Returns the number of (distinct) elements in the set. int size(); bool empty(); // Returns true if and only if the set contains 'item'. bool contains(int item); // Inserts 'item' into the set. // If 'item' is already a member of the set, this operation has no // effect. void insert(int item); // Removes 'item' from the set. // If 'item' is not a member of the set, this operation has no effect. void remove(int item); private: vector<int> vec; int insertion_index(int item); bool item_present(int index, int item); }; IntSet::IntSet() { } int IntSet::size() { return vec.size(); } bool IntSet::empty() { return size() == 0; } // Returns true if and only if 'item' is present at 'index' in vector. bool IntSet::item_present(int index, int item) { return index != size() && vec[index] == item; } // Returns the index before which 'item' should be inserted, in order to // maintain the strict increasing order of vec. // If 'item' is in vec, then the index of 'item' is returned. int IntSet::insertion_index(int item) { int l = 0; int r = vec.size() - 1; int m; while(l <= r) { m = (l + r) / 2; if(vec[m] == item) { return m; } else if (vec[m] < item) { l = m + 1; } else { r = m - 1; } } return l; } bool IntSet::contains(int item) { int ind = insertion_index(item); return item_present(ind, item); } void IntSet::insert(int item) { int ind = insertion_index(item); if(!item_present(ind, item)) { vec.insert(vec.begin() + ind, item); } } void IntSet::remove(int item) { int ind = insertion_index(item); if(item_present(ind, item)) { vec.erase(vec.begin() + ind); } } int main() { srand(1337); IntSet s; for(int i = 0; i != 20; i++) { s.insert(rand() % 30); } for(int i = 0; i != 30; i++) { cout << i << ": " << (s.contains(i) ? "Yes" : "No") << endl; if (i % 2 == 0) { s.remove(i); } } cout << endl; for(int i = 0; i != 30; i++) { cout << i << ": " << (s.contains(i) ? "Yes" : "No") << endl; } for(int i = 0; i != 100000; i++) { s.insert(rand() % 55789127); } cout << "Done inserting" << endl; for(int i = 0; i != 1000000; i++) { s.contains(i); } }
20.045455
78
0.519274
[ "vector" ]
a2b09852fab5ce38059326ff2c15de89a8a68958
6,457
hpp
C++
rj_topic_utils/include/rj_topic_utils/async_message_queue.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
200
2015-01-26T01:45:34.000Z
2022-03-19T13:05:31.000Z
rj_topic_utils/include/rj_topic_utils/async_message_queue.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
1,254
2015-01-03T01:57:35.000Z
2022-03-16T06:32:21.000Z
rj_topic_utils/include/rj_topic_utils/async_message_queue.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
206
2015-01-21T02:03:18.000Z
2022-02-01T17:57:46.000Z
#pragma once #include <rclcpp/rclcpp.hpp> #include <thread> #include <vector> #include "message_queue.hpp" namespace rj_topic_utils { /** * @brief Declared but not defined template class, so that Policy must be one * of MessagePolicy::kQueue or MessagePolicy::kLatest. * @tparam T The message type to use. * @tparam Policy What policy to use. * @tparam queue_size The queue size to use. For now, this can either be * kUnboundedQueueSize or 1. */ template <typename T, MessagePolicy Policy, int queue_size = kUnboundedQueueSize> class AsyncMessageQueue; // ============================================================================ /** * @brief A asynchronous message queue that stores messages from a ROS2 topic * into a queue, spinning off a worker thread to handle all the ROS2 * subscription work. * @tparam T The message type to use. * @tparam queue_size */ template <typename T, int queue_size> class AsyncMessageQueue<T, MessagePolicy::kQueue, queue_size> { public: using UniquePtr = std::unique_ptr< AsyncMessageQueue<T, MessagePolicy::kQueue, queue_size>>; AsyncMessageQueue(const std::string& node_name, const std::string& topic_name); /** * @brief Returns a vector of unique_ptr to the received ROS2 messages, * emptying the internal queue. * @return A vector of all the messages in in chronologically * ascending order (first is oldest, last is newest). */ std::vector<std::unique_ptr<T>> get_all(); private: rclcpp::Node::SharedPtr node_; MessageQueue<T, MessagePolicy::kQueue> queue_; rclcpp::executors::SingleThreadedExecutor executor_; std::thread worker_; }; // ============================================================================ /** * @brief A asynchronous message queue that stores messages from a ROS2 topic * into a queue, spinning off a worker thread to handle all the ROS2 * subscription work. * @tparam T The message type to use. * @tparam queue_size The size of the queue. */ template <typename T> class AsyncMessageQueue<T, MessagePolicy::kQueue, 1> { public: using UniquePtr = std::unique_ptr<AsyncMessageQueue<T, MessagePolicy::kQueue, 1>>; AsyncMessageQueue(const std::string& node_name, const std::string& topic_name); /** * @brief Returns a unique_ptr to item in the queue, emptying the queue. If * the queue is empty, returns nullptr. * @return unique_ptr to the item in the queue, returning nullptr if the * queue is empty. */ std::unique_ptr<T> get(); private: rclcpp::Node::SharedPtr node_; MessageQueue<T, MessagePolicy::kQueue, 1> queue_; rclcpp::executors::SingleThreadedExecutor executor_; std::thread worker_; }; // ============================================================================ /** * @brief A asynchronous message queue that stores only the latest messages * from a ROS2 topic, spinning off a worker thread to handle all the ROS2 * subscription work. * @tparam T The message type to use. */ template <typename T> class AsyncMessageQueue<T, MessagePolicy::kLatest> { public: using UniquePtr = std::unique_ptr<AsyncMessageQueue<T, MessagePolicy::kLatest>>; AsyncMessageQueue(const std::string& node_name, const std::string& topic_name, const T& default_value); AsyncMessageQueue(const std::string& node_name, const std::string& topic_name); /** * @brief Returns a shared_ptr to the latest received message, or nullptr * if none have been received so far. * @return shared_ptr to the latest received message, or nullptr * if none have been received so far. */ std::shared_ptr<T> get(); private: rclcpp::Node::SharedPtr node_; MessageQueue<T, MessagePolicy::kLatest> queue_; rclcpp::executors::SingleThreadedExecutor executor_; std::thread worker_; }; // ============================================================================ template <typename T, int queue_size> AsyncMessageQueue<T, MessagePolicy::kQueue, queue_size>::AsyncMessageQueue( const std::string& node_name, const std::string& topic_name) : node_{rclcpp::Node::make_shared(node_name)}, queue_{node_.get(), topic_name} { executor_.add_node(node_); worker_ = std::thread([this]() { executor_.spin(); }); } // ============================================================================ template <typename T, int queue_size> std::vector<std::unique_ptr<T>> AsyncMessageQueue<T, MessagePolicy::kQueue, queue_size>::get_all() { std::vector<std::unique_ptr<T>> vec; queue_.get_all_threaded(vec); return vec; } // ============================================================================ template <typename T> AsyncMessageQueue<T, MessagePolicy::kQueue, 1>::AsyncMessageQueue( const std::string& node_name, const std::string& topic_name) : node_{rclcpp::Node::make_shared(node_name)}, queue_{node_.get(), topic_name} { executor_.add_node(node_); worker_ = std::thread([this]() { executor_.spin(); }); } // ============================================================================ template <typename T> std::unique_ptr<T> AsyncMessageQueue<T, MessagePolicy::kQueue, 1>::get() { return queue_.get_threaded(); } // ============================================================================ template <typename T> AsyncMessageQueue<T, MessagePolicy::kLatest>::AsyncMessageQueue( const std::string& node_name, const std::string& topic_name, const T& default_value) : node_{rclcpp::Node::make_shared(node_name)}, queue_{node_.get(), topic_name, default_value} { executor_.add_node(node_); worker_ = std::thread([this]() { executor_.spin(); }); } // ============================================================================ template <typename T> AsyncMessageQueue<T, MessagePolicy::kLatest>::AsyncMessageQueue( const std::string& node_name, const std::string& topic_name) : node_{rclcpp::Node::make_shared(node_name)}, queue_{node_.get(), topic_name} { executor_.add_node(node_); worker_ = std::thread([this]() { executor_.spin(); }); } // ============================================================================ template <typename T> std::shared_ptr<T> AsyncMessageQueue<T, MessagePolicy::kLatest>::get() { return queue_.get_threaded(); } } // namespace rj_topic_utils
35.284153
79
0.612668
[ "vector" ]
a2b1724a31fa61c864ec8a317492c0db928dfed1
11,996
hpp
C++
redist/deps/mcm/Huffman.hpp
VIGGEEN/bundle
9a7a392ea31780660d5b5c34fbe143693c8f0d7b
[ "Zlib" ]
443
2018-01-30T13:36:46.000Z
2022-03-30T18:26:26.000Z
redist/deps/mcm/Huffman.hpp
VIGGEEN/bundle
9a7a392ea31780660d5b5c34fbe143693c8f0d7b
[ "Zlib" ]
3
2019-04-18T08:15:34.000Z
2022-02-13T00:33:07.000Z
redist/deps/mcm/Huffman.hpp
VIGGEEN/bundle
9a7a392ea31780660d5b5c34fbe143693c8f0d7b
[ "Zlib" ]
58
2018-01-20T12:57:10.000Z
2022-03-22T22:10:02.000Z
/* MCM file compressor Copyright (C) 2013, Google Inc. Authors: Mathieu Chartier LICENSE This file is part of the MCM file compressor. MCM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MCM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MCM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _HUFFMAN_HPP_ #define _HUFFMAN_HPP_ #include <algorithm> #include <cassert> #include <set> #include "Compressor.hpp" #include "ProgressMeter.hpp" #include "Range.hpp" class Huffman { public: class Code { public: static const uint32_t nonLeaf = 0; uint32_t value; uint32_t length; Code() : value(0), length(nonLeaf) { } }; template <typename T> class Tree { public: uint32_t value; T weight; Tree *a, *b; forceinline uint32_t getAlphabet() const { return value; } forceinline bool isLeaf() const { return a == nullptr && b == nullptr; } forceinline T getWeight() const { return weight; } void getCodes(Code* codes, uint32_t bits = 0, uint32_t length = 0) const { assert(codes != nullptr); if (isLeaf()) { codes[value].value = bits; codes[value].length = length; } else { a->getCodes(codes, (bits << 1) | 0, length + 1); b->getCodes(codes, (bits << 1) | 1, length + 1); } } void getLengths(T* lengths, uint32_t cur_len = 0) { if (isLeaf()) { lengths[value] = cur_len; } else { a->getLengths(lengths, cur_len + 1); b->getLengths(lengths, cur_len + 1); } } void calcDepth(uint32_t cur_depth = 0) { if (!isLeaf()) weight = 0; if (a != nullptr) { a->calcDepth(cur_depth + 1); weight += a->getWeight(); } if (b != nullptr) { b->calcDepth(cur_depth + 1); weight += b->getWeight(); } } uint64_t getCost(uint32_t bits = 0) const { if (isLeaf()) return bits * weight; else return a->getCost(bits + 1) + b->getCost(bits + 1); } Tree(uint32_t value, T w) : value(value), weight(w), a(nullptr), b(nullptr) { } Tree(Tree* a, Tree* b) : value(0), weight(a->getWeight() + b->getWeight()), a(a), b(b) { } ~Tree() { delete a; delete b; } void printRatio(const char* name) const { //std::cout << "Huffman tree " << name << ": " << getWeight() << " -> " << getCost() / 8 << std::endl; } }; typedef Tree<uint32_t> HuffTree; class TreeComparator { public: inline bool operator()(HuffTree* a, HuffTree* b) const { return a->getWeight() < b->getWeight(); } }; typedef std::multiset<HuffTree*, TreeComparator> TreeSet; public: // TODO, not hardcode the size in?? uint16_t state_trans[256][2]; Code codes[256]; static const uint16_t start_state = 0; forceinline static bool isLeaf(uint16_t state) { return (state & 0x100) != 0; } forceinline uint32_t getTransition(uint16_t state, uint32_t bit) { assert(state < 256); return state_trans[state][bit]; } forceinline static uint32_t getChar(uint16_t state) { assert(isLeaf(state)); return state ^ 0x100; } forceinline const Code& getCode(uint32_t index) const { return codes[index]; } template <typename T> void build(const Tree<T>* tree, uint32_t alphabet_size = 256) { typedef const Tree<T> TTree; tree->getCodes(codes); std::vector<TTree*> work, todo; work.push_back(tree); std::map<TTree*, uint32_t> tree_map; uint32_t cur_state = start_state, cur_state_leaf = cur_state + 0x100; bool state_available[256]; for (auto& b : state_available) b = true; // Calculate tree -> state map. // TODO: Improve layout to maximize number of cache misses to 2 per byte. do { std::vector<TTree*> temp; for (uint32_t i = 0; i < work.size(); ++i) { auto* cur_tree = work[i]; if (cur_tree->isLeaf()) { tree_map[cur_tree] = cur_tree->value | 0x100; } else { if (true || cur_state < 64) { state_available[cur_state] = false; tree_map[cur_tree] = cur_state++; } else { // Try to find a state with matching low 6 bits: // todo } temp.push_back(cur_tree->a); temp.push_back(cur_tree->b); } } work.swap(temp); } while (!work.empty()); // Calculate transitions. for (auto it : tree_map) { auto* t = it.first; if (!isLeaf(tree_map[t])) { state_trans[tree_map[t]][0] = tree_map[t->a]; state_trans[tree_map[t]][1] = tree_map[t->b]; } } } // TODO: Optimize, fix memory leaks. // Based off of example from Introduction to Data Compression. static HuffTree* buildTreePackageMerge(size_t* frequencies, uint32_t count = 256, uint32_t max_depth = 16) { class Package { public: std::multiset<uint32_t> alphabets; uint64_t weight; Package() : weight(0) { } bool operator()(const Package* a, const Package* b) const { if (a->weight < b->weight) return true; if (a->weight > b->weight) return false; return a->alphabets.size() < b->alphabets.size(); } }; uint32_t package_limit = 2 * count - 2; // Set up initial packages. typedef std::multiset<Package*, Package> PSet; PSet original_set; for (uint32_t i = 0; i < count; ++i) { auto* p = new Package; p->alphabets.insert(i); p->weight = 1 + frequencies[i]; // Algorithm can't handle 0 frequencies. original_set.insert(p); } PSet merge_set = original_set; // Perform the package merge algorithm. for (uint32_t i = 1; i < max_depth; ++i) { PSet new_set; size_t count = merge_set.size() / 2; // Package count pacakges. auto it = merge_set.begin(); for (uint32_t j = 0; j < count; ++j) { Package *a = *(it++); Package *b = *(it++); auto *new_package = new Package; new_package->alphabets.insert(a->alphabets.begin(), a->alphabets.end()); new_package->alphabets.insert(b->alphabets.begin(), b->alphabets.end()); new_package->weight = a->weight + b->weight; new_set.insert(new_package); } // Merge back into original set. merge_set = original_set; merge_set.insert(new_set.begin(), new_set.end()); while (merge_set.size() > package_limit) { auto* pend = *merge_set.rbegin(); merge_set.erase(pend); //delete pend; } // Print packages. /*if (false) { for (auto* p : merge_set) { std::cout << " " << p->weight << "{"; for (auto a : p->alphabets) std::cout << a << ","; std::cout << "}, "; } std::cout << std::endl; }*/ } // Calculate lengths. std::vector<uint32_t> lengths(count, 0); for (auto* p : merge_set) { for (auto a : p->alphabets) { ++lengths[a]; } } // Might not work for max_depth = 32. uint32_t total = 0; for (auto l : lengths) { assert(l > 0 && l <= max_depth); total += 1 << (max_depth - l); } // Sanity check. if (total != 1 << max_depth) { std::cerr << "Fatal error constructing huffman table " << total << " vs " << (1 << max_depth) << std::endl; return nullptr; } // Build huffmann tree from the code lengths. return buildFromCodeLengths(&lengths[0], count, max_depth, &frequencies[0]); } static HuffTree* buildFromCodeLengths(uint32_t* lengths, uint32_t count, uint32_t max_depth, size_t* freqs = nullptr) { HuffTree* tree = new HuffTree(uint32_t(0), 0); typedef std::vector<HuffTree*> TreeVec; TreeVec cur_level; cur_level.push_back(tree); for (uint32_t i = 0; i <= max_depth; ++i) { for (uint32_t j = 0; j < count; ++j) { if (lengths[j] == i) { if (cur_level.empty()) break; auto* tree = cur_level.back(); cur_level.pop_back(); tree->value = j; tree->weight = static_cast<uint32_t>(freqs != nullptr ? freqs[j] : 0); } } TreeVec new_set; for (uint32_t i = 0; i < cur_level.size(); ++i) { auto* tree = cur_level[i]; tree->a = new HuffTree(uint32_t(0), 0); tree->b = new HuffTree(uint32_t(0), 0); new_set.push_back(tree->a); new_set.push_back(tree->b); } cur_level = new_set; } tree->calcDepth(0); return tree; } // Combine two smallest trees until we hit max depth. static HuffTree* buildTree(TreeSet& trees) { while (trees.size() > 1) { auto it = trees.begin(); HuffTree *a = *it; trees.erase(it); it = trees.begin(); HuffTree *b = *it; trees.erase(it); // Reinsert the new tree. trees.insert(new HuffTree(a, b)); } return *trees.begin(); } // Write a huffmann tree to a stream. template <typename TEnt, typename TStream> static void writeTree(TEnt& ent, TStream& stream, HuffTree* tree, uint32_t alphabet_size, uint32_t max_length) { std::vector<uint32_t> lengths(alphabet_size, 0); tree->getLengths(&lengths[0]); // Assumes we can't have any 0 length codes. for (uint32_t i = 0; i < alphabet_size; ++i) { assert(lengths[i] > 0 && lengths[i] <= max_length); ent.encodeDirect(stream, lengths[i] - 1, max_length); } } // Read a huffmann tree from a stream. template <typename TEnt, typename TStream> static HuffTree* readTree(TEnt& ent, TStream& stream, uint32_t alphabet_size, uint32_t max_length) { std::vector<uint32_t> lengths(alphabet_size, 0); for (uint32_t i = 0; i < alphabet_size; ++i) { lengths[i] = ent.decodeDirect(stream, max_length) + 1; } return buildFromCodeLengths(&lengths[0], alphabet_size, max_length, nullptr); } static const uint32_t alphabet_size = 256; static const uint32_t max_length = 16; public: static const uint32_t version = 0; void setMemUsage(uint32_t n) {} template <typename TOut, typename TIn> uint64_t Compress(TOut& sout, TIn& sin) { Range7 ent; uint32_t count = 0; std::vector<size_t> freq(alphabet_size, 0); // Get frequencies uint32_t length = 0; for (;;++length) { auto c = sin.read(); if (c == EOF) break; ++freq[static_cast<uint32_t>(c)]; } // Print frequencies printIndexedArray("frequencies", freq); sin.restart(); // Build length limited tree with package merge algorithm. auto* tree = buildTreePackageMerge(&freq[0], alphabet_size, max_length); tree->printRatio("LL(16)"); ProgressMeter meter; ent.init(); writeTree(ent, sout, tree, alphabet_size, max_length); build(tree); std::cout << "Encoded huffmann tree in ~" << sout.getTotal() << " bytes" << std::endl; ent.EncodeBits(sout, length, 31); // Encode with huffman codes. std::cout << std::endl; for (;;) { int c = sin.read(); if (c == EOF) break; const auto& huff_code = getCode(c); ent.EncodeBits(sout, huff_code.value, huff_code.length); meter.addBytePrint(sout.getTotal()); } std::cout << std::endl; ent.flush(sout); return sout.getTotal(); } template <typename TOut, typename TIn> bool DeCompress(TOut& sout, TIn& sin) { Range7 ent; ProgressMeter meter(true); ent.initDecoder(sin); auto* tree = readTree(ent, sin, alphabet_size, max_length); uint32_t length = ent.DecodeDirectBits(sin, 31); // Generate codes. build(tree); std::cout << std::endl; for (uint32_t i = 0; i < length; ++i) { uint32_t state = 0; do { state = getTransition(state, ent.DecodeDirectBit(sin)); } while (!isLeaf(state)); sout.write(getChar(state)); meter.addBytePrint(sin.getTotal()); } std::cout << std::endl; return true; } }; class HuffmanStatic : public MemoryCompressor { static const uint32_t kCodeBits = 16; static const uint32_t kAlphabetSize = 256; public: virtual uint32_t getMaxExpansion(uint32_t in_size) { return in_size * 6 / 5 + (kCodeBits * 256 / kBitsPerByte + 100); } virtual uint32_t compressBytes(byte* in, byte* out, uint32_t count); virtual void decompressBytes(byte* in, byte* out, uint32_t count); }; #endif
26.307018
120
0.64138
[ "vector" ]
a2b818aad03abddaa667a93bf365a7c3777c8be1
5,212
cpp
C++
rest_capabilities.cpp
MoshiBin/deconz-rest-plugin
116b0df8c8aaa4e0cd3976e9fb0de933d7bcf69d
[ "BSD-3-Clause" ]
1,765
2015-06-09T08:10:44.000Z
2022-03-29T16:20:41.000Z
rest_capabilities.cpp
MoshiBin/deconz-rest-plugin
116b0df8c8aaa4e0cd3976e9fb0de933d7bcf69d
[ "BSD-3-Clause" ]
5,354
2015-01-09T21:18:14.000Z
2022-03-31T21:41:56.000Z
rest_capabilities.cpp
MoshiBin/deconz-rest-plugin
116b0df8c8aaa4e0cd3976e9fb0de933d7bcf69d
[ "BSD-3-Clause" ]
506
2015-04-15T14:08:41.000Z
2022-03-28T09:23:35.000Z
/* * Copyright (c) 2018-2019 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "de_web_plugin.h" #include "de_web_plugin_private.h" /*! Capabilities REST API broker. \param req - request data \param rsp - response data \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::handleCapabilitiesApi(const ApiRequest &req, ApiResponse &rsp) { // GET /api/<apikey>/capabilities if ((req.path.size() == 3) && (req.hdr.method() == "GET")) { return getCapabilities(req, rsp); } return REQ_NOT_HANDLED; } /*! GET /api/<apikey>/info/timezones \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::getCapabilities(const ApiRequest &req, ApiResponse &rsp) { Q_UNUSED(req) QVariantMap lightsMap; lightsMap[QLatin1String("available")] = static_cast<double>(MAX_NODES - nodes.size()); lightsMap[QLatin1String("total")] = MAX_NODES; rsp.map[QLatin1String("lights")] = lightsMap; QVariantMap sensorsMap; sensorsMap[QLatin1String("available")] = static_cast<double>(MAX_SENSORS - sensors.size()); sensorsMap[QLatin1String("total")] = MAX_SENSORS; QVariantMap clipMap; clipMap[QLatin1String("available")] = static_cast<double>(MAX_SENSORS - sensors.size()); clipMap[QLatin1String("total")] = MAX_SENSORS; sensorsMap[QLatin1String("clip")] = clipMap; QVariantMap zllMap; zllMap[QLatin1String("available")] = static_cast<double>(MAX_NODES - nodes.size()); zllMap[QLatin1String("total")] = MAX_NODES; sensorsMap[QLatin1String("zll")] = zllMap; QVariantMap zgpMap; zgpMap[QLatin1String("available")] = static_cast<double>(MAX_NODES - nodes.size()); zgpMap[QLatin1String("total")] = MAX_NODES; sensorsMap[QLatin1String("zgp")] = zgpMap; rsp.map[QLatin1String("sensors")] = sensorsMap; QVariantMap groupsMap; groupsMap[QLatin1String("available")] = static_cast<double>(MAX_GROUPS - groups.size()); groupsMap[QLatin1String("total")] = MAX_GROUPS; rsp.map[QLatin1String("groups")] = groupsMap; QVariantMap scenesMap; int scenes_size = 0; int lightstates_size = 0; { std::vector<Group>::iterator g = groups.begin(); std::vector<Group>::iterator g_end = groups.end(); for (; g != g_end; ++g) { scenes_size += g->scenes.size(); std::vector<Scene>::const_iterator s = g->scenes.begin(); std::vector<Scene>::const_iterator s_end = g->scenes.end(); for (; s != s_end; ++s) { lightstates_size += s->lights().size(); } } } scenesMap[QLatin1String("available")] = MAX_SCENES - scenes_size; scenesMap[QLatin1String("total")] = MAX_SCENES; QVariantMap lightstatesMap; lightstatesMap[QLatin1String("available")] = MAX_LIGHTSTATES - lightstates_size; lightstatesMap[QLatin1String("total")] = MAX_LIGHTSTATES; scenesMap[QLatin1String("lightstates")] = lightstatesMap; rsp.map[QLatin1String("scenes")] = scenesMap; QVariantMap schedulesMap; schedulesMap[QLatin1String("available")] = static_cast<double>(MAX_SCHEDULES - schedules.size()); schedulesMap[QLatin1String("total")] = MAX_SCHEDULES; rsp.map[QLatin1String("schedules")] = schedulesMap; QVariantMap rulesMap; int conditions_size = 0; int actions_size = 0; { std::vector<Rule>::const_iterator r = rules.begin(); std::vector<Rule>::const_iterator r_end = rules.end(); for (; r != r_end; ++r) { conditions_size += r->conditions().size(); actions_size += r->actions().size(); } } rulesMap[QLatin1String("available")] = static_cast<double>(MAX_RULES - rules.size()); rulesMap[QLatin1String("total")] = MAX_RULES; QVariantMap conditionsMap; conditionsMap[QLatin1String("available")] = MAX_CONDITIONS - conditions_size; conditionsMap[QLatin1String("total")] = MAX_CONDITIONS; rulesMap[QLatin1String("conditions")] = conditionsMap; QVariantMap actionsMap; actionsMap[QLatin1String("available")] = MAX_ACTIONS - actions_size; actionsMap[QLatin1String("total")] = MAX_ACTIONS; rulesMap[QLatin1String("actions")] = actionsMap; rsp.map[QLatin1String("rules")] = rulesMap; QVariantMap resourcelinksMap; resourcelinksMap[QLatin1String("available")] = static_cast<double>(MAX_RESOURCELINKS - resourcelinks.size()); resourcelinksMap[QLatin1String("total")] = MAX_RESOURCELINKS; rsp.map[QLatin1String("resourcelinks")] = resourcelinksMap; QVariantMap streamingMap; streamingMap[QLatin1String("available")] = MAX_STREAMING; streamingMap[QLatin1String("total")] = MAX_STREAMING; streamingMap[QLatin1String("channels")] = MAX_CHANNELS; rsp.map[QLatin1String("streaming")] = streamingMap; QVariantMap tzs; tzs["values"] = getTimezones(); rsp.map["timezones"] = tzs; rsp.httpStatus = HttpStatusOk; return REQ_READY_SEND; }
37.768116
113
0.678818
[ "vector" ]
a2b961d4e4c01539def90f1b1f0ed1c2540abfd7
16,496
cpp
C++
tectosaur2/hmatrix/aca_ext_impl.cpp
tbenthompson/BIE_tutorials
02cd56ab7e63e36afc4a10db17072076541aab77
[ "MIT" ]
1
2021-06-18T18:02:55.000Z
2021-06-18T18:02:55.000Z
tectosaur2/hmatrix/aca_ext_impl.cpp
tbenthompson/BIE_tutorials
02cd56ab7e63e36afc4a10db17072076541aab77
[ "MIT" ]
null
null
null
tectosaur2/hmatrix/aca_ext_impl.cpp
tbenthompson/BIE_tutorials
02cd56ab7e63e36afc4a10db17072076541aab77
[ "MIT" ]
1
2021-07-14T19:47:00.000Z
2021-07-14T19:47:00.000Z
#include <algorithm> #include <cstdio> #include <math.h> #include "../direct_kernels.hpp" #define Real double struct ACAArgs { // out parameters here Real* buffer; int* uv_ptrs; int* n_terms; // mutable workspace parameters int* next_buffer_ptr; Real* fworkspace; int* iworkspace; // immutable parameters below here /* There are three relevant dimensions to handle a wide range of kernels: - row_dim and col_dim represent the tensor dimensions (row_dim x col_dim) for the input and output of the kernel. - space_dim represents the underlying dimension of the space of the points/entities. Typically, this is 2D or 3D. For example, the displacement -> stress kernel in 3D elasticity has: - row_dim = 6, col_dim = 3, space_dim = 3 - The row_dim is 6 because the stress tensor output has 6 independent components (sxx, syy, szz, sxy, sxz, syz) - The col_dim is 3 because the displacement input has 3 components (x, y, z) - The space_dim is 3 because the observation and source points are 3D. And, for the 2D hypersingular kernel for the Laplace equation: - row_dim = 2, col_dim = 1, space_dim = 2 - The row_dim is 2 because the potential gradient has two components representing the x and y derivatives of the potential. */ int row_dim; int col_dim; // The number of blocks to approximate. int n_blocks; // The index of the obs and src point start and end for each block. All // blocks are contiguous in obs/src idx because the indices have been // re-arranged during the tree construction phase. long* obs_start; long* obs_end; long* src_start; long* src_end; // uv_ptrs holds a set of indices into the buffer array that point to the // location of each row/col in the output U/V matrix. A sufficiently large // array of integers has been allocated in the calling code. Here, // uv_ptrs_starts indicates the first index in the uv_ptrs array to use for // each block. int* uv_ptrs_starts; // Which chunk of the float workspace to use for each block? This might be // removable. int* fworkspace_starts; // For each block, Iref0 and Jref0 provide the index of the starting // reference row/col. This was added historically because generating random // numbers in CUDA is harder than doing it in the calling code. int* Iref0; int* Jref0; // Data on the observation points and the source mesh. Real* obs_pts; Real* src_pts; Real* src_normals; Real* src_weights; Real* tol; int* max_iter; Real* kernel_parameters; bool verbose; }; struct MatrixIndex { int row; int col; }; int buffer_alloc(int* next_ptr, int n_values) { int out; #pragma omp critical { out = *next_ptr; *next_ptr += n_values; } return out; } bool in(int target, int* arr, int n_arr) { // Could be faster by keeping arr sorted and doing binary search. // but that is probably premature optimization. for (int i = 0; i < n_arr; i++) { if (target == arr[i]) { return true; } } return false; } struct MatrixIndex argmax_abs_not_in_list(Real* data, int n_data_rows, int n_data_cols, int* prev, int n_prev, bool rows_or_cols) { struct MatrixIndex max_idx; Real max_val = -1; for (int i = 0; i < n_data_rows; i++) { for (int j = 0; j < n_data_cols; j++) { Real v = fabs(data[i * n_data_cols + j]); int relevant_idx; if (rows_or_cols) { relevant_idx = i; } else { relevant_idx = j; } if (v > max_val && !in(relevant_idx, prev, n_prev)) { max_idx.row = i; max_idx.col = j; max_val = v; } } } return max_idx; } void sub_residual(Real* output, const ACAArgs& a, int n_rows, int n_cols, int rowcol_start, int rowcol_end, int n_terms, bool rows_or_cols, int uv_ptr0) { for (int sr_idx = 0; sr_idx < n_terms; sr_idx++) { int buffer_ptr = a.uv_ptrs[uv_ptr0 + sr_idx]; Real* U_term = &a.buffer[buffer_ptr]; Real* V_term = &a.buffer[buffer_ptr + n_rows]; int n_rowcol = rowcol_end - rowcol_start; if (rows_or_cols) { for (int i = 0; i < n_rowcol; i++) { Real uv = U_term[i + rowcol_start]; for (int j = 0; j < n_cols; j++) { Real vv = V_term[j]; output[i * n_cols + j] -= uv * vv; } } } else { for (int i = 0; i < n_rows; i++) { Real uv = U_term[i]; for (int j = 0; j < n_rowcol; j++) { Real vv = V_term[j + rowcol_start]; output[i * n_rowcol + j] -= uv * vv; } } } } } template <typename K> void calc(const K& kf, Real* output, const ACAArgs& a, int ss, int se, int os, int oe, int rowcol_start, int rowcol_end, bool row_or_col) { int i_start; int i_end; int j_start; int j_end; int obs_dim_start; int obs_dim_end; int src_dim_start; int src_dim_end; if (row_or_col) { int offset = floor(((float)rowcol_start) / a.row_dim); i_start = os + offset; i_end = i_start + 1; j_start = ss; j_end = se; obs_dim_start = rowcol_start - offset * a.row_dim; obs_dim_end = rowcol_end - offset * a.row_dim; src_dim_start = 0; src_dim_end = a.col_dim; } else { int offset = floor(((float)rowcol_start) / a.col_dim); i_start = os; i_end = oe; j_start = ss + offset; j_end = j_start + 1; obs_dim_start = 0; obs_dim_end = a.row_dim; src_dim_start = rowcol_start - offset * a.col_dim; src_dim_end = rowcol_end - offset * a.col_dim; } if (a.verbose) { printf("calc i_start=%i i_end=%i j_start=%i j_end=%i obs_dim_start=%i " "obs_dim_end=%i src_dim_start=%i src_dim_end=%i\n", i_start, i_end, j_start, j_end, obs_dim_start, obs_dim_end, src_dim_start, src_dim_end); } int n_output_src = j_end - j_start; for (int i = i_start; i < i_end; i++) { int obs_idx = i - i_start; DirectObsInfo obs{a.obs_pts[i * 2 + 0], a.obs_pts[i * 2 + 1], a.kernel_parameters}; for (int j = j_start; j < j_end; j++) { int src_idx = j - j_start; Real srcx = a.src_pts[j * 2 + 0]; Real srcy = a.src_pts[j * 2 + 1]; Real srcnx = a.src_normals[j * 2 + 0]; Real srcny = a.src_normals[j * 2 + 1]; Real srcwt = a.src_weights[j]; auto kernel = kf(obs, srcx, srcy, srcnx, srcny); for (int d_obs = obs_dim_start; d_obs < obs_dim_end; d_obs++) { for (int d_src = src_dim_start; d_src < src_dim_end; d_src++) { int idx = ((obs_idx * a.row_dim + (d_obs - obs_dim_start)) * n_output_src + src_idx) * (src_dim_end - src_dim_start) + (d_src - src_dim_start); output[idx] = kernel[d_obs * a.col_dim + d_src] * srcwt; } } } } } template <typename K> void _aca_integrals(K kf, const ACAArgs& a) { #pragma omp parallel for for (long block_idx = 0; block_idx < a.n_blocks; block_idx++) { long os = a.obs_start[block_idx]; long oe = a.obs_end[block_idx]; long ss = a.src_start[block_idx]; long se = a.src_end[block_idx]; long n_obs = oe - os; long n_src = se - ss; long n_rows = n_obs * a.row_dim; long n_cols = n_src * a.col_dim; int uv_ptr0 = a.uv_ptrs_starts[block_idx]; int* block_iworkspace = &a.iworkspace[uv_ptr0]; int* prevIstar = block_iworkspace; int* prevJstar = &block_iworkspace[std::min(n_cols, n_rows) / 2]; Real* block_fworkspace = &a.fworkspace[a.fworkspace_starts[block_idx]]; Real* RIstar = block_fworkspace; Real* RJstar = &block_fworkspace[n_cols]; Real* RIref = &block_fworkspace[n_cols + n_rows]; Real* RJref = &block_fworkspace[n_cols + n_rows + a.row_dim * n_cols]; int Iref = a.Iref0[block_idx]; Iref -= Iref % a.row_dim; int Jref = a.Jref0[block_idx]; Jref -= Jref % a.col_dim; calc(kf, RIref, a, ss, se, os, oe, Iref, Iref + a.row_dim, true); calc(kf, RJref, a, ss, se, os, oe, Jref, Jref + a.col_dim, false); // TODO: this is bad because it limits the number of vectors to half of // what might be needed int max_iter = std::min(a.max_iter[block_idx], (int)std::min(n_rows / 2, n_cols / 2)); Real tol = a.tol[block_idx]; if (a.verbose) { printf("(row_dim, col_dim) = (%i, %i)\n", a.row_dim, a.col_dim); printf("max_iter = %i\n", max_iter); printf("tol = %i\n", max_iter); } Real frob_est = 0; int k = 0; for (; k < max_iter; k++) { if (a.verbose) { printf("\n\nstart iteration %i with Iref=%i Jref=%i\n", k, Iref, Jref); for (int i = 0; i < 5; i++) { printf("RIref[%i] = %f\n", i, RIref[i]); } for (int j = 0; j < 5; j++) { printf("RJref[%i] = %f\n", j, RJref[j]); } } MatrixIndex Istar_entry = argmax_abs_not_in_list(RJref, n_rows, a.col_dim, prevIstar, k, true); MatrixIndex Jstar_entry = argmax_abs_not_in_list(RIref, a.row_dim, n_cols, prevJstar, k, false); int Istar = Istar_entry.row; int Jstar = Jstar_entry.col; Real Istar_val = fabs(RJref[Istar_entry.row * a.col_dim + Istar_entry.col]); Real Jstar_val = fabs(RIref[Jstar_entry.row * n_cols + Jstar_entry.col]); if (a.verbose) { printf("pivot guess %i %i %e %e \n", Istar, Jstar, Istar_val, Jstar_val); } if (Istar_val > Jstar_val) { calc(kf, RIstar, a, ss, se, os, oe, Istar, Istar + 1, true); sub_residual(RIstar, a, n_rows, n_cols, Istar, Istar + 1, k, true, uv_ptr0); Jstar_entry = argmax_abs_not_in_list(RIstar, 1, n_cols, prevJstar, k, false); Jstar = Jstar_entry.col; calc(kf, RJstar, a, ss, se, os, oe, Jstar, Jstar + 1, false); sub_residual(RJstar, a, n_rows, n_cols, Jstar, Jstar + 1, k, false, uv_ptr0); } else { calc(kf, RJstar, a, ss, se, os, oe, Jstar, Jstar + 1, false); sub_residual(RJstar, a, n_rows, n_cols, Jstar, Jstar + 1, k, false, uv_ptr0); Istar_entry = argmax_abs_not_in_list(RJstar, n_rows, 1, prevIstar, k, true); Istar = Istar_entry.row; calc(kf, RIstar, a, ss, se, os, oe, Istar, Istar + 1, true); sub_residual(RIstar, a, n_rows, n_cols, Istar, Istar + 1, k, true, uv_ptr0); } bool done = false; prevIstar[k] = Istar; prevJstar[k] = Jstar; // claim a block of space for the first U and first V vectors and collect // the corresponding Real* pointers int next_buffer_u_ptr = buffer_alloc(a.next_buffer_ptr, n_rows + n_cols); int next_buffer_v_ptr = next_buffer_u_ptr + n_rows; Real* next_buffer_u = &a.buffer[next_buffer_u_ptr]; Real* next_buffer_v = &a.buffer[next_buffer_v_ptr]; // Assign our uv_ptr to point to the u,v buffer location. a.uv_ptrs[uv_ptr0 + k] = next_buffer_u_ptr; Real v2 = 0; for (int i = 0; i < n_cols; i++) { next_buffer_v[i] = RIstar[i] / RIstar[Jstar]; v2 += next_buffer_v[i] * next_buffer_v[i]; } Real u2 = 0; for (int j = 0; j < n_rows; j++) { next_buffer_u[j] = RJstar[j]; u2 += next_buffer_u[j] * next_buffer_u[j]; } if (a.verbose) { printf("true pivot: %i %i \n", Istar, Jstar); printf("diagonal %f \n", RIstar[Jstar]); for (int i = 0; i < 5; i++) { printf("u[%i] = %f\n", i, next_buffer_u[i]); } for (int j = 0; j < 5; j++) { printf("v[%i] = %f\n", j, next_buffer_v[j]); } } Real step_size = sqrt(u2 * v2); frob_est += step_size; if (a.verbose) { printf("step_size %f \n", step_size); printf("frob_est: %f \n", frob_est); } if (step_size < tol) { done = true; } if (k == max_iter - 1) { done = true; } if (done) { break; } if (Iref <= Istar && Istar < Iref + a.row_dim) { while (true) { Iref = (Iref + a.row_dim) % n_rows; Iref -= Iref % a.row_dim; if (!in(Iref, prevIstar, k + 1)) { if (a.verbose) { printf("new Iref: %i \n", Iref); } break; } } calc(kf, RIref, a, ss, se, os, oe, Iref, Iref + a.row_dim, true); sub_residual(RIref, a, n_rows, n_cols, Iref, Iref + a.row_dim, k + 1, true, uv_ptr0); } else { Real* next_buffer_u = &a.buffer[a.uv_ptrs[uv_ptr0 + k]]; Real* next_buffer_v = &a.buffer[a.uv_ptrs[uv_ptr0 + k] + n_rows]; for (int i = 0; i < a.row_dim; i++) { for (int j = 0; j < n_cols; j++) { RIref[i * n_cols + j] -= next_buffer_u[i + Iref] * next_buffer_v[j]; } } } if (Jref <= Jstar && Jstar < Jref + a.col_dim) { while (true) { Jref = (Jref + a.col_dim) % n_cols; Jref -= Jref % a.col_dim; if (!in(Jref, prevJstar, k + 1)) { if (a.verbose) { printf("new Jref: %i \n", Jref); } break; } } calc(kf, RJref, a, ss, se, os, oe, Jref, Jref + a.col_dim, false); sub_residual(RJref, a, n_rows, n_cols, Jref, Jref + a.col_dim, k + 1, false, uv_ptr0); } else { Real* next_buffer_u = &a.buffer[a.uv_ptrs[uv_ptr0 + k]]; Real* next_buffer_v = &a.buffer[a.uv_ptrs[uv_ptr0 + k] + n_rows]; for (int i = 0; i < n_rows; i++) { for (int j = 0; j < a.col_dim; j++) { RJref[i * a.col_dim + j] -= next_buffer_u[i] * next_buffer_v[j + Jref]; } } } } a.n_terms[block_idx] = k + 1; } } void aca_single_layer(const ACAArgs& a) { _aca_integrals(single_layer, a); } void aca_double_layer(const ACAArgs& a) { _aca_integrals(double_layer, a); } void aca_adjoint_double_layer(const ACAArgs& a) { _aca_integrals(adjoint_double_layer, a); } void aca_hypersingular(const ACAArgs& a) { _aca_integrals(hypersingular, a); } void aca_elastic_U(const ACAArgs& a) { _aca_integrals(elastic_U, a); } void aca_elastic_T(const ACAArgs& a) { _aca_integrals(elastic_T, a); } void aca_elastic_A(const ACAArgs& a) { _aca_integrals(elastic_A, a); } void aca_elastic_H(const ACAArgs& a) { _aca_integrals(elastic_H, a); }
35.705628
88
0.515883
[ "mesh", "3d" ]
a2d5d7045642622eec6b9e00f2773d2507debe54
3,258
cpp
C++
src/generated/CPACSFuselages.cpp
MarAlder/tigl
76e1f1442a045e1b8b7954119ca6f9c883ea41e2
[ "Apache-2.0" ]
null
null
null
src/generated/CPACSFuselages.cpp
MarAlder/tigl
76e1f1442a045e1b8b7954119ca6f9c883ea41e2
[ "Apache-2.0" ]
null
null
null
src/generated/CPACSFuselages.cpp
MarAlder/tigl
76e1f1442a045e1b8b7954119ca6f9c883ea41e2
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018 RISC Software GmbH // // This file was generated by CPACSGen from CPACS XML Schema (c) German Aerospace Center (DLR/SC). // Do not edit, all changes are lost when files are re-generated. // // 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 <cassert> #include <CCPACSFuselage.h> #include "CCPACSAircraftModel.h" #include "CCPACSRotorcraftModel.h" #include "CPACSFuselages.h" #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglUIDManager.h" #include "TixiHelper.h" namespace tigl { namespace generated { CPACSFuselages::CPACSFuselages(CCPACSAircraftModel* parent, CTiglUIDManager* uidMgr) : m_uidMgr(uidMgr) { //assert(parent != NULL); m_parent = parent; m_parentType = &typeid(CCPACSAircraftModel); } CPACSFuselages::CPACSFuselages(CCPACSRotorcraftModel* parent, CTiglUIDManager* uidMgr) : m_uidMgr(uidMgr) { //assert(parent != NULL); m_parent = parent; m_parentType = &typeid(CCPACSRotorcraftModel); } CPACSFuselages::~CPACSFuselages() { } CTiglUIDManager& CPACSFuselages::GetUIDManager() { return *m_uidMgr; } const CTiglUIDManager& CPACSFuselages::GetUIDManager() const { return *m_uidMgr; } void CPACSFuselages::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { // read element fuselage if (tixi::TixiCheckElement(tixiHandle, xpath + "/fuselage")) { tixi::TixiReadElements(tixiHandle, xpath + "/fuselage", m_fuselages, 1, tixi::xsdUnbounded, reinterpret_cast<CCPACSFuselages*>(this), m_uidMgr); } } void CPACSFuselages::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { // write element fuselage tixi::TixiSaveElements(tixiHandle, xpath + "/fuselage", m_fuselages); } const std::vector<std::unique_ptr<CCPACSFuselage>>& CPACSFuselages::GetFuselages() const { return m_fuselages; } std::vector<std::unique_ptr<CCPACSFuselage>>& CPACSFuselages::GetFuselages() { return m_fuselages; } CCPACSFuselage& CPACSFuselages::AddFuselage() { m_fuselages.push_back(make_unique<CCPACSFuselage>(reinterpret_cast<CCPACSFuselages*>(this), m_uidMgr)); return *m_fuselages.back(); } void CPACSFuselages::RemoveFuselage(CCPACSFuselage& ref) { for (std::size_t i = 0; i < m_fuselages.size(); i++) { if (m_fuselages[i].get() == &ref) { m_fuselages.erase(m_fuselages.begin() + i); return; } } throw CTiglError("Element not found"); } } // namespace generated } // namespace tigl
30.448598
156
0.672192
[ "vector" ]
a2da03a2a602d1bd9022e67f37a73c48c3d15089
2,770
hpp
C++
tabu_search.hpp
AnkilP/ieeextreme_prep
449cbc198bb5a7466fd72964747ce5c11ec1ef18
[ "MIT" ]
null
null
null
tabu_search.hpp
AnkilP/ieeextreme_prep
449cbc198bb5a7466fd72964747ce5c11ec1ef18
[ "MIT" ]
null
null
null
tabu_search.hpp
AnkilP/ieeextreme_prep
449cbc198bb5a7466fd72964747ce5c11ec1ef18
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <fstream> #include <string> #include <sstream> #include <memory> #include <type_traits> #include <map> #include <queue> #include <ctime> #include <stdlib.h> class CSVReader { std::string fileName; public: CSVReader(std::string filename) : fileName(filename) { } void get(std::vector<std::vector<int>>&); void set(std::string & fileName); }; void CSVReader::set(std::string & fileName){ this->fileName = fileName; } void CSVReader::get(std::vector<std::vector<int>> & dataList) { std::ifstream file(fileName); std::string line; while(std::getline(file,line)) { std::stringstream lineStream(line); std::string cell; std::vector<int> parsedRow; while(std::getline(lineStream,cell,',')) { parsedRow.emplace_back(std::stoi(cell)); } dataList.emplace_back(parsedRow); } // Close the File file.close(); } class neighbour{ int index1; int index2; int spcost; public: neighbour(int i, int j, int cost){ index1 = i; spcost = cost; index2 = j; } neighbour() = default; int getCost() const { return this->spcost; } int getIndex1(){ return this->index1; } int getIndex2(){ return this->index2; } }; class compareNeighbours{ public: int operator() (const neighbour& p1, const neighbour& p2) { return p1.getCost() > p2.getCost(); } }; class tabu_search{ CSVReader flowRead = CSVReader("/home/batman/Documents/google_code_jam/ieeextreme_prep/Flow.csv"); CSVReader distanceRead = CSVReader("/home/batman/Documents/google_code_jam/ieeextreme_prep/Distance.csv"); std::vector<std::vector<int>> flowMatrix; std::vector<std::vector<int>> DistanceMatrix; int tabu_list_size; std::vector<int> state = std::vector<int>(20, 0); std::map<std::vector<int>, int> recency_frequency_matrix; std::map<std::vector<int>, int> frequency_matrix; int best_score; int current_state_score; int numIter; int find_cost(); int find_cost(const std::vector<int> &); void swap(std::vector<int> & state, const int & index1, const int & index2); bool try_add(const std::vector<int> &); void print_recency_matrix(); // static int myrandom(int); public: tabu_search(const int & tabu_list); void move(); void solve(); void print_matrix(const std::vector<std::vector<int>> & matrix); void print_matrix(const std::vector<int> & matrix); void test_cases(); };
22.704918
110
0.601805
[ "vector" ]