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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c14c4bee1fba8a7fbf10317a79e6c08bc5900042 | 2,424 | cpp | C++ | src/xml2cab.cpp | BGCX262/zunda-hg-to-git | a160a1395c4dddbe48a6279872ab1ae12d00184a | [
"BSD-3-Clause"
] | 8 | 2016-09-01T12:10:44.000Z | 2021-12-05T07:08:23.000Z | src/xml2cab.cpp | BGCX262/zunda-hg-to-git | a160a1395c4dddbe48a6279872ab1ae12d00184a | [
"BSD-3-Clause"
] | 1 | 2020-07-22T04:44:25.000Z | 2021-01-08T11:29:57.000Z | src/xml2cab.cpp | BGCX262/zunda-hg-to-git | a160a1395c4dddbe48a6279872ab1ae12d00184a | [
"BSD-3-Clause"
] | 2 | 2019-02-27T02:21:16.000Z | 2021-07-07T05:57:25.000Z | #include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include "sentence.hpp"
#include "modality.hpp"
int main(int argc, char *argv[]) {
boost::program_options::options_description opt("Usage", 200);
opt.add_options()
("file,f", boost::program_options::value<std::string>(), "input xml file (required)")
("outdir,o", boost::program_options::value<std::string>(), "output directory (optional): default same as input xml file")
("enable-wl", "enabled parsing webLine tag")
("help,h", "Show help messages")
("version,v", "Show version informaion");
boost::program_options::variables_map argmap;
boost::program_options::store(parse_command_line(argc, argv, opt), argmap);
boost::program_options::notify(argmap);
if (argmap.count("help")) {
std::cout << opt << std::endl;
return 1;
}
if (argmap.count("version")) {
std::cout << PACKAGE_VERSION << std::endl;
return 1;
}
std::string xml;
if (argmap.count("file")) {
xml = argmap["file"].as<std::string>();
}
else {
std::cerr << "error: input xml file is required" << std::endl;
exit(-1);
}
std::cerr << "input: " << xml << std::endl;
boost::filesystem::path xml_path(xml);
std::string outdir;
if (argmap.count("outdir")) {
outdir = argmap["outdir"].as<std::string>();
}
else {
outdir = xml_path.parent_path().string();
}
std::cerr << "outdir: " << outdir << std::endl;
boost::filesystem::path outdir_path(outdir);
modality::parser mod_parser;
std::vector< std::vector< modality::t_token > > sents;
if (argmap.count("enable-wl")) {
sents = mod_parser.parse_OC(xml_path.string());
}
else {
sents = mod_parser.parse_OW_PB_PN(xml_path.string());
}
int cnt = 0;
BOOST_FOREACH ( std::vector< modality::t_token > sent, sents ) {
nlp::sentence *mod_ipa_sent = new nlp::sentence;
mod_parser.make_tagged_ipasents(sent, modality::IN_DEP_CAB, *mod_ipa_sent);
std::stringstream ss;
ss << (outdir_path / xml_path.stem()).string() << "_" << std::setw(3) << std::setfill('0') << cnt << ".depmod";
std::cerr << "output: " << ss.str() << std::endl;
std::ofstream os(ss.str().c_str());
std::string cabocha_str;
mod_ipa_sent->cabocha(cabocha_str);
os << cabocha_str << std::endl;
os.close();
cnt++;
delete mod_ipa_sent;
}
return true;
}
| 27.545455 | 123 | 0.665429 | [
"vector"
] |
c153f4545201397ba74bfc307b47d9d81000b28c | 6,292 | cc | C++ | src/Geometry/GeomFacet3d.cc | as1m0n/spheral | 4d72822f56aca76d70724c543d389d15ff6ca48e | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | null | null | null | src/Geometry/GeomFacet3d.cc | as1m0n/spheral | 4d72822f56aca76d70724c543d389d15ff6ca48e | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | null | null | null | src/Geometry/GeomFacet3d.cc | as1m0n/spheral | 4d72822f56aca76d70724c543d389d15ff6ca48e | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | null | null | null | #include <limits>
#include "GeomVector.hh"
#include "GeomFacet3d.hh"
#include "Utilities/pointDistances.hh"
#include "Utilities/pointInPolygon.hh"
#include "Utilities/lineSegmentIntersections.hh"
#include "Utilities/safeInv.hh"
namespace Spheral {
//------------------------------------------------------------------------------
// Compare a set of points:
// 1 => all points above.
// 0 => points both above and below (or equal).
// -1 => all points below.
//------------------------------------------------------------------------------
int
GeomFacet3d::
compare(const std::vector<GeomFacet3d::Vector>& points,
const double tol) const {
if (points.size() == 0) return 0;
int result = this->compare(points[0], tol);
int thpt;
for (unsigned i = 1; i != points.size(); ++i) {
thpt = this->compare(points[i], tol);
if (thpt != result) return 0;
}
return result;
}
//------------------------------------------------------------------------------
// Compute the position.
//------------------------------------------------------------------------------
GeomFacet3d::Vector
GeomFacet3d::
position() const {
const unsigned n = mPoints.size();
REQUIRE(n >= 3);
Vector result;
unsigned i, j;
double circum = 0.0, dl;
for (i = 0; i != n; ++i) {
j = (i + 1) % n;
dl = (point(i) - point(j)).magnitude();
result += (point(i) + point(j)) * dl;
circum += dl;
}
result *= safeInvVar(2.0*circum);
return result;
}
//------------------------------------------------------------------------------
// Compute the area.
//------------------------------------------------------------------------------
double
GeomFacet3d::
area() const {
Vector vecsum;
const Vector cent = this->position();
unsigned i, j, npts = mPoints.size();
for (i = 0; i != npts; ++i) {
j = (i + 1) % npts;
vecsum += (point(i) - cent).cross(point(j) - cent);
}
const double result = 0.5*vecsum.magnitude();
ENSURE(result >= 0.0);
return result;
}
//------------------------------------------------------------------------------
// Minimum distance to a point.
//------------------------------------------------------------------------------
double
GeomFacet3d::
distance(const GeomFacet3d::Vector& p) const {
return (p - this->closestPoint(p)).magnitude();
}
//------------------------------------------------------------------------------
// Find the point on the facet closest to the given point.
//------------------------------------------------------------------------------
GeomFacet3d::Vector
GeomFacet3d::
closestPoint(const GeomFacet3d::Vector& p) const {
// First check if the closest point on the plane is in the facet. If so,
// that's it!
const Vector centroid = this->position();
const Vector nhat = this->normal();
CHECK(fuzzyEqual(nhat.magnitude2(), 1.0, 1.0e-10));
Vector result = closestPointOnPlane(p, centroid, nhat);
if (pointInPolygon(result, *mVerticesPtr, mPoints, nhat)) return result;
// Nope, so look for the point around the circumference of the facet that is
// closest.
unsigned i, j, npts = mPoints.size();
double r2, minr2 = std::numeric_limits<double>::max();
Vector potential;
for (i = 0; i != npts; ++i) {
j = (i + 1) % npts;
potential = closestPointOnSegment(p, point(i), point(j));
r2 = (potential - p).magnitude2();
if (r2 < minr2) {
result = potential;
minr2 = r2;
}
}
// That's it.
return result;
}
//------------------------------------------------------------------------------
// Return the points for the triangles that decompose this facet.
//------------------------------------------------------------------------------
void
GeomFacet3d::
decompose(std::vector<std::array<Vector, 3>>& subfacets) const {
const auto numPoints = mPoints.size();
// switch (numPoints) {
// We could specialize as below, but that would make the facets inconsistent.
// case 3:
// // Return the input triangle
// subfacets = {{point(0), point(1), point(2)}};
// break;
// case 4:
// // Split the quadrilateral into two triangles
// subfacets = {{point(0), point(1), point(2)},
// {point(0), point(2), point(3)}};
// break;
// case 5:
// // Split the pentagon into three triangles
// subfacets = {{point(0), point(1), point(2)},
// {point(0), point(2), point(4)},
// {point(2), point(3), point(4)}};
// break;
// case 6:
// // Split the hexagon into four triangles
// subfacets = {{point(0), point(1), point(2)},
// {point(0), point(2), point(3)},
// {point(0), point(3), point(5)},
// {point(3), point(4), point(5)}};,
// default:
const auto centroid = this->position();
subfacets.resize(numPoints);
for (auto i = 0u; i < numPoints; ++i) {
subfacets[i] = {point(i), point((i+1) % numPoints), centroid};
}
// break;
// }
BEGIN_CONTRACT_SCOPE
{
const auto originalArea = this->area();
auto areasum = 0.;
for (auto& subfacet : subfacets) {
const auto ab = subfacet[1] - subfacet[0];
const auto ac = subfacet[2] - subfacet[0];
const auto subnormal = ab.cross(ac);
const auto subarea = 0.5 * subnormal.magnitude();
CONTRACT_VAR(originalArea);
CHECK(0 < subarea and subarea < originalArea);
const auto subnormalUnit = subnormal.unitVector();
const auto normalUnit = mNormal.unitVector();
CHECK(fuzzyEqual(subnormalUnit(0), normalUnit(0), 1.e-12) &&
fuzzyEqual(subnormalUnit(1), normalUnit(1), 1.e-12) &&
fuzzyEqual(subnormalUnit(2), normalUnit(2), 1.e-12));
areasum += subarea;
}
CHECK(fuzzyEqual(areasum, originalArea));
}
END_CONTRACT_SCOPE
}
//------------------------------------------------------------------------------
// Split into triangular sub-facets.
//------------------------------------------------------------------------------
std::vector<GeomFacet3d>
GeomFacet3d::
triangles() const {
std::vector<GeomFacet3d> result;
const auto nverts = mPoints.size();
for (auto k = 1u; k < nverts - 1; ++k) {
result.emplace_back(*mVerticesPtr, std::vector<unsigned>({mPoints[0], mPoints[k], mPoints[k+1]}), mNormal);
}
return result;
}
}
| 32.770833 | 111 | 0.504609 | [
"vector"
] |
c1585d8a0fac348986753724fe8e9d4e42a3253b | 3,653 | hpp | C++ | src/augment_audio.hpp | ashahba/aeon | eafbc6b7040bf594854bd92f1606d37ddd862943 | [
"Apache-2.0"
] | null | null | null | src/augment_audio.hpp | ashahba/aeon | eafbc6b7040bf594854bd92f1606d37ddd862943 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:26:12.000Z | 2022-03-12T00:45:28.000Z | src/augment_audio.hpp | ashahba/aeon | eafbc6b7040bf594854bd92f1606d37ddd862943 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2017 Intel(R) Nervana(TM)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <random>
#include "json.hpp"
#include "interface.hpp"
namespace nervana
{
namespace augment
{
namespace audio
{
class params;
class param_factory;
}
}
}
class nervana::augment::audio::params : public interface::params
{
friend class nervana::augment::audio::param_factory;
public:
friend std::ostream& operator<<(std::ostream& out, const params& obj)
{
out << "add_noise " << obj.add_noise << "\n";
out << "noise_index " << obj.noise_index << "\n";
out << "noise_level " << obj.noise_level << "\n";
out << "noise_offset_fraction " << obj.noise_offset_fraction << "\n";
out << "time_scale_fraction " << obj.time_scale_fraction << "\n";
return out;
}
bool add_noise;
uint32_t noise_index;
float noise_level;
float noise_offset_fraction;
float time_scale_fraction;
private:
params() {}
};
class nervana::augment::audio::param_factory : public json_configurable
{
public:
param_factory(nlohmann::json config);
std::shared_ptr<augment::audio::params> make_params() const;
// This derived distribution gets filled by parsing add_noise_probability
/** Probability of adding noise */
mutable std::bernoulli_distribution add_noise{0.0f};
/** Index into noise index file */
mutable std::uniform_int_distribution<uint32_t> noise_index{0, UINT32_MAX};
/** Offset from start of noise file */
mutable std::uniform_real_distribution<float> noise_offset_fraction{0.0f, 1.0f};
/** Simple linear time-warping */
mutable std::uniform_real_distribution<float> time_scale_fraction{1.0f, 1.0f};
/** How much noise to add (a value of 1 would be 0 dB SNR) */
mutable std::uniform_real_distribution<float> noise_level{0.0f, 0.5f};
private:
float add_noise_probability = 0.0f;
std::vector<std::shared_ptr<interface::config_info_interface>> config_list = {
// ADD_SCALAR(type, mode::REQUIRED, [](const std::string& s) { return s == "audio"; }),
// ADD_SCALAR(max_duration, mode::REQUIRED),
// ADD_SCALAR(frame_stride, mode::REQUIRED),
// ADD_SCALAR(frame_length, mode::REQUIRED),
// ADD_SCALAR(num_cepstra, mode::OPTIONAL),
// ADD_SCALAR(num_filters, mode::OPTIONAL),
// ADD_SCALAR(output_type,
// mode::OPTIONAL,
// [](const std::string& v) { return output_type::is_valid_type(v); }),
// ADD_SCALAR(feature_type, mode::OPTIONAL),
// ADD_SCALAR(window_type, mode::OPTIONAL),
// ADD_SCALAR(noise_root, mode::OPTIONAL),
ADD_SCALAR(add_noise_probability, mode::OPTIONAL),
ADD_DISTRIBUTION(time_scale_fraction,
mode::OPTIONAL,
[](decltype(time_scale_fraction) v) { return v.a() <= v.b(); }),
ADD_DISTRIBUTION(
noise_level, mode::OPTIONAL, [](decltype(noise_level) v) { return v.a() <= v.b(); })};
};
| 34.790476 | 98 | 0.645223 | [
"vector"
] |
c15c18c1538cc0bb75e8da394e57df5dd8253bd4 | 20,676 | cpp | C++ | src/server/ConfigLoader.cpp | benma/opentxs | 40aebd8baa0a1456f00fcafa9eb1b7d72f94b202 | [
"Apache-2.0"
] | 1 | 2015-11-05T12:09:37.000Z | 2015-11-05T12:09:37.000Z | src/server/ConfigLoader.cpp | murrekatt/opentxs | 2f6ee63bbba8c36c5fca1916b345f38f78df01ab | [
"Apache-2.0"
] | null | null | null | src/server/ConfigLoader.cpp | murrekatt/opentxs | 2f6ee63bbba8c36c5fca1916b345f38f78df01ab | [
"Apache-2.0"
] | null | null | null | /************************************************************
*
* ConfigLoader.cpp
*
*/
/************************************************************
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
*
* EMAIL:
* FellowTraveler@rayservers.net
*
* BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
*
* KEY FINGERPRINT (PGP Key in license file):
* 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
*
* OFFICIAL PROJECT WIKI(s):
* https://github.com/FellowTraveler/Moneychanger
* https://github.com/FellowTraveler/Open-Transactions/wiki
*
* WEBSITE:
* http://www.OpenTransactions.org/
*
* Components and licensing:
* -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
* -- otlib.........A class library.......LICENSE:...LAGPLv3
* -- otapi.........A client API..........LICENSE:...LAGPLv3
* -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
* -- otserver......Server Application....LICENSE:....AGPLv3
* Github.com/FellowTraveler/Open-Transactions/wiki/Components
*
* All of the above OT components were designed and written by
* Fellow Traveler, with the exception of Moneychanger, which
* was contracted out to Vicky C (bitcointrader4@gmail.com).
* The open-source community has since actively contributed.
*
* -----------------------------------------------------
*
* LICENSE:
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* ADDITIONAL PERMISSION under the GNU Affero GPL version 3
* section 7: (This paragraph applies only to the LAGPLv3
* components listed above.) If you modify this Program, or
* any covered work, by linking or combining it with other
* code, such other code is not for that reason alone subject
* to any of the requirements of the GNU Affero GPL version 3.
* (==> This means if you are only using the OT API, then you
* don't have to open-source your code--only your changes to
* Open-Transactions itself must be open source. Similar to
* LGPLv3, except it applies to software-as-a-service, not
* just to distributing binaries.)
*
* Extra WAIVER for OpenSSL, Lucre, and all other libraries
* used by Open Transactions: This program is released under
* the AGPL with the additional exemption that compiling,
* linking, and/or using OpenSSL is allowed. The same is true
* for any other open source libraries included in this
* project: complete waiver from the AGPL is hereby granted to
* compile, link, and/or use them with Open-Transactions,
* according to their own terms, as long as the rest of the
* Open-Transactions terms remain respected, with regard to
* the Open-Transactions code itself.
*
* Lucre License:
* This code is also "dual-license", meaning that Ben Lau-
* rie's license must also be included and respected, since
* the code for Lucre is also included with Open Transactions.
* See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
* The Laurie requirements are light, but if there is any
* problem with his license, simply remove the Lucre code.
* Although there are no other blind token algorithms in Open
* Transactions (yet. credlib is coming), the other functions
* will continue to operate.
* See Lucre on Github: https://github.com/benlaurie/lucre
* -----------------------------------------------------
* You should have received a copy of the GNU Affero General
* Public License along with this program. If not, see:
* http://www.gnu.org/licenses/
*
* If you would like to use this software outside of the free
* software license, please contact FellowTraveler.
* (Unfortunately many will run anonymously and untraceably,
* so who could really stop them?)
*
* DISCLAIMER:
* This program is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Affero General Public License for
* more details.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
kamH0Y/n11lCvo1oQxM+
=uSzz
-----END PGP SIGNATURE-----
**************************************************************/
#include <opentxs/server/ConfigLoader.hpp>
#include <opentxs/server/ServerSettings.hpp>
#include <opentxs/core/String.hpp>
#include <opentxs/core/util/OTDataFolder.hpp>
#include <opentxs/core/OTSettings.hpp>
#include <opentxs/core/cron/OTCron.hpp>
#include <opentxs/core/OTLog.hpp>
#include <opentxs/core/crypto/OTCachedKey.hpp>
#include <cstdint>
#define SERVER_WALLET_FILENAME "notaryServer.xml"
#define SERVER_MASTER_KEY_TIMEOUT_DEFAULT -1
#define SERVER_USE_SYSTEM_KEYRING false
namespace opentxs
{
bool ConfigLoader::load(String& walletFilename)
{
const char* szFunc = "ConfigLoader::load()";
// Setup Config File
String strConfigFolder, strConfigFilename;
if (!OTDataFolder::IsInitialized()) {
OT_FAIL;
}
// Create Config Object (OTSettings)
String strConfigFilePath = "";
if (!OTDataFolder::GetConfigFilePath(strConfigFilePath)) {
OT_FAIL;
}
OTSettings* p_Config = new OTSettings(strConfigFilePath);
// First Load, Create new fresh config file if failed loading.
if (!p_Config->Load()) {
OTLog::vOutput(
0, "%s: Note: Unable to Load Config. Creating a new file: %s\n",
szFunc, strConfigFilename.Get());
if (!p_Config->Reset()) return false;
if (!p_Config->Save()) return false;
}
if (!p_Config->Reset()) return false;
// Second Load, Throw Assert if Failed loading.
if (!p_Config->Load()) {
OTLog::vError("%s: Error: Unable to load config file: %s It should "
"exist, as we just saved it!\n",
szFunc, strConfigFilename.Get());
OT_FAIL;
}
// LOG LEVEL
{
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("logging", "log_level", 0, lValue, bIsNewKey);
OTLog::SetLogLevel(static_cast<int32_t>(lValue));
}
// WALLET
// WALLET FILENAME
//
// Clean and Set
{
bool bIsNewKey;
String strValue;
p_Config->CheckSet_str("wallet", "wallet_filename",
SERVER_WALLET_FILENAME, strValue, bIsNewKey);
walletFilename.Set(strValue);
OTLog::vOutput(0, "Using Wallet: %s\n", strValue.Get());
}
// CRON
{
const char* szComment = ";; CRON (regular events like market trades "
"and smart contract clauses)\n";
bool b_SectionExist;
p_Config->CheckSetSection("cron", szComment, b_SectionExist);
}
{
const char* szComment = "; refill_trans_number is the count of "
"transaction numbers cron will grab for "
"itself,\n"
"; whenever its supply is getting low. If it "
"ever drops below 20% of this count\n"
"; while in the middle of processing, it will "
"put a WARNING into your server log.\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("cron", "refill_trans_number", 500, lValue,
bIsNewKey, szComment);
OTCron::SetCronRefillAmount(static_cast<int32_t>(lValue));
}
{
const char* szComment = "; ms_between_cron_beats is the number of "
"milliseconds before Cron processes\n"
"; (all the trades, all the smart contracts, "
"etc every 10 seconds.)\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("cron", "ms_between_cron_beats", 10000, lValue,
bIsNewKey, szComment);
OTCron::SetCronMsBetweenProcess(static_cast<int32_t>(lValue));
}
{
const char* szComment = "; max_items_per_nym is the number of cron "
"items (such as market offers or payment\n"
"; plans) that any given Nym is allowed to "
"have live and active at the same time.\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("cron", "max_items_per_nym", 10, lValue,
bIsNewKey, szComment);
OTCron::SetCronMaxItemsPerNym(static_cast<int32_t>(lValue));
}
// HEARTBEAT
{
const char* szComment = ";; HEARTBEAT\n";
bool bSectionExist;
p_Config->CheckSetSection("heartbeat", szComment, bSectionExist);
}
{
const char* szComment = "; no_requests is the number of client "
"requests the server processes per "
"heartbeat.\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("heartbeat", "no_requests", 10, lValue,
bIsNewKey, szComment);
ServerSettings::SetHeartbeatNoRequests(static_cast<int32_t>(lValue));
}
{
const char* szComment = "; ms_between_beats is the number of "
"milliseconds between each heartbeat.\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("heartbeat", "ms_between_beats", 100, lValue,
bIsNewKey, szComment);
ServerSettings::SetHeartbeatMsBetweenBeats(
static_cast<int32_t>(lValue));
}
// PERMISSIONS
{
const char* szComment = ";; PERMISSIONS\n"
";; You can deactivate server functions here "
"by setting them to false.\n"
";; (Even if you do, override_nym_id will "
"STILL be able to do those functions.)\n";
bool bSectionExists;
p_Config->CheckSetSection("permissions", szComment, bSectionExists);
}
{
String strValue;
const char* szValue;
std::string stdstrValue = ServerSettings::GetOverrideNymID();
szValue = stdstrValue.c_str();
bool bIsNewKey;
if (nullptr == szValue)
p_Config->CheckSet_str("permissions", "override_nym_id", nullptr,
strValue, bIsNewKey);
else
p_Config->CheckSet_str("permissions", "override_nym_id", szValue,
strValue, bIsNewKey);
ServerSettings::SetOverrideNymID(strValue.Get());
}
// MARKETS
{
const char* szComment = "; minimum_scale is the smallest allowed "
"power-of-ten for the scale, for any market.\n"
"; (1oz, 10oz, 100oz, 1000oz.)\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("markets", "minimum_scale",
ServerSettings::GetMinMarketScale(), lValue,
bIsNewKey, szComment);
ServerSettings::SetMinMarketScale(lValue);
}
// SECURITY (beginnings of..)
// Master Key Timeout
{
const char* szComment =
"; master_key_timeout is how int64_t the master key will be in "
"memory until a thread wipes it out.\n"
"; 0 : means you have to type your password EVERY time OT uses a "
"private key. (Even multiple times in a single function.)\n"
"; 300 : means you only have to type it once per 5 minutes.\n"
"; -1 : means you only type it once PER RUN (popular for "
"servers.)\n";
bool bIsNewKey;
int64_t lValue;
p_Config->CheckSet_long("security", "master_key_timeout",
SERVER_MASTER_KEY_TIMEOUT_DEFAULT, lValue,
bIsNewKey, szComment);
OTCachedKey::It()->SetTimeoutSeconds(static_cast<int32_t>(lValue));
}
// Use System Keyring
{
bool bIsNewKey;
bool bValue;
p_Config->CheckSet_bool("security", "use_system_keyring",
SERVER_USE_SYSTEM_KEYRING, bValue, bIsNewKey);
OTCachedKey::It()->UseSystemKeyring(bValue);
#if defined(OT_KEYRING_FLATFILE)
// Is there a password folder? (There shouldn't be, but we allow it...)
//
if (bValue) {
bool bIsNewKey2;
OTString strValue;
p_Config->CheckSet_str("security", "password_folder",
SERVER_PASSWORD_FOLDER, strValue,
bIsNewKey2);
if (strValue.Exists()) {
OTKeyring::FlatFile_SetPasswordFolder(strValue.Get());
OTLog::vOutput(0, " Using server password folder: %s\n",
strValue.Get());
}
}
#endif
}
// (#defined right above this function.)
//
p_Config->SetOption_bool("permissions", "admin_usage_credits",
ServerSettings::__admin_usage_credits);
p_Config->SetOption_bool("permissions", "admin_server_locked",
ServerSettings::__admin_server_locked);
p_Config->SetOption_bool("permissions", "cmd_usage_credits",
ServerSettings::__cmd_usage_credits);
p_Config->SetOption_bool("permissions", "cmd_issue_asset",
ServerSettings::__cmd_issue_asset);
p_Config->SetOption_bool("permissions", "cmd_get_contract",
ServerSettings::__cmd_get_contract);
p_Config->SetOption_bool("permissions", "cmd_check_notary_id",
ServerSettings::__cmd_check_notary_id);
p_Config->SetOption_bool("permissions", "cmd_create_user_acct",
ServerSettings::__cmd_create_user_acct);
p_Config->SetOption_bool("permissions", "cmd_del_user_acct",
ServerSettings::__cmd_del_user_acct);
p_Config->SetOption_bool("permissions", "cmd_check_nym",
ServerSettings::__cmd_check_nym);
p_Config->SetOption_bool("permissions", "cmd_get_requestnumber",
ServerSettings::__cmd_get_requestnumber);
p_Config->SetOption_bool("permissions", "cmd_get_trans_nums",
ServerSettings::__cmd_get_trans_nums);
p_Config->SetOption_bool("permissions", "cmd_send_message",
ServerSettings::__cmd_send_message);
p_Config->SetOption_bool("permissions", "cmd_get_nymbox",
ServerSettings::__cmd_get_nymbox);
p_Config->SetOption_bool("permissions", "cmd_process_nymbox",
ServerSettings::__cmd_process_nymbox);
p_Config->SetOption_bool("permissions", "cmd_create_asset_acct",
ServerSettings::__cmd_create_asset_acct);
p_Config->SetOption_bool("permissions", "cmd_del_asset_acct",
ServerSettings::__cmd_del_asset_acct);
p_Config->SetOption_bool("permissions", "cmd_get_acct",
ServerSettings::__cmd_get_acct);
p_Config->SetOption_bool("permissions", "cmd_get_inbox",
ServerSettings::__cmd_get_inbox);
p_Config->SetOption_bool("permissions", "cmd_get_outbox",
ServerSettings::__cmd_get_outbox);
p_Config->SetOption_bool("permissions", "cmd_process_inbox",
ServerSettings::__cmd_process_inbox);
p_Config->SetOption_bool("permissions", "cmd_issue_basket",
ServerSettings::__cmd_issue_basket);
p_Config->SetOption_bool("permissions", "transact_exchange_basket",
ServerSettings::__transact_exchange_basket);
p_Config->SetOption_bool("permissions", "cmd_notarize_transaction",
ServerSettings::__cmd_notarize_transaction);
p_Config->SetOption_bool("permissions", "transact_process_inbox",
ServerSettings::__transact_process_inbox);
p_Config->SetOption_bool("permissions", "transact_transfer",
ServerSettings::__transact_transfer);
p_Config->SetOption_bool("permissions", "transact_withdrawal",
ServerSettings::__transact_withdrawal);
p_Config->SetOption_bool("permissions", "transact_deposit",
ServerSettings::__transact_deposit);
p_Config->SetOption_bool("permissions", "transact_withdraw_voucher",
ServerSettings::__transact_withdraw_voucher);
p_Config->SetOption_bool("permissions", "transact_pay_dividend",
ServerSettings::__transact_pay_dividend);
p_Config->SetOption_bool("permissions", "transact_deposit_cheque",
ServerSettings::__transact_deposit_cheque);
p_Config->SetOption_bool("permissions", "cmd_get_mint",
ServerSettings::__cmd_get_mint);
p_Config->SetOption_bool("permissions", "transact_withdraw_cash",
ServerSettings::__transact_withdraw_cash);
p_Config->SetOption_bool("permissions", "transact_deposit_cash",
ServerSettings::__transact_deposit_cash);
p_Config->SetOption_bool("permissions", "cmd_get_market_list",
ServerSettings::__cmd_get_market_list);
p_Config->SetOption_bool("permissions", "cmd_get_market_offers",
ServerSettings::__cmd_get_market_offers);
p_Config->SetOption_bool("permissions", "cmd_get_market_recent_trades",
ServerSettings::__cmd_get_market_recent_trades);
p_Config->SetOption_bool("permissions", "cmd_get_nym_market_offers",
ServerSettings::__cmd_get_nym_market_offers);
p_Config->SetOption_bool("permissions", "transact_market_offer",
ServerSettings::__transact_market_offer);
p_Config->SetOption_bool("permissions", "transact_payment_plan",
ServerSettings::__transact_payment_plan);
p_Config->SetOption_bool("permissions", "transact_cancel_cron_item",
ServerSettings::__transact_cancel_cron_item);
p_Config->SetOption_bool("permissions", "transact_smart_contract",
ServerSettings::__transact_smart_contract);
p_Config->SetOption_bool("permissions", "cmd_trigger_clause",
ServerSettings::__cmd_trigger_clause);
// Done Loading... Lets save any changes...
if (!p_Config->Save()) {
OTLog::vError("%s: Error! Unable to save updated Config!!!\n", szFunc);
OT_FAIL;
}
// Finsihed Saving... now lets cleanup!
if (!p_Config->Reset()) return false;
if (nullptr != p_Config) delete p_Config;
p_Config = nullptr;
return true;
}
} // namespace opentxs
| 42.10998 | 80 | 0.614384 | [
"object"
] |
c161bfc8b13b69d4e50ee187e81aa32308ac7c26 | 5,424 | cpp | C++ | SLImageLibraries/SLOpenCVProcess/Private/SLCVMatCImageHandles.cpp | SenonLi/VS_OpenGLSL_4.1 | caaa4c66b0ca93128b2fa615f39c65f621b58803 | [
"MIT"
] | 1 | 2019-01-02T08:14:26.000Z | 2019-01-02T08:14:26.000Z | SLImageLibraries/SLOpenCVProcess/Private/SLCVMatCImageHandles.cpp | SenonLi/OpenGL_4.0_FreeSpace | caaa4c66b0ca93128b2fa615f39c65f621b58803 | [
"MIT"
] | null | null | null | SLImageLibraries/SLOpenCVProcess/Private/SLCVMatCImageHandles.cpp | SenonLi/OpenGL_4.0_FreeSpace | caaa4c66b0ca93128b2fa615f39c65f621b58803 | [
"MIT"
] | null | null | null | #include "../stdafx.h"
#include "SLCVMatCImageHandles.h"
#include "StaticConstBasics\SLGeneralImageBasics.h"
namespace slopencv
{
/// <summary>Bad solution to Get cv::Mat from CImage</summary>
/// <param name="src">CImage [IN]</param>
/// <param name="dst">cv::Mat [OUT]</param>
void ConvertCImageToCVMat(CImage& src, cv::Mat& dst)
{
assert(!src.IsNull());
dst.release();
switch (src.GetBPP())
{
case 8:
dst.create(src.GetHeight(), src.GetWidth(), CV_8UC1);
for (int row = 0; row < src.GetHeight(); row++) {
for (int col = 0; col < src.GetWidth(); col++) {
dst.at<unsigned char>(row, col) = static_cast<BYTE*>(src.GetPixelAddress(col, row))[0];
}
}
break;
case 24:
dst.create(src.GetHeight(), src.GetWidth(), CV_8UC3);
for (int row = 0; row < src.GetHeight(); row++) {
for (int col = 0; col < src.GetWidth(); col++) {
dst.at<cv::Vec3b>(row, col)[0] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[0];
dst.at<cv::Vec3b>(row, col)[1] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[1];
dst.at<cv::Vec3b>(row, col)[2] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[2];
}
}
break;
case 32:
dst.create(src.GetHeight(), src.GetWidth(), CV_8UC4);
for (int row = 0; row < src.GetHeight(); row++) {
for (int col = 0; col < src.GetWidth(); col++) {
dst.at<cv::Vec4b>(row, col)[0] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[0];
dst.at<cv::Vec4b>(row, col)[1] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[1];
dst.at<cv::Vec4b>(row, col)[2] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[2];
dst.at<cv::Vec4b>(row, col)[3] = static_cast<BYTE*>(src.GetPixelAddress(col, row))[3];
}
}
break;
}// End of switch (src.GetBPP())
}// End of ConvertCImageToCVMat(CImage& src, cv::Mat& dst)
/// <summary>cv::imwrite doesn't support Unicode, we need to use CImage to save </summary>
/// <param name="in">cv::Mat image [IN]</param>
/// <param name="out">CImage image [OUT]</param>
/// <remarks>This function only accept BYTE image (8bits per single channel), doesn't support double value image </remarks>
void ConvertCVMatToCImage(const cv::Mat& in, CImage& out)
{
assert(!in.empty());
assert(in.depth() == CV_8U); // Only support BYTE image
if (!out.IsNull())
out.Destroy();
if (in.type() == CV_8UC1) // single channel
out.Create(in.cols, in.rows, in.channels() * slutil::BYTE_IMAGE_SINGLE_CHANNEL_BITS * 3);//CImage doesn't support 8bit single pixel color change
else if (in.type() == CV_8UC4)
out.Create(in.cols, in.rows, in.channels() * slutil::BYTE_IMAGE_SINGLE_CHANNEL_BITS, CImage::createAlphaChannel);
else
out.Create(in.cols, in.rows, in.channels() * slutil::BYTE_IMAGE_SINGLE_CHANNEL_BITS);
switch (in.channels())
{
case 1:
{
for (int row = 0; row < in.rows; row++) {
for (int col = 0; col < in.cols; col++) {
BYTE intensity = in.at<BYTE>(row, col);
static_cast<BYTE*>(out.GetPixelAddress(col, row))[0] = intensity;
static_cast<BYTE*>(out.GetPixelAddress(col, row))[1] = intensity;
static_cast<BYTE*>(out.GetPixelAddress(col, row))[2] = intensity;
}
}
}break;
case 3:
{
for (int row = 0; row < in.rows; row++) {
for (int col = 0; col < in.cols; col++) {
static_cast<BYTE*>(out.GetPixelAddress(col, row))[0] = in.at<cv::Vec3b>(row, col)[0];
static_cast<BYTE*>(out.GetPixelAddress(col, row))[1] = in.at<cv::Vec3b>(row, col)[1];
static_cast<BYTE*>(out.GetPixelAddress(col, row))[2] = in.at<cv::Vec3b>(row, col)[2];
}
}
}break;
case 4:
{
for (int row = 0; row < in.rows; row++) {
for (int col = 0; col < in.cols; col++) {
static_cast<BYTE*>(out.GetPixelAddress(col, row))[0] = in.at<cv::Vec4b>(row, col)[0];
static_cast<BYTE*>(out.GetPixelAddress(col, row))[1] = in.at<cv::Vec4b>(row, col)[1];
static_cast<BYTE*>(out.GetPixelAddress(col, row))[2] = in.at<cv::Vec4b>(row, col)[2];
static_cast<BYTE*>(out.GetPixelAddress(col, row))[3] = in.at<cv::Vec4b>(row, col)[3];
}
}
}break;
default:
assert(true);// Doesn't support cases other than 8bits/24bits/32bits image
} // End of switch (in.channels())
}// End of ConvertCVMatToCImage(const cv::Mat& in, CImage& out)
/// <summary>Get down-sampled CImage based on maxWidthInPixel from raw image stream </summary>
/// <param name="srcEncodedImage">Source Image Stream read from raw image file [IN]</param>
/// <param name="maxWidthInPixel">Down-sampled image width [IN]</param>
/// <param name="dstImage">Down-sampled CImage [OUT]</param>
void GetSmallerImageByWidth(const std::vector<BYTE>& srcEncodedImage, int maxWidthInPixel, CImage& dstImage)
{
assert(!srcEncodedImage.empty());
cv::Mat fullImage = cv::imdecode(cv::Mat(srcEncodedImage), cv::IMREAD_UNCHANGED);
assert(!fullImage.empty() && fullImage.depth() == CV_8U);
if (fullImage.type() == CV_8UC1)
cv::cvtColor(fullImage, fullImage, cv::COLOR_GRAY2RGB);
if (fullImage.cols > maxWidthInPixel)
{
cv::Size newSize(maxWidthInPixel, static_cast<int>(static_cast<double>(fullImage.rows) / fullImage.cols * maxWidthInPixel));
cv::resize(fullImage, fullImage, newSize, 0, 0, cv::INTER_CUBIC);
}
ConvertCVMatToCImage(fullImage, dstImage);
}// End of GetImageByWidth(const std::vector<BYTE>& srcEncodedImage, int maxWidthInPixel, CImage& dstImage)
} // End of namespace slopencv
| 38.468085 | 147 | 0.649705 | [
"vector"
] |
c1680e8137ecce0bb71d4ad9e1362700341c7c9a | 4,818 | cpp | C++ | test-accuracy-msvc-cmath/main.cpp | imallett/minitrig | 6d7269f41850326827b6a6832aee23b49ff39606 | [
"MIT"
] | null | null | null | test-accuracy-msvc-cmath/main.cpp | imallett/minitrig | 6d7269f41850326827b6a6832aee23b49ff39606 | [
"MIT"
] | null | null | null | test-accuracy-msvc-cmath/main.cpp | imallett/minitrig | 6d7269f41850326827b6a6832aee23b49ff39606 | [
"MIT"
] | null | null | null | #include <cassert>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <chrono>
#include <string>
#include <vector>
#include "../libminitrig/include-f32.hpp"
#include "../libminitrig/include-highprec.hpp"
#include "../libminitrig/_misc.hpp"
#ifdef _MSC_VER
#include <intrin.h>
inline uint64_t rdtsc(void) {
return __rdtsc();
}
#else
inline uint64_t rdtsc(void) {
uint32_t low,high;
__asm__ __volatile__ ("rdtsc" : "=a" (low), "=d" (high));
return ((uint64_t)(high) << 32) | low;
}
#endif
static void gen_accuracy_data(char const* cachename, char const* fnname, float(*fn)(float), float low,float high, size_t steps) {
assert(steps>0);
assert(high>=low);
FILE* file;
std::vector<float> xs(steps+1);
for (size_t i=0;i<=steps;++i) xs[i]=((float)(i)/(float)(steps))*(high-low) + low;
std::vector<float> gts(steps+1);
{
std::string filename = ".cache/"+std::string(cachename)+"_"+std::to_string(steps+1)+"_"+std::to_string(low)+"_"+std::to_string(high)+".f32";
file = fopen(filename.c_str(),"rb");
if (file==nullptr) {
fprintf(stderr,"Could not open cache file \"%s\". Run the `test-gen-cache` first to generate.\n",filename.c_str());
getchar();
return;
}
fread(gts.data(), sizeof(float),steps+1, file);
fclose(file);
}
std::vector<float> vals(steps+1);
std::vector<float> dts(steps+1);
#define TRIALS_INNER 512
#define TRIALS_OUTER 16
for (size_t i=0;i<=steps;++i) {
float x=xs[i], val;
double ns_avg,ns_var,ns_stddev;
do {
double sum_dts = 0.0;
double sum_dts_sq = 0.0;
for (size_t j=0;j<TRIALS_OUTER;++j) {
auto t0 = std::chrono::high_resolution_clock::now();
for (int k=0;k<TRIALS_INNER;++k) val=fn(x);
auto t1 = std::chrono::high_resolution_clock::now();
double ns = (double)(std::chrono::duration_cast<std::chrono::nanoseconds>(t1-t0).count())/TRIALS_INNER;
sum_dts += ns;
sum_dts_sq += ns*ns;
}
ns_avg = sum_dts / TRIALS_OUTER;
ns_var = (sum_dts_sq - sum_dts*sum_dts/TRIALS_OUTER)/TRIALS_OUTER;
ns_stddev = sqrt(ns_var);
} while (ns_stddev/ns_avg >= 0.05);
vals[i] = val;
dts[i] = (float)(ns_avg);
}
/*for (int j=0;j<TRIALS;++j) {
float overhead;
do {
uint64_t t0 = rdtsc();
uint64_t t1 = rdtsc();
overhead = (float)(t1) - (float)(t0);
} while (overhead<=0.0f || overhead>1000.0f);
for (size_t i=0;i<=steps;++i) {
float x, val, dt;
do {
x = xs[i];
uint64_t t0 = rdtsc();
val = fn(x);
uint64_t t1 = rdtsc();
dt = (float)(t1) - (float)(t0) - overhead;
} while (dt<=0.0f || dt>=1000.0f);
vals[i] = val;
dts[i] += dt;
}
}
for (float& dt_sum : dts) {
dt_sum /= (float)(TRIALS);
}*/
std::vector<float> errs(steps+1);
for (size_t i=0;i<=steps;++i) errs[i]=fabsf( gts[i] - vals[i] );
file = fopen( (".accuracy/"+std::string(fnname)+".f32").c_str(), "wb" );
fwrite(&low, sizeof(float),1, file);
fwrite(&high, sizeof(float),1, file);
fwrite(errs.data(), sizeof(float),errs.size(), file);
fclose(file);
file = fopen( (".speed/"+std::string(fnname)+".f32").c_str(), "wb" );
fwrite(&low, sizeof(float),1, file);
fwrite(&high, sizeof(float),1, file);
fwrite(dts.data(), sizeof(float),dts.size(), file);
fclose(file);
}
template <typename T> static T clamp(T x, T low,T high) {
if (x<low) return low;
if (x>high) return high;
return x;
}
static void graph( float(*fn)(float), float low,float high, size_t height=11) {
size_t data[80];
for (size_t i=0;i<80;++i) {
float x = ((float)(i)/80.0f)*(high-low) + low;
float temp = 0.5f*fn(x) + 0.5f;
temp *= (float)(height);
data[i] = (size_t)clamp<int>((int)roundf(temp), 0,(int)height);
data[i] = height - data[i];
}
for (size_t j=0;j<=height;++j) {
for (size_t i=0;i<80;++i) {
char c = ' ';
if (j==0||j==height) c='-';
else if (j==height/2) c='=';
if (j==data[i]) c='*';
printf("%c",c);
}
}
}
int main(int /*argc*/, char* /*argv*/[]) {
#define N 10000
gen_accuracy_data( "sin", "sin-32f-minitrig", minitrig::sin, -F32_2PI,2.0f*F32_2PI, N);
gen_accuracy_data( "sin", "sin-32f-msvc", ::sinf, -F32_2PI,2.0f*F32_2PI, N);
gen_accuracy_data( "cos", "cos-32f-minitrig", minitrig::cos, -F32_2PI,2.0f*F32_2PI, N);
gen_accuracy_data( "cos", "cos-32f-msvc", ::cosf, -F32_2PI,2.0f*F32_2PI, N);
gen_accuracy_data( "arcsin", "arcsin-32f-minitrig", minitrig::arcsin, -1.0f,1.0f, N);
gen_accuracy_data( "arcsin", "arcsin-32f-msvc", ::asinf, -1.0f,1.0f, N);
gen_accuracy_data( "arccos", "arccos-32f-minitrig", minitrig::arccos, -1.0f,1.0f, N);
gen_accuracy_data( "arccos", "arccos-32f-msvc", ::acosf, -1.0f,1.0f, N);
return 0;
}
| 29.740741 | 143 | 0.594853 | [
"vector"
] |
c16a396e75f2974f349e356e29ed804e7cebe933 | 9,273 | cpp | C++ | folly/test/MemoryTest.cpp | x4snowman/folly | d52816c1a5b9315fc01f6907de62468e2ae3612d | [
"Apache-2.0"
] | null | null | null | folly/test/MemoryTest.cpp | x4snowman/folly | d52816c1a5b9315fc01f6907de62468e2ae3612d | [
"Apache-2.0"
] | null | null | null | folly/test/MemoryTest.cpp | x4snowman/folly | d52816c1a5b9315fc01f6907de62468e2ae3612d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013-present Facebook, 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.
*/
#include <folly/Memory.h>
#include <type_traits>
#include <utility>
#include <glog/logging.h>
#include <folly/String.h>
#include <folly/memory/Arena.h>
#include <folly/portability/GMock.h>
#include <folly/portability/GTest.h>
using namespace folly;
TEST(aligned_malloc, examples) {
auto trial = [](size_t align) {
auto const ptr = aligned_malloc(1, align);
return (aligned_free(ptr), uintptr_t(ptr));
};
if (!kIsSanitize) { // asan allocator raises SIGABRT instead
EXPECT_EQ(EINVAL, (trial(2), errno)) << "too small";
EXPECT_EQ(EINVAL, (trial(513), errno)) << "not power of two";
}
EXPECT_EQ(0, trial(512) % 512);
EXPECT_EQ(0, trial(8192) % 8192);
}
TEST(make_unique, compatible_with_std_make_unique) {
// HACK: To enforce that `folly::` is imported here.
to_shared_ptr(std::unique_ptr<std::string>());
using namespace std;
make_unique<string>("hello, world");
}
TEST(to_weak_ptr, example) {
auto s = std::make_shared<int>(17);
EXPECT_EQ(1, s.use_count());
EXPECT_EQ(2, (to_weak_ptr(s).lock(), s.use_count())) << "lvalue";
EXPECT_EQ(3, (to_weak_ptr(decltype(s)(s)).lock(), s.use_count())) << "rvalue";
}
TEST(SysAllocator, equality) {
using Alloc = SysAllocator<float>;
Alloc const a, b;
EXPECT_TRUE(a == b);
EXPECT_FALSE(a != b);
}
TEST(SysAllocator, allocate_unique) {
using Alloc = SysAllocator<float>;
Alloc const alloc;
auto ptr = allocate_unique<float>(alloc, 3.);
EXPECT_EQ(3., *ptr);
}
TEST(SysAllocator, vector) {
using Alloc = SysAllocator<float>;
Alloc const alloc;
std::vector<float, Alloc> nums(alloc);
nums.push_back(3.);
nums.push_back(5.);
EXPECT_THAT(nums, testing::ElementsAreArray({3., 5.}));
}
TEST(SysAllocator, bad_alloc) {
using Alloc = SysAllocator<float>;
Alloc const alloc;
std::vector<float, Alloc> nums(alloc);
if (!kIsSanitize) {
EXPECT_THROW(nums.reserve(1ull << 50), std::bad_alloc);
}
}
TEST(AlignedSysAllocator, equality_fixed) {
using Alloc = AlignedSysAllocator<float, FixedAlign<1024>>;
Alloc const a, b;
EXPECT_TRUE(a == b);
EXPECT_FALSE(a != b);
}
TEST(AlignedSysAllocator, allocate_unique_fixed) {
using Alloc = AlignedSysAllocator<float, FixedAlign<1024>>;
Alloc const alloc;
auto ptr = allocate_unique<float>(alloc, 3.);
EXPECT_EQ(3., *ptr);
EXPECT_EQ(0, std::uintptr_t(ptr.get()) % 1024);
}
TEST(AlignedSysAllocator, vector_fixed) {
using Alloc = AlignedSysAllocator<float, FixedAlign<1024>>;
Alloc const alloc;
std::vector<float, Alloc> nums(alloc);
nums.push_back(3.);
nums.push_back(5.);
EXPECT_THAT(nums, testing::ElementsAreArray({3., 5.}));
EXPECT_EQ(0, std::uintptr_t(nums.data()) % 1024);
}
TEST(AlignedSysAllocator, bad_alloc_fixed) {
using Alloc = AlignedSysAllocator<float, FixedAlign<1024>>;
Alloc const alloc;
std::vector<float, Alloc> nums(alloc);
if (!kIsSanitize) {
EXPECT_THROW(nums.reserve(1ull << 50), std::bad_alloc);
}
}
TEST(AlignedSysAllocator, equality_default) {
using Alloc = AlignedSysAllocator<float>;
Alloc const a(1024), b(1024), c(512);
EXPECT_TRUE(a == b);
EXPECT_FALSE(a != b);
EXPECT_FALSE(a == c);
EXPECT_TRUE(a != c);
}
TEST(AlignedSysAllocator, allocate_unique_default) {
using Alloc = AlignedSysAllocator<float>;
Alloc const alloc(1024);
auto ptr = allocate_unique<float>(alloc, 3.);
EXPECT_EQ(3., *ptr);
EXPECT_EQ(0, std::uintptr_t(ptr.get()) % 1024);
}
TEST(AlignedSysAllocator, vector_default) {
using Alloc = AlignedSysAllocator<float>;
Alloc const alloc(1024);
std::vector<float, Alloc> nums(alloc);
nums.push_back(3.);
nums.push_back(5.);
EXPECT_THAT(nums, testing::ElementsAreArray({3., 5.}));
EXPECT_EQ(0, std::uintptr_t(nums.data()) % 1024);
}
TEST(AlignedSysAllocator, bad_alloc_default) {
using Alloc = AlignedSysAllocator<float>;
Alloc const alloc(1024);
std::vector<float, Alloc> nums(alloc);
if (!kIsSanitize) {
EXPECT_THROW(nums.reserve(1ull << 50), std::bad_alloc);
}
}
TEST(allocate_sys_buffer, compiles) {
auto buf = allocate_sys_buffer(256);
// Freed at the end of the scope.
}
namespace {
template <typename T>
struct TestAlloc1 : SysAllocator<T> {
template <typename U, typename... Args>
void construct(U* p, Args&&... args) {
::new (static_cast<void*>(p)) U(std::forward<Args>(args)...);
}
};
template <typename T>
struct TestAlloc2 : TestAlloc1<T> {
template <typename U>
void destroy(U* p) {
p->~U();
}
};
template <typename T>
struct TestAlloc3 : TestAlloc2<T> {
using folly_has_default_object_construct = std::true_type;
};
template <typename T>
struct TestAlloc4 : TestAlloc3<T> {
using folly_has_default_object_destroy = std::true_type;
};
template <typename T>
struct TestAlloc5 : SysAllocator<T> {
using folly_has_default_object_construct = std::true_type;
using folly_has_default_object_destroy = std::false_type;
};
} // namespace
TEST(AllocatorObjectLifecycleTraits, compiles) {
using A = std::allocator<int>;
using S = std::string;
static_assert(
folly::AllocatorHasDefaultObjectConstruct<A, int, int>::value, "");
static_assert(folly::AllocatorHasDefaultObjectConstruct<A, S, S>::value, "");
static_assert(folly::AllocatorHasDefaultObjectDestroy<A, int>::value, "");
static_assert(folly::AllocatorHasDefaultObjectDestroy<A, S>::value, "");
static_assert(
folly::AllocatorHasDefaultObjectConstruct<
folly::AlignedSysAllocator<int>,
int,
int>::value,
"");
static_assert(
folly::AllocatorHasDefaultObjectConstruct<
folly::AlignedSysAllocator<int>,
S,
S>::value,
"");
static_assert(
folly::AllocatorHasDefaultObjectDestroy<
folly::AlignedSysAllocator<int>,
int>::value,
"");
static_assert(
folly::AllocatorHasDefaultObjectDestroy<
folly::AlignedSysAllocator<int>,
S>::value,
"");
static_assert(
!folly::AllocatorHasDefaultObjectConstruct<TestAlloc1<S>, S, S>::value,
"");
static_assert(
folly::AllocatorHasDefaultObjectDestroy<TestAlloc1<S>, S>::value, "");
static_assert(
!folly::AllocatorHasDefaultObjectConstruct<TestAlloc2<S>, S, S>::value,
"");
static_assert(
!folly::AllocatorHasDefaultObjectDestroy<TestAlloc2<S>, S>::value, "");
static_assert(
folly::AllocatorHasDefaultObjectConstruct<TestAlloc3<S>, S, S>::value,
"");
static_assert(
!folly::AllocatorHasDefaultObjectDestroy<TestAlloc3<S>, S>::value, "");
static_assert(
folly::AllocatorHasDefaultObjectConstruct<TestAlloc4<S>, S, S>::value,
"");
static_assert(
folly::AllocatorHasDefaultObjectDestroy<TestAlloc4<S>, S>::value, "");
static_assert(
folly::AllocatorHasDefaultObjectConstruct<TestAlloc5<S>, S, S>::value,
"");
static_assert(
!folly::AllocatorHasDefaultObjectDestroy<TestAlloc5<S>, S>::value, "");
}
template <typename C>
static void test_enable_shared_from_this(std::shared_ptr<C> sp) {
ASSERT_EQ(1l, sp.use_count());
// Test shared_from_this().
std::shared_ptr<C> sp2 = sp->shared_from_this();
ASSERT_EQ(sp, sp2);
// Test weak_from_this().
std::weak_ptr<C> wp = sp->weak_from_this();
ASSERT_EQ(sp, wp.lock());
sp.reset();
sp2.reset();
ASSERT_EQ(nullptr, wp.lock());
// Test shared_from_this() and weak_from_this() on object not owned by a
// shared_ptr. Undefined in C++14 but well-defined in C++17. Also known to
// work with libstdc++ >= 20150123. Feel free to add other standard library
// versions where the behavior is known.
#if __cplusplus >= 201700L || __GLIBCXX__ >= 20150123L
C stack_resident;
ASSERT_THROW(stack_resident.shared_from_this(), std::bad_weak_ptr);
ASSERT_TRUE(stack_resident.weak_from_this().expired());
#endif
}
TEST(enable_shared_from_this, compatible_with_std_enable_shared_from_this) {
// Compile-time compatibility.
class C_std : public std::enable_shared_from_this<C_std> {};
class C_folly : public folly::enable_shared_from_this<C_folly> {};
static_assert(
noexcept(std::declval<C_std>().shared_from_this()) ==
noexcept(std::declval<C_folly>().shared_from_this()),
"");
static_assert(
noexcept(std::declval<C_std const>().shared_from_this()) ==
noexcept(std::declval<C_folly const>().shared_from_this()),
"");
static_assert(noexcept(std::declval<C_folly>().weak_from_this()), "");
static_assert(noexcept(std::declval<C_folly const>().weak_from_this()), "");
// Runtime compatibility.
test_enable_shared_from_this(std::make_shared<C_folly>());
test_enable_shared_from_this(std::make_shared<C_folly const>());
}
| 29.626198 | 80 | 0.69395 | [
"object",
"vector"
] |
c16c80a184d7deddf69e3326e987f50ddcac375e | 3,948 | cc | C++ | src/yb/integration-tests/log_version-test.cc | myang2021/yugabyte-db | 165a48be4c29e408f986f64bc3bba306752de5b9 | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2021-08-18T03:06:54.000Z | 2021-08-18T03:06:54.000Z | src/yb/integration-tests/log_version-test.cc | myang2021/yugabyte-db | 165a48be4c29e408f986f64bc3bba306752de5b9 | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2021-08-28T22:46:44.000Z | 2021-08-28T22:46:44.000Z | src/yb/integration-tests/log_version-test.cc | myang2021/yugabyte-db | 165a48be4c29e408f986f64bc3bba306752de5b9 | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | // Copyright (c) YugaByte, 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.
//
#include <fstream>
#include <regex>
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include <glog/logging.h>
#include "yb/integration-tests/external_mini_cluster.h"
#include "yb/integration-tests/external_mini_cluster-itest-base.h"
#include "yb/master/master.pb.h"
#include "yb/rpc/rpc_controller.h"
#include "yb/util/path_util.h"
#include "yb/util/size_literals.h"
#include "yb/util/string_trim.h"
#include "yb/util/subprocess.h"
#include "yb/util/test_util.h"
using std::string;
namespace yb {
namespace test {
namespace {
const string kDurationPrefix("Running duration (h:mm:ss): ");
class LogHeader {
public:
explicit LogHeader(const string& file_path) {
std::ifstream log_stream(file_path);
string line;
for(int i = 0; i < 10 && getline(log_stream, line); ++i) {
lines_.push_back(std::move(line));
}
}
const string& GetByPrefix(const string& prefix) const {
static const std::string empty;
for(const auto& l : lines_) {
if(boost::algorithm::starts_with(l, prefix)) {
return l;
}
}
return empty;
}
private:
std::vector<string> lines_;
};
} // namespace
class LogRollingTest : public ExternalMiniClusterITestBase {
public:
void SetUpCluster(ExternalMiniClusterOptions* opts) override {
ExternalMiniClusterITestBase::SetUpCluster(opts);
opts->log_to_file = true;
}
};
TEST_F(LogRollingTest, Rolling) {
// Set minimal possible size limit for file rolling
StartCluster({}, {"--max_log_size=1"}, 1);
auto master = cluster_->master();
const auto exe = master->exe();
string version;
ASSERT_OK(Subprocess::Call({exe, "--version"}, &version));
version = util::TrimStr(version);
ASSERT_TRUE(std::regex_match(
version, std::regex(R"(version \S+ build \S+ revision \S+ build_type \S+ built at .+)")));
const auto log_path = JoinPathSegments(master->GetDataDirs()[0], "logs", BaseName(exe) + ".INFO");
const auto fingerprint = "Application fingerprint: " + version;
const LogHeader header(log_path);
ASSERT_NE(header.GetByPrefix(fingerprint), "");
const auto& initial_duration = header.GetByPrefix(kDurationPrefix);
ASSERT_NE(initial_duration, "");
// In case of log rolling log_path link will be pointed to newly created file
const auto initial_target = ASSERT_RESULT(env_->ReadLink(log_path));
auto prev_size = ASSERT_RESULT(env_->GetFileSize(log_path));
auto master_proxy = cluster_->master_proxy();
while(initial_target == ASSERT_RESULT(env_->ReadLink(log_path))) {
// Call rpc functions to generate logs in master
for(int i = 0; i < 20; ++i) {
master::TruncateTableRequestPB req;
master::TruncateTableResponsePB resp;
rpc::RpcController rpc;
ASSERT_OK(master_proxy->TruncateTable(req, &resp, &rpc));
}
const auto current_size = ASSERT_RESULT(env_->GetFileSize(log_path));
// Make sure log size is changed and it is not much than 2Mb
// Something goes wrong in other case
ASSERT_NE(current_size, prev_size);
ASSERT_LT(current_size, 2_MB);
prev_size = current_size;
}
const LogHeader fresh_header(log_path);
ASSERT_NE(fresh_header.GetByPrefix(fingerprint), "");
const auto& duration = fresh_header.GetByPrefix(kDurationPrefix);
ASSERT_NE(duration, "");
ASSERT_NE(duration, initial_duration);
}
} // namespace test
} // namespace yb
| 32.360656 | 100 | 0.714539 | [
"vector"
] |
c1708eac4cccb5f0ff369d63caadad2ce43a0614 | 3,791 | cpp | C++ | examples/cli_hello.cpp | michab66/dev_smack_cpp | 37d57b8ccf35e8bbcc98c12eeaf2aeb7b82fa6c6 | [
"MIT"
] | 2 | 2021-07-19T16:13:46.000Z | 2021-11-25T13:39:46.000Z | examples/cli_hello.cpp | michab66/dev_smack_cpp | 37d57b8ccf35e8bbcc98c12eeaf2aeb7b82fa6c6 | [
"MIT"
] | 34 | 2021-06-27T08:54:35.000Z | 2022-02-16T09:13:56.000Z | examples/cli_hello.cpp | michab66/dev_smack_cpp | 37d57b8ccf35e8bbcc98c12eeaf2aeb7b82fa6c6 | [
"MIT"
] | null | null | null | /* Smack C++ @ https://github.com/smacklib/dev_smack_cpp
*
* smack::cli example.
*
* Copyright © 2019-2021 Michael Binz
*/
#include <iostream>
#include <string>
// Include smack cli support.
#include <smack_cli.hpp>
// smack::cli's basic concept is to make functions implemented in
// C++ callable from the command line as commands with minimial
// efforts for the coder. That is, parameter conversion is
// handled automatically and a nice help page is printed if
// the cli is executed without any arguments.
// See ...
// This anonymous name space is used to hold the functions that should
// be invoked from the command line. Not needed but recommended.
namespace {
using smack::cli::Commands;
using std::cout;
using std::endl;
using std::string;
// Here come the plain functions. Each one represents later a
// command on the command line.
// Add function parameters as needed, these are automatically
// converted by smack::cli when the function is called from the
// command line. Below we only use primitive parameters.
// See https://github.com/smacklib/dev_smack_cpp/blob/master/examples/cli_hello_new_type.cpp
// for an example that adds user-defined types.
// The function's return value represents the process return code.
int add_int(int p1, int p2) {
cout << (p1+p2) << endl;
return EXIT_SUCCESS;
}
int add_float(float p1, float p2) {
cout << (p1+p2) << endl;
return EXIT_SUCCESS;
}
int concat(string p1, string p2) {
cout << (p1+p2) << endl;
return EXIT_SUCCESS;
}
// No arguments.
int pi() {
cout << 3.14159265 << endl;
return EXIT_SUCCESS;
}
// Throws an error. The error is catched by cli::smack
// and returned as a proper error message.
int error() {
throw std::runtime_error( "error() was called." );
}
// Throws an error. Demonstrates error handling.
int error_1(const string& message) {
throw std::runtime_error(message);
}
} // namespace anonymous
int main(int argc, char**argv)
{
// Now tie everything together: Create an application object
// and register the commands one by one.
smack::cli::CliApplication cli{
// An overall help text for the cli.
"Demonstrates smack::cli. Enjoy...",
// A fully specified command. The template parameter
// refers to the function above that is called by the
// command.
Commands::make<add_int>(
// The command name that is used to select the
// command on the command line. This can be freely
// selected.
"add_int",
// Text describing the command.
"Add two integers.",
// A list of symbolic argument names.
{ "first", "second" }),
// A minimal command, just a function reference and the
// command name need to be passed.
Commands::make<add_float>(
"add_float"),
// Simple. Function arguments are strings, but these
// are automatically parsed as the arguments of the
// functions above.
Commands::make<concat>(
"concat", "Concatenate strings." ),
// No argument at all.
Commands::make<pi>(
"pi", "Returns PI."),
// Overloading. This is 'error' with no parameter.
Commands::make<error>(
"error", "Print a predefined error."),
// Overload the 'error' command with a function taking one
// parameter.
Commands::make<error_1>(
"error", "Print an error message.",
{"message"})
};
// Finally launch the application. The launch operation
// returns the executed command's return value. We simply return
// this from main() and are done.
return cli.launch(argc, argv);
// Easy, eh?
}
| 30.087302 | 92 | 0.642047 | [
"object"
] |
c17753ba9c09c8486bf507f202be746758968a30 | 35,928 | cpp | C++ | src/htl/GenCommonIncFile.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | src/htl/GenCommonIncFile.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | src/htl/GenCommonIncFile.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | /* Copyright (c) 2015 Convey Computer Corporation
*
* This file is part of the OpenHT toolset located at:
*
* https://github.com/TonyBrewer/OpenHT
*
* Use and distribution licensed under the BSD 3-clause license.
* See the LICENSE file for the complete license text.
*/
#include "CnyHt.h"
#include "DsnInfo.h"
void CDsnInfo::GenerateCommonIncludeFile()
{
string unitNameUc = !g_appArgs.IsModuleUnitNamesEnabled() ? m_unitName.Uc() : "";
string fileName = g_appArgs.GetOutputFolder() + "/Pers" + unitNameUc + "Common.h";
CHtFile incFile(fileName.c_str(), "w");
GenerateBanner(incFile, fileName.c_str(), true);
for (size_t i = 0; i < m_includeList.size(); i += 1) {
// only print include if not in src directory
string &fullPath = m_includeList[i].m_fullPath;
size_t pos = fullPath.find_last_of("/\\");
if (strncmp(fullPath.c_str() + pos - 3, "src", 3) != 0)
fprintf(incFile, "#include \"%s\"\n", m_includeList[i].m_name.c_str());
}
if (m_includeList.size() > 0)
fprintf(incFile, "\n");
fprintf(incFile, "#ifndef _HTV\n");
fprintf(incFile, "#include \"sysc/SyscMon.h\"\n");
fprintf(incFile, "#endif\n");
fprintf(incFile, "\n");
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Common #define's\n");
fprintf(incFile, "\n");
fprintf(incFile, "#define HT_INVALID 0\n");
fprintf(incFile, "#define HT_CONT 1\n");
fprintf(incFile, "#define HT_CALL 2\n");
fprintf(incFile, "#define HT_RTN 3\n");
fprintf(incFile, "#define HT_JOIN 4\n");
fprintf(incFile, "#define HT_RETRY 5\n");
fprintf(incFile, "#define HT_TERM 6\n");
fprintf(incFile, "#define HT_PAUSE 7\n");
fprintf(incFile, "#define HT_JOIN_AND_CONT 8\n");
fprintf(incFile, "\n");
for (size_t i = 0; i< m_defineTable.size(); i += 1) {
// must be a unit or host
if (m_defineTable[i].m_scope.compare("unit") == 0 && !m_defineTable[i].m_bPreDefined) {
fprintf(incFile, "#define %s",
m_defineTable[i].m_name.c_str());
if (m_defineTable[i].m_bHasParamList) {
fprintf(incFile, "(");
char * pSeparator = "";
for (size_t j = 0; j < m_defineTable[i].m_paramList.size(); j += 1) {
fprintf(incFile, "%s%s", pSeparator, m_defineTable[i].m_paramList[j].c_str());
pSeparator = ",";
}
fprintf(incFile, ")");
}
fprintf(incFile, " %s\n",
m_defineTable[i].m_value.c_str());
}
}
if (GetMacroTblSize() > 0 || m_defineTable.size() > 0)
fprintf(incFile, "\n");
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Common typedef's\n");
fprintf(incFile, "\n");
for (size_t typedefIdx = 0; typedefIdx < m_typedefList.size(); typedefIdx += 1) {
CTypeDef &typeDef = m_typedefList[typedefIdx];
if (typeDef.m_scope.compare("unit") != 0) {
continue; // host or module or auto
}
if (typeDef.m_width.size() == 0)
fprintf(incFile, "typedef %s %s;\n", typeDef.m_type.c_str(), typeDef.m_name.c_str());
else {
int width = typeDef.m_width.AsInt();
if (typeDef.m_name == "uint8_t" || typeDef.m_name == "uint16_t" || typeDef.m_name == "uint32_t" || typeDef.m_name == "uint64_t"
|| typeDef.m_name == "int8_t" || typeDef.m_name == "int16_t" || typeDef.m_name == "int32_t" || typeDef.m_name == "int64_t")
continue;
if (width > 0) {
if (typeDef.m_type.substr(0, 3) == "int")
fprintf(incFile, "typedef %s<%s> %s;\n",
width > 64 ? "sc_bigint" : "sc_int", typeDef.m_width.c_str(), typeDef.m_name.c_str());
else if (typeDef.m_type.substr(0, 4) == "uint")
fprintf(incFile, "typedef %s<%s> %s;\n",
width > 64 ? "sc_biguint" : "sc_uint", typeDef.m_width.c_str(), typeDef.m_name.c_str());
else
ParseMsg(Fatal, typeDef.m_lineInfo, "unexpected type '%s'", typeDef.m_type.c_str());
}
}
}
fprintf(incFile, "\n");
// If csr intf exists
bool bSimCsrUsed = false;
for (size_t modIdx = 0; modIdx < m_modList.size(); modIdx += 1) {
CModule &mod = *m_modList[modIdx];
if (!mod.m_bIsUsed) continue;
if (mod.m_uioCsrIntfList.size() > 0) {
bSimCsrUsed = true;
}
}
if (bSimCsrUsed) {
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// CSR typedef's\n");
fprintf(incFile, "\n");
fprintf(incFile, "struct uio_csr_rq_t {\n");
fprintf(incFile, "\tint cmd;\n");
fprintf(incFile, "\tuint64_t addr;\n");
fprintf(incFile, "\tuint64_t data;\n");
fprintf(incFile, "};\n");
fprintf(incFile, "\n");
fprintf(incFile, "struct uio_csr_rs_t {\n");
fprintf(incFile, "\tuint64_t data;\n");
fprintf(incFile, "};\n");
fprintf(incFile, "\n");
}
fprintf(incFile, "#ifdef _HTV\n");
fprintf(incFile, "#define INT(a) a\n");
fprintf(incFile, "#else\n");
fprintf(incFile, "#define INT(a) int(a)\n");
fprintf(incFile, "#define HT_CYC_1X ((long long)sc_time_stamp().value() / 10000)\n");
fprintf(incFile, "#endif\n");
fprintf(incFile, "\n");
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Ht Assert interfaces\n");
fprintf(incFile, "\n");
fprintf(incFile, "#ifdef HT_ASSERT\n");
fprintf(incFile, "#\tifdef _HTV\n");
fprintf(incFile, "#\t\tdefine HtAssert(expression, info) \\\n");
fprintf(incFile, "\t\tif (!c_htAssert.m_bAssert && !(expression)) {\\\n");
fprintf(incFile, "\t\t\tc_htAssert.m_bAssert = true; \\\n");
fprintf(incFile, "\t\t\tc_htAssert.m_module = HT_MOD_ID; \\\n");
fprintf(incFile, "\t\t\tc_htAssert.m_lineNum = __LINE__; \\\n");
fprintf(incFile, "\t\t\tc_htAssert.m_info = info;\\\n");
fprintf(incFile, "\t\t}\n");
fprintf(incFile, "#\telse\n");
fprintf(incFile, "#\t\tdefine HtAssert(expression, info) \\\n");
fprintf(incFile, "\t\tif (!(expression)) {\\\n");
fprintf(incFile, "\t\t\tfprintf(stderr, \"HtAssert: file %%s, line %%d, info 0x%%x\\n\", __FILE__, __LINE__, (int)info);\\\n");
fprintf(incFile, "\t\t\tif (Ht::g_vcdp) sc_close_vcd_trace_file(Ht::g_vcdp);\\\n");
fprintf(incFile, "\t\t\tassert(expression);\\\n");
fprintf(incFile, "\t\t\tuint32_t *pNull = 0; *pNull = 0;\\\n");
fprintf(incFile, "\t\t}\n");
fprintf(incFile, "#\t\tendif\n");
fprintf(incFile, "#else\n");
fprintf(incFile, "#\tdefine HtAssert(expression, info) assert(expression)\n");
fprintf(incFile, "#endif\n");
fprintf(incFile, "\n");
CRecord htAssert;
htAssert.AddStructField(&g_bool, "bAssert");
htAssert.AddStructField(&g_bool, "bCollision");
htAssert.AddStructField(FindHtIntType(eUnsigned, 8), "module");
htAssert.AddStructField(FindHtIntType(eUnsigned, 16), "lineNum");
htAssert.AddStructField(FindHtIntType(eUnsigned, 32), "info");
GenIntfStruct(incFile, "CHtAssert", htAssert.m_fieldList, htAssert.m_bCStyle, false, false, false);
fprintf(incFile, "#ifdef _HTV\n");
fprintf(incFile, "#define assert_msg(bCond, ...) HtAssert(bCond, 0)\n");
fprintf(incFile, "#else\n");
fprintf(incFile, "#define assert_msg(...) if (!assert_msg_(__VA_ARGS__)) assert(0)\n");
fprintf(incFile, "\n");
fprintf(incFile, "inline bool assert_msg_(bool bCond, char const * pFmt, ... ) {\n");
fprintf(incFile, "\tif (bCond) return true;\n");
fprintf(incFile, "\tva_list args;\n");
fprintf(incFile, "\tva_start( args, pFmt );\n");
fprintf(incFile, "\tvprintf(pFmt, args);\n");
fprintf(incFile, "\tif (Ht::g_vcdp) sc_close_vcd_trace_file(Ht::g_vcdp);\n");
fprintf(incFile, "\treturn false;\n");
fprintf(incFile, "}\n");
fprintf(incFile, "#endif\n");
fprintf(incFile, "\n");
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Common structs and unions\n");
fprintf(incFile, "\n");
for (size_t recordIdx = 0; recordIdx < m_recordList.size(); recordIdx += 1) {
if (m_recordList[recordIdx]->m_scope != eUnit && !m_recordList[recordIdx]->m_bInclude) continue;
//if (!m_recordList[recordIdx]->m_bNeedIntf) continue;
if (m_recordList[recordIdx]->m_bCStyle)
GenIntfStruct(incFile, m_recordList[recordIdx]->m_typeName, m_recordList[recordIdx]->m_fieldList,
m_recordList[recordIdx]->m_bCStyle, m_recordList[recordIdx]->m_bInclude,
false, m_recordList[recordIdx]->m_bUnion);
else
GenUserStructs(incFile, m_recordList[recordIdx]);
CHtCode htFile(incFile);
GenUserStructBadData(htFile, true, m_recordList[recordIdx]->m_typeName,
m_recordList[recordIdx]->m_fieldList, m_recordList[recordIdx]->m_bCStyle, "");
}
fprintf(incFile, "\n");
if (m_ngvList.size() > 0) {
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Global variable write structs\n");
fprintf(incFile, "\n");
vector<string> gvTypeList;
for (size_t gvIdx = 0; gvIdx < m_ngvList.size(); gvIdx += 1) {
CNgvInfo * pNgvInfo = m_ngvList[gvIdx];
CRam * pNgv = pNgvInfo->m_modInfoList[0].m_pNgv;
GenGlobalVarWriteTypes(incFile, pNgv->m_pType, pNgvInfo->m_atomicMask, gvTypeList, pNgv);
}
}
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Host Control interfaces\n");
fprintf(incFile, "\n");
CRecord ctrlMsgIntf;
ctrlMsgIntf.AddStructField(&g_uint64, "bValid", "1");
ctrlMsgIntf.AddStructField(&g_uint64, "msgType", "7");
ctrlMsgIntf.AddStructField(&g_uint64, "msgData", "56");
GenIntfStruct(incFile, "CHostCtrlMsg", ctrlMsgIntf.m_fieldList, false, false, true, false);
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Host Queue interfaces\n");
fprintf(incFile, "\n");
fprintf(incFile, "#define HT_DQ_NULL\t1\n");
fprintf(incFile, "#define HT_DQ_DATA\t2\n");
fprintf(incFile, "#define HT_DQ_FLSH\t3\n");
fprintf(incFile, "#define HT_DQ_CALL\t6\n");
fprintf(incFile, "#define HT_DQ_HALT\t7\n");
CRecord hostDataQue;
hostDataQue.AddStructField(FindHtIntType(eUnsigned, 64), "data");
hostDataQue.AddStructField(FindHtIntType(eUnsigned, 3), "ctl");
GenIntfStruct(incFile, "CHostDataQue", hostDataQue.m_fieldList, false, false, false, false);
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Module Queue interfaces\n");
fprintf(incFile, "\n");
for (size_t modIdx = 0; modIdx < m_modList.size(); modIdx += 1) {
CModule &mod = *m_modList[modIdx];
for (size_t queIdx = 0; queIdx < mod.m_queIntfList.size(); queIdx += 1) {
CQueIntf & queIntf = mod.m_queIntfList[queIdx];
bool bHifQue = queIntf.m_modName.Lc() == "hif" || mod.m_modName.Lc() == "hif";
if (!bHifQue) {
char queIntfName[256];
if (queIntf.m_queType == Pop)
sprintf(queIntfName, "C%sTo%s_%sIntf", queIntf.m_modName.Uc().c_str(), mod.m_modName.Uc().c_str(), queIntf.m_queName.Lc().c_str());
else
sprintf(queIntfName, "C%sTo%s_%sIntf", mod.m_modName.Uc().c_str(), queIntf.m_modName.Uc().c_str(), queIntf.m_queName.Lc().c_str());
queIntf.m_typeName = queIntfName;
} else
queIntf.m_typeName = "CHostDataQueIntf";
if (queIntf.m_queType == Push || bHifQue) continue;
GenUserStructs(incFile, &queIntf);
CHtCode htFile(incFile);
GenUserStructBadData(htFile, true, queIntf.m_typeName, queIntf.m_fieldList, queIntf.m_bCStyle, "");
}
}
fprintf(incFile, "//////////////////////////////////\n");
fprintf(incFile, "// Command interfaces\n");
fprintf(incFile, "\n");
// generate interface struct for all inbound cxr interfaces (that are non-empty)
vector<string> intfNameList;
for (size_t modIdx = 0; modIdx < m_modList.size(); modIdx += 1) {
CModule &mod = *m_modList[modIdx];
if (!mod.m_bIsUsed) continue;
for (int modInstIdx = 0; modInstIdx < mod.m_instSet.GetInstCnt(); modInstIdx += 1) {
CInstance * pModInst = mod.m_instSet.GetInst(modInstIdx);
for (size_t intfIdx = 0; intfIdx < pModInst->m_cxrIntfList.size(); intfIdx += 1) {
CCxrIntf * pCxrIntf = pModInst->m_cxrIntfList[intfIdx];
if (pCxrIntf->m_cxrDir == CxrOut) continue;
char intfName[256];
sprintf(intfName, "C%s_%s", pCxrIntf->GetSrcToDstUc(), pCxrIntf->GetIntfName());
size_t i;
for (i = 0; i < intfNameList.size(); i += 1) {
if (intfNameList[i] == intfName)
break;
}
if (i < intfNameList.size())
continue;
intfNameList.push_back(intfName);
pCxrIntf->m_fullFieldList = *pCxrIntf->m_pFieldList;
CLineInfo lineInfo;
if (pCxrIntf->m_cxrType == CxrCall) {
if (pCxrIntf->m_pSrcGroup->m_htIdW.AsInt() > 0) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pSrcGroup->m_pHtIdType, "rtnHtId"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
if (pCxrIntf->m_pSrcModInst->m_pMod->m_pInstrType) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pSrcModInst->m_pMod->m_pInstrType, "rtnInstr"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
} else if (pCxrIntf->m_cxrType == CxrTransfer) { // else Transfer
if (pCxrIntf->m_pSrcGroup->m_rtnSelW > 0) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pSrcGroup->m_pRtnSelType, "rtnSel"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
if (pCxrIntf->m_pSrcGroup->m_rtnHtIdW > 0) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pSrcGroup->m_pRtnHtIdType, "rtnHtId"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
if (pCxrIntf->m_pSrcGroup->m_rtnInstrW > 0) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pSrcGroup->m_pRtnInstrType, "rtnInstr"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
} else { // CxrReturn
if (pCxrIntf->m_pDstGroup->m_htIdW.AsInt() > 0) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pDstGroup->m_pHtIdType, "rtnHtId"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
if (pCxrIntf->m_pDstModInst->m_pMod->m_pInstrType != 0) {
pCxrIntf->m_fullFieldList.push_back(new CField(pCxrIntf->m_pDstModInst->m_pMod->m_pInstrType, "rtnInstr"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
}
if (pCxrIntf->m_bRtnJoin) {
pCxrIntf->m_fullFieldList.push_back(new CField(&g_bool, "rtnJoin"));
pCxrIntf->m_fullFieldList.back()->InitDimen(lineInfo);
}
if (pCxrIntf->m_fullFieldList.size() == 0)
continue;
GenIntfStruct(incFile, intfName, pCxrIntf->m_fullFieldList, false, false, false, false);
}
}
}
incFile.FileClose();
}
void CDsnInfo::MarkNeededIncludeStructs()
{
for (size_t recordIdx = 0; recordIdx < m_recordList.size(); recordIdx += 1) {
CRecord * pRecord = m_recordList[recordIdx];
if (pRecord->m_scope != eUnit && !pRecord->m_bInclude) continue;
if (!pRecord->m_bNeedIntf) continue;
// walk struct and see it if has embedded structures
MarkNeededIncludeStructs(pRecord);
}
}
void CDsnInfo::MarkNeededIncludeStructs(CRecord * pRecord)
{
for (size_t fieldIdx = 0; fieldIdx < pRecord->m_fieldList.size(); fieldIdx += 1) {
CField * pField = pRecord->m_fieldList[fieldIdx];
for (size_t struct2Idx = 0; struct2Idx < m_recordList.size(); struct2Idx += 1) {
CRecord * pRecord2 = m_recordList[struct2Idx];
if (pRecord2->m_typeName == pField->m_pType->m_typeName && !pRecord2->m_bNeedIntf) {
pRecord2->m_bNeedIntf = true;
MarkNeededIncludeStructs(pRecord2);
}
}
}
}
void CDsnInfo::GenGlobalVarWriteTypes(CHtFile & htFile, CType * pType, int &atomicMask, vector<string> &gvTypeList, CRam * pGv)
{
string ramTypeName = pType->m_typeName;
if (pGv) {
if (pGv->m_addr0W.AsInt() > 0)
ramTypeName += VA("_H%d", pGv->m_addr0W.AsInt());
if (pGv->m_addr1W.AsInt() > 0)
ramTypeName += VA("_%c%d", pGv->m_addr1Name == "htId" ? 'H' : 'A', pGv->m_addr1W.AsInt());
if (pGv->m_addr2W.AsInt() > 0)
ramTypeName += VA("_%c%d", pGv->m_addr2Name == "htId" ? 'H' : 'A', pGv->m_addr2W.AsInt());
pGv->m_pNgvInfo->m_ngvWrType = ramTypeName;
}
string wrTypeName = "CGW_" + ramTypeName;
switch (atomicMask) {
case ATOMIC_INC: wrTypeName += "_I"; break;
case ATOMIC_SET: wrTypeName += "_S"; break;
case ATOMIC_ADD: wrTypeName += "_A"; break;
default: break;
}
CRecord * pRecord = pType->AsRecord();
// check if type already generated
for (size_t i = 0; i < gvTypeList.size(); i += 1) {
if (gvTypeList[i] == wrTypeName) {
if (pRecord)
atomicMask |= pRecord->m_atomicMask;
return;
}
}
gvTypeList.push_back(wrTypeName);
if (pRecord) {
for (CStructElemIter iter(this, pRecord, false, false); !iter.end(); iter++) {
CField & field = iter();
CType * pFieldType = 0;
if (field.m_fieldWidth.size() > 0) {
int width;
bool bSigned;
bool bFound = FindCIntType(field.m_pType->m_typeName, width, bSigned);
HtlAssert(bFound);
pFieldType = FindHtIntType(bSigned ? eSigned : eUnsigned, field.m_fieldWidth.AsInt());
} else {
pFieldType = field.m_pType;
}
GenGlobalVarWriteTypes(htFile, pFieldType, field.m_atomicMask, gvTypeList);
pRecord->m_atomicMask |= field.m_atomicMask;
}
}
fprintf(htFile, "struct %s {\n", wrTypeName.c_str());
fprintf(htFile, "#\tifndef _HTV\n");
fprintf(htFile, "\tbool operator == (const %s & rhs) const\n", wrTypeName.c_str());
fprintf(htFile, "\t{\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\t\tif (!(m_bAddr == rhs.m_bAddr)) return false;\n");
fprintf(htFile, "\t\tif (!(m_addr == rhs.m_addr)) return false;\n");
}
if (pRecord) {
for (CStructElemIter iter(this, pRecord, false); !iter.end(); iter++) {
fprintf(htFile, "\t\tif (!(%s == rhs.%s)) return false;\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
} else {
fprintf(htFile, "\t\tif (!(m_bWrite == rhs.m_bWrite)) return false;\n");
switch (atomicMask) {
case ATOMIC_INC: fprintf(htFile, "\t\tif (!(m_bInc == rhs.m_bInc)) return false;\n"); break;
case ATOMIC_SET: fprintf(htFile, "\t\tif (!(m_bSet == rhs.m_bSet)) return false;\n"); break;
case ATOMIC_ADD: fprintf(htFile, "\t\tif (!(m_bAdd == rhs.m_bAdd)) return false;\n"); break;
default: break;
}
fprintf(htFile, "\t\tif (!(m_data == rhs.m_data)) return false;\n");
}
fprintf(htFile, "\t\treturn true;\n");
fprintf(htFile, "\t}\n");
bool bInitBAddrFalse = false;
if (pGv) {
bool bAddr1EqHtId = pGv->m_addr1Name == "htId";
bool bAddr2EqHtId = pGv->m_addr2Name == "htId";
bInitBAddrFalse = pGv->m_addr1W.size() > 0 && !bAddr1EqHtId || pGv->m_addr2W.size() > 0 && !bAddr2EqHtId;
}
if (pRecord) {
fprintf(htFile, "\tvoid operator = (int zero) {\n");
fprintf(htFile, "\t\tassert(zero == 0);\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
for (CStructElemIter iter(this, pRecord, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t%s = 0;\n", iter.GetHeirFieldName(false).c_str());
}
fprintf(htFile, "\t}\n");
}
fprintf(htFile, "#\tifdef HT_SYSC\n");
fprintf(htFile, "\tfriend void sc_trace(sc_trace_file *tf, const %s & v, const std::string & NAME)\n", wrTypeName.c_str());
fprintf(htFile, "\t{\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\t\tsc_trace(tf, v.m_bAddr, NAME + \".m_bAddr\");\n");
fprintf(htFile, "\t\tsc_trace(tf, v.m_addr, NAME + \".m_addr\");\n");
}
if (pRecord) {
for (CStructElemIter iter(this, pRecord/*->m_structName*/, false); !iter.end(); iter++) {
fprintf(htFile, "\t\tsc_trace(tf, v.%s, NAME + \".%s\");\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
} else {
fprintf(htFile, "\t\tsc_trace(tf, v.m_bWrite, NAME + \".m_bWrite\");\n");
switch (atomicMask) {
case ATOMIC_INC: fprintf(htFile, "\t\tsc_trace(tf, v.m_bInc, NAME + \".m_bInc\");\n"); break;
case ATOMIC_SET: fprintf(htFile, "\t\tsc_trace(tf, v.m_bSet, NAME + \".m_bSet\");\n"); break;
case ATOMIC_ADD: fprintf(htFile, "\t\tsc_trace(tf, v.m_bAdd, NAME + \".m_bAdd\");\n"); break;
default: break;
}
fprintf(htFile, "\t\tsc_trace(tf, v.m_data, NAME + \".m_data\");\n");
}
fprintf(htFile, "\t}\n");
fprintf(htFile, "\tfriend ostream & operator << (ostream & os, %s const & v) { return os; }\n", wrTypeName.c_str());
fprintf(htFile, "#\tendif\n");
fprintf(htFile, "#\tendif\n");
if (pRecord) {
if (pGv) {
int htIdW = 0;
if (pGv->m_addr0W.AsInt() > 0)
htIdW = pGv->m_addr0W.AsInt();
else if (pGv->m_addr1Name == "htId")
htIdW = pGv->m_addr1W.AsInt();
else if (pGv->m_addr2Name == "htId")
htIdW = pGv->m_addr2W.AsInt();
if (htIdW > 0)
fprintf(htFile, "\tvoid InitZero(ht_uint%d htId=0) {\n", htIdW);
else
fprintf(htFile, "\tvoid InitZero() {\n");
if (pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
if (htIdW > 0) {
if (pGv->m_addr0W.AsInt() > 0)
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addrW - 1, pGv->m_addrW - pGv->m_addr0W.AsInt());
if (pGv->m_addr1Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1, pGv->m_addr2W.AsInt());
if (pGv->m_addr2Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, 0) = htId;\n", pGv->m_addr2W.AsInt() - 1);
}
} else
fprintf(htFile, "\tvoid InitZero() {\n");
CHtCode htCode(htFile);
for (CStructElemIter iter(this, pRecord/*->m_structName*/, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t%s.InitZero();\n", iter.GetHeirFieldName(false).c_str());
}
fprintf(htFile, "\t}\n");
if (pGv) {
int htIdW = 0;
if (pGv->m_addr0W.AsInt() > 0)
htIdW = pGv->m_addr0W.AsInt();
else if (pGv->m_addr1Name == "htId")
htIdW = pGv->m_addr1W.AsInt();
else if (pGv->m_addr2Name == "htId")
htIdW = pGv->m_addr2W.AsInt();
if (htIdW > 0) {
fprintf(htFile, "\tvoid InitData(ht_uint%d htId, %s _data_)\n", htIdW, pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
if (pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
if (pGv->m_addr0W.AsInt() > 0)
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addrW - 1, pGv->m_addrW - pGv->m_addr0W.AsInt());
if (pGv->m_addr1Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1, pGv->m_addr2W.AsInt());
if (pGv->m_addr2Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, 0) = htId;\n", pGv->m_addr2W.AsInt() - 1);
} else {
fprintf(htFile, "\tvoid InitData(%s _data_)\n", pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
if (pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
}
for (CStructElemIter iter(this, pRecord, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t%s.InitData(_data_.%s);\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
fprintf(htFile, "\t}\n");
} else {
fprintf(htFile, "\tvoid InitData(%s _data_)\n", pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
for (CStructElemIter iter(this, pRecord, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t%s.InitData(_data_.%s);\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
fprintf(htFile, "\t}\n");
}
if (pGv) {
bool bAddr1EqHtId = pGv->m_addr1Name == "htId";
bool bAddr2EqHtId = pGv->m_addr2Name == "htId";
bool bAddr1WEq0 = pGv->m_addr1W.AsInt() == 0;
bool bAddr2WEq0 = pGv->m_addr2W.AsInt() == 0;
if (pGv->m_addr1W.size() > 0 && !bAddr1EqHtId || pGv->m_addr2W.size() > 0 && !bAddr2EqHtId) {
fprintf(htFile, "\tvoid write_addr(");
if (pGv->m_addr1W.size() > 0 && !bAddr1EqHtId)
fprintf(htFile, "ht_uint%d addr1", bAddr1WEq0 ? 1 : pGv->m_addr1W.AsInt());
if (pGv->m_addr1W.size() > 0 && !bAddr1EqHtId && pGv->m_addr2W.size() > 0 && !bAddr2EqHtId)
fprintf(htFile, ", ");
if (pGv->m_addr2W.size() > 0 && !bAddr2EqHtId)
fprintf(htFile, "ht_uint%d addr2", bAddr2WEq0 ? 1 : pGv->m_addr2W.AsInt());
fprintf(htFile, ")\n");
fprintf(htFile, "\t{\n");
if (pGv->m_addr1W.size() > 0 && bAddr1WEq0)
fprintf(htFile, "\t\tht_assert(addr1 == 0); // addr1 bounds check\n");
if (pGv->m_addr2W.size() > 0 && bAddr2WEq0)
fprintf(htFile, "\t\tht_assert(addr2 == 0); // addr2 bounds check\n");
if (pGv->m_addrW > 0) {
fprintf(htFile, "#ifndef _HTV\n");
fprintf(htFile, "\t\tsc_time t_cur = sc_time_stamp();\n");
fprintf(htFile, "\t\tif (!assert_msg_(!(m_bAddr && (t_cur.value() != 0)), \"Runtime check failed in %s.write_addr() method - write_addr() was already called on this variable\\n\")) assert(0);\n", pGv->m_gblName.c_str());
fprintf(htFile, "#endif\n");
fprintf(htFile, "\t\tm_bAddr = true;\n");
}
string bitRange = pGv->m_addr0W.AsInt() > 0 ? VA("(%d, 0)", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1) : "";
if (pGv->m_addr1W.AsInt() > 0 && !bAddr1EqHtId)
fprintf(htFile, "\t\tm_addr(%d, %d) = addr1;\n", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1, pGv->m_addr2W.AsInt());
if (pGv->m_addr2W.AsInt() > 0 && !bAddr2EqHtId)
fprintf(htFile, "\t\tm_addr(%d, 0) = addr2;\n", pGv->m_addr2W.AsInt() - 1);
fprintf(htFile, "\t}\n");
}
}
fprintf(htFile, "\tvoid operator = (%s rhs) {\n", pType->m_typeName.c_str());
for (CStructElemIter iter(this, pRecord/*->m_structName*/, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t%s = rhs.%s;\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
fprintf(htFile, "\t}\n");
fprintf(htFile, "\toperator %s () const\n", pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
fprintf(htFile, "\t\t%s _data_;\n", pType->m_typeName.c_str());
for (CStructElemIter iter(this, pRecord, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t_data_.%s = %s.GetData();\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
fprintf(htFile, "\t\treturn _data_;\n");
fprintf(htFile, "\t}\n");
fprintf(htFile, "\t%s GetData() const\n", pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
fprintf(htFile, "\t\t%s _data_;\n", pType->m_typeName.c_str());
if (pRecord->m_bUnion) {
fprintf(htFile, "\t\t_data_ = 0;\n");
for (CStructElemIter iter(this, pRecord, true); !iter.end(); iter++) {
fprintf(htFile, "\t\tif (%s.GetWrEn())\n",
iter.GetHeirFieldName(false).c_str());
fprintf(htFile, "\t\t\t_data_.%s = %s.GetData();\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
} else {
for (CStructElemIter iter(this, pRecord, false); !iter.end(); iter++) {
fprintf(htFile, "\t\t_data_.%s = %s.GetData();\n",
iter.GetHeirFieldName(false).c_str(), iter.GetHeirFieldName(false).c_str());
}
}
fprintf(htFile, "\t\treturn _data_;\n");
fprintf(htFile, "\t}\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\tbool IsAddrSet() const { return m_bAddr; }\n");
fprintf(htFile, "\tht_uint%d GetAddr() const { return m_addr; }\n", pGv->m_addrW);
}
fprintf(htFile, "public:\n");
for (CStructElemIter iter(this, pRecord, false, false); !iter.end(); iter++) {
CField & field = iter();
string fieldTypeName = "CGW_";
if (field.m_fieldWidth.size() > 0) {
int width;
bool bSigned;
bool bFound = FindCIntType(field.m_pType->m_typeName, width, bSigned);
HtlAssert(bFound);
if (bSigned)
fieldTypeName += VA("ht_int%d", field.m_fieldWidth.AsInt());
else
fieldTypeName += VA("ht_uint%d", field.m_fieldWidth.AsInt());
} else {
fieldTypeName += field.m_pType->m_typeName;
}
if (!field.m_pType->IsRecord()) {
switch (field.m_atomicMask) {
case ATOMIC_INC: fieldTypeName += "_I"; break;
case ATOMIC_SET: fieldTypeName += "_S"; break;
case ATOMIC_ADD: fieldTypeName += "_A"; break;
default: break;
}
}
fprintf(htFile, "\t%s %s%s;\n", fieldTypeName.c_str(), field.m_name.c_str(), field.m_dimenDecl.c_str());
}
fprintf(htFile, "private:\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\tbool m_bAddr;\n");
fprintf(htFile, "\tht_uint%d m_addr;\n", pGv->m_addrW);
}
} else {
if (pGv) {
int htIdW = 0;
if (pGv->m_addr0W.AsInt() > 0)
htIdW = pGv->m_addr0W.AsInt();
else if (pGv->m_addr1Name == "htId")
htIdW = pGv->m_addr1W.AsInt();
else if (pGv->m_addr2Name == "htId")
htIdW = pGv->m_addr2W.AsInt();
if (htIdW > 0) {
fprintf(htFile, "\tvoid InitZero(ht_uint%d htId=0)\n", htIdW);
fprintf(htFile, "\t{\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
if (pGv->m_addr0W.AsInt() > 0)
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addrW - 1, pGv->m_addrW - pGv->m_addr0W.AsInt());
if (pGv->m_addr1Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1, pGv->m_addr2W.AsInt());
if (pGv->m_addr2Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, 0) = htId;\n", pGv->m_addr2W.AsInt() - 1);
} else {
fprintf(htFile, "\tvoid InitZero()\n");
fprintf(htFile, "\t{\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
}
} else {
fprintf(htFile, "\tvoid InitZero()\n");
fprintf(htFile, "\t{\n");
}
fprintf(htFile, "\t\tm_bWrite = false;\n");
switch (atomicMask) {
case ATOMIC_INC: fprintf(htFile, "\t\tm_bInc = false;\n"); break;
case ATOMIC_SET: fprintf(htFile, "\t\tm_bSet = false;\n"); break;
case ATOMIC_ADD: fprintf(htFile, "\t\tm_bAdd = false;\n"); break;
default: break;
}
fprintf(htFile, "\t\tm_data = 0;\n");
fprintf(htFile, "\t}\n");
if (pGv) {
int htIdW = 0;
if (pGv->m_addr0W.AsInt() > 0)
htIdW = pGv->m_addr0W.AsInt();
else if (pGv->m_addr1Name == "htId")
htIdW = pGv->m_addr1W.AsInt();
else if (pGv->m_addr2Name == "htId")
htIdW = pGv->m_addr2W.AsInt();
if (htIdW > 0) {
fprintf(htFile, "\tvoid InitData(ht_uint%d htId, %s _data_)\n", htIdW, pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
if (pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
if (pGv->m_addr0W.AsInt() > 0)
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addrW - 1, pGv->m_addrW - pGv->m_addr0W.AsInt());
if (pGv->m_addr1Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, %d) = htId;\n", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1, pGv->m_addr2W.AsInt());
if (pGv->m_addr2Name == "htId")
fprintf(htFile, "\t\tm_addr(%d, 0) = htId;\n", pGv->m_addr2W.AsInt() - 1);
} else {
fprintf(htFile, "\tvoid InitData(%s _data_)\n", pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
if (pGv->m_addrW > 0) {
fprintf(htFile, "\t\tm_bAddr = %s;\n", bInitBAddrFalse ? "false" : "true");
fprintf(htFile, "\t\tm_addr = 0;\n");
}
}
fprintf(htFile, "\t\tm_bWrite = false;\n");
switch (atomicMask) {
case ATOMIC_INC: fprintf(htFile, "\t\tm_bInc = false;\n"); break;
case ATOMIC_SET: fprintf(htFile, "\t\tm_bSet = false;\n"); break;
case ATOMIC_ADD: fprintf(htFile, "\t\tm_bAdd = false;\n"); break;
default: break;
}
fprintf(htFile, "\t\tm_data = _data_;\n");
fprintf(htFile, "\t}\n");
} else {
fprintf(htFile, "\tvoid InitData(%s _data_)\n", pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
fprintf(htFile, "\t\tm_bWrite = false;\n");
switch (atomicMask) {
case ATOMIC_INC: fprintf(htFile, "\t\tm_bInc = false;\n"); break;
case ATOMIC_SET: fprintf(htFile, "\t\tm_bSet = false;\n"); break;
case ATOMIC_ADD: fprintf(htFile, "\t\tm_bAdd = false;\n"); break;
default: break;
}
fprintf(htFile, "\t\tm_data = _data_;\n");
fprintf(htFile, "\t}\n");
}
if (pGv && pGv->m_addr1W.AsInt() > 0) {
fprintf(htFile, "\tvoid write_addr(ht_uint%d addr1%s) {\n", pGv->m_addr1W.AsInt(),
VA(pGv->m_addr2W.AsInt() == 0 ? "" : ", ht_uint%d addr2", pGv->m_addr2W.AsInt()).c_str());
fprintf(htFile, "#ifndef _HTV\n");
fprintf(htFile, "\t\tsc_time t_cur = sc_time_stamp();\n");
fprintf(htFile, "\t\tif (!assert_msg_(!(m_bAddr && (t_cur.value() != 0)), \"Runtime check failed in %s.write_addr() method - write_addr() was already called on this variable\\n\")) assert(0);\n", pGv->m_gblName.c_str());
fprintf(htFile, "#endif\n");
fprintf(htFile, "\t\tm_bAddr = true;\n");
string bitRange = pGv->m_addr0W.AsInt() > 0 ? VA("(%d, 0)", pGv->m_addr1W.AsInt() + pGv->m_addr2W.AsInt() - 1) : "";
if (pGv->m_addr2W.AsInt() == 0)
fprintf(htFile, "\t\tm_addr%s = addr1;\n", bitRange.c_str());
else
fprintf(htFile, "\t\tm_addr%s = (addr1, addr2);\n", bitRange.c_str());
fprintf(htFile, "\t}\n");
}
char * intOpList[] = { "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", 0 };
char * booleanOpList[] = { "=", "&=", "|=", "^=", 0 };
char ** opList = pType == &g_bool ? booleanOpList : intOpList;
for (int i = 0; opList[i]; i += 1) {
fprintf(htFile, "\tvoid operator %s (%s rhs)\n", opList[i], pType->m_typeName.c_str());
fprintf(htFile, "\t{\n");
fprintf(htFile, "\t\tm_bWrite = true;\n");
fprintf(htFile, "\t\tm_data %s rhs;\n", opList[i]);
fprintf(htFile, "\t}\n");
}
if (pType->IsInt() && pType->AsInt()->m_clangMinAlign == 1) {
fprintf(htFile, "\tbool operator == (%s const &rhs) const { return m_data == rhs; }\n",
pType->m_typeName.c_str());
fprintf(htFile, "\tbool operator != (%s const &rhs) const { return m_data != rhs; }\n",
pType->m_typeName.c_str());
}
switch (atomicMask) {
case ATOMIC_INC:
fprintf(htFile, "\tvoid AtomicInc() { m_bInc = true; }\n");
fprintf(htFile, "\tbool GetIncEn() const { return m_bInc; }\n");
break;
case ATOMIC_SET:
fprintf(htFile, "\tvoid AtomicSet() { m_bSet = true; }\n");
fprintf(htFile, "\tbool GetSetEn() const { return m_bSet; }\n");
break;
case ATOMIC_ADD:
fprintf(htFile, "\tvoid AtomicAdd(%s rhs) {\n", pType->m_typeName.c_str());
fprintf(htFile, "\t\tm_bAdd = true;\n");
fprintf(htFile, "\t\tm_data = rhs;\n");
fprintf(htFile, "\t}\n");
fprintf(htFile, "\tbool GetAddEn() const { return m_bAdd; }\n");
break;
default: break;
}
fprintf(htFile, "\tbool GetWrEn() const { return m_bWrite; }\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\tbool IsAddrSet() const { return m_bAddr; }\n");
fprintf(htFile, "\tht_uint%d GetAddr() const { return m_addr; }\n", pGv->m_addrW);
}
fprintf(htFile, "\t%s GetData() const { return m_data; }\n", pType->m_typeName.c_str());
//fprintf(htFile, "\toperator %s () const { return m_data; }\n", pType->m_typeName.c_str());
if (pType->IsInt()) {
string typeName;
if (pType->AsInt()->m_clangMinAlign == 1) {
string typePrefix = pType->m_typeName.substr(0, 4);
if (typePrefix == "ht_u")
typeName = "uint64_t";
else if (typePrefix == "ht_i")
typeName = "int64_t";
else
HtlAssert(0);
fprintf(htFile, "\toperator %s () const { return m_data; }\n", typeName.c_str());
} else
typeName = pType->m_typeName;
fprintf(htFile, "\toperator %s () const { return m_data; }\n", pType->m_typeName.c_str());
}
fprintf(htFile, "private:\n");
if (pGv && pGv->m_addrW > 0) {
fprintf(htFile, "\tbool m_bAddr;\n");
fprintf(htFile, "\tht_uint%d m_addr;\n", pGv->m_addrW);
}
fprintf(htFile, "\tbool m_bWrite;\n");
switch (atomicMask) {
case ATOMIC_INC: fprintf(htFile, "\tbool m_bInc;\n"); break;
case ATOMIC_SET: fprintf(htFile, "\tbool m_bSet;\n"); break;
case ATOMIC_ADD: fprintf(htFile, "\tbool m_bAdd;\n"); break;
default: break;
}
fprintf(htFile, "\t%s m_data;\n", pType->m_typeName.c_str());
}
fprintf(htFile, "};\n");
fprintf(htFile, "\n");
if (pRecord)
atomicMask |= pRecord->m_atomicMask;
}
| 37.115702 | 225 | 0.628145 | [
"vector"
] |
c179552c4b8e7ffbbb9b28db690dabfda7df04f8 | 45,368 | cpp | C++ | src/hed/libs/common/XMLNode.cpp | davidgcameron/arc | 9813ef5f45e5089507953239de8fa2248f5ad32c | [
"Apache-2.0"
] | null | null | null | src/hed/libs/common/XMLNode.cpp | davidgcameron/arc | 9813ef5f45e5089507953239de8fa2248f5ad32c | [
"Apache-2.0"
] | null | null | null | src/hed/libs/common/XMLNode.cpp | davidgcameron/arc | 9813ef5f45e5089507953239de8fa2248f5ad32c | [
"Apache-2.0"
] | null | null | null | // -*- indent-tabs-mode: nil -*-
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <fstream>
#include <cstring>
#include "XMLNode.h"
#include "Utils.h"
namespace Arc {
// prefix == NULL means node should have no namespace
// for default namespace prefix == "" is used
static void SetName(xmlNodePtr node, const char *name, const char *prefix) {
if (!node) return;
xmlNsPtr ns = NULL;
if(prefix) {
// libxml expect empty prefix to be NULL, not empty string.
ns = xmlSearchNs(node->doc, node, (const xmlChar*)(prefix[0]?prefix:NULL));
}
// ns element is located at same place in Node and Attr elements
node->ns = ns;
xmlNodeSetName(node, (const xmlChar*)name);
}
// prefix == NULL means node should have no namespace
// for default namespace prefix == "" is used
static void SetPrefix(xmlNodePtr node, const char *prefix, int recursion) {
if (!node) return;
if ((node->type != XML_ELEMENT_NODE) && (node->type != XML_ATTRIBUTE_NODE)) return;
if(!prefix || (node->type == XML_ATTRIBUTE_NODE)) {
// Request to remove namespace or attribute - attributes have no namespaces
node->ns = NULL;
} else {
xmlNsPtr ns = xmlSearchNs(node->doc, node, (const xmlChar*)(prefix[0]?prefix:NULL));
node->ns = ns;
}
if (recursion == 0) return;
for (xmlNodePtr node_ = node->children; node_; node_ = node_->next) {
SetPrefix(node_, prefix, (recursion>0)?(recursion-1):(-1));
}
}
static xmlNsPtr GetNamespace(xmlNodePtr node) {
if (node == NULL) return NULL;
xmlNsPtr ns_ = NULL;
if (node->type == XML_ELEMENT_NODE) {
ns_ = node->ns;
} else if (node->type == XML_ATTRIBUTE_NODE) {
ns_ = ((xmlAttrPtr)node)->ns;
};
if (ns_) return ns_;
if (node->parent) return GetNamespace(node->parent);
return NULL;
}
static bool MatchXMLName(xmlNodePtr node1, xmlNodePtr node2) {
if (node1 == NULL) return false;
if (node2 == NULL) return false;
if (strcmp((char*)(node1->name), (char*)(node2->name)) != 0) return false;
if (node1->type != node2->type) return false;
if ((node1->type != XML_ELEMENT_NODE) && (node1->type != XML_ATTRIBUTE_NODE)) return true;
xmlNsPtr ns1 = GetNamespace(node1);
xmlNsPtr ns2 = GetNamespace(node2);
if (ns1 == ns2) return true;
if (ns1 && ns2) {
if(ns1->href && ns2->href) {
return (strcmp((const char*)(ns1->href),(const char*)(ns2->href)) == 0);
};
};
return false;
}
static bool MatchXMLName(xmlNodePtr node, const char *name) {
if (node == NULL) return false;
if (name == NULL) return false;
const char *name_ = strrchr(name, ':');
if (name_ == NULL) {
name_ = name;
} else {
++name_;
};
if (strcmp(name_, (char*)(node->name)) != 0) return false;
if (name_ == name) return true;
xmlNsPtr ns_ = GetNamespace(node);
std::string ns(name, name_ - name - 1);
if (ns_ == NULL) return ns.empty();
if (ns.find(':') != std::string::npos) {
// URI
if (ns_->href == NULL) return false;
return (ns == (const char*)(ns_->href));
} else {
// prefix
if (ns_->prefix == NULL) return ns.empty();
return (ns == (const char*)(ns_->prefix));
}
}
static bool MatchXMLNamespace(xmlNodePtr node1, xmlNodePtr node2) {
if (node1 == NULL) return false;
if (node2 == NULL) return false;
if (node1->type != node2->type) return false;
if ((node1->type != XML_ELEMENT_NODE) && (node1->type != XML_ATTRIBUTE_NODE))
return false;
xmlNsPtr ns1 = GetNamespace(node1);
xmlNsPtr ns2 = GetNamespace(node2);
if (ns1 == ns2) return true;
if (ns1 && ns2) {
if(ns1->href && ns2->href) {
return (strcmp((const char*)(ns1->href),(const char*)(ns2->href)) == 0);
};
};
return false;
}
static bool MatchXMLNamespace(xmlNodePtr node, const char *uri) {
if (node == NULL) return false;
if (uri == NULL) return false;
xmlNsPtr ns_ = GetNamespace(node);
if ((ns_ == NULL) || (ns_->href == NULL)) return (uri[0] == 0);
return (strcmp(uri, (const char*)(ns_->href)) == 0);
}
bool MatchXMLName(const XMLNode& node1, const XMLNode& node2) {
return MatchXMLName(node1.node_, node2.node_);
}
bool MatchXMLName(const XMLNode& node, const char *name) {
return MatchXMLName(node.node_, name);
}
bool MatchXMLName(const XMLNode& node, const std::string& name) {
return MatchXMLName(node.node_, name.c_str());
}
bool MatchXMLNamespace(const XMLNode& node1, const XMLNode& node2) {
return MatchXMLNamespace(node1.node_, node2.node_);
}
bool MatchXMLNamespace(const XMLNode& node, const char *uri) {
return MatchXMLNamespace(node.node_, uri);
}
bool MatchXMLNamespace(const XMLNode& node, const std::string& uri) {
return MatchXMLNamespace(node.node_, uri.c_str());
}
static void ReplaceNamespace(xmlNsPtr ns, xmlNodePtr node, xmlNsPtr new_ns) {
if (node->type == XML_ELEMENT_NODE) {
if (node->ns == ns)
node->ns = new_ns;
for (xmlAttrPtr node_ = node->properties; node_; node_ = node_->next)
ReplaceNamespace(ns, (xmlNodePtr)node_, new_ns);
for (xmlNodePtr node_ = node->children; node_; node_ = node_->next)
ReplaceNamespace(ns, node_, new_ns);
}
else if (node->type == XML_ATTRIBUTE_NODE) {
if (((xmlAttrPtr)node)->ns == ns)
((xmlAttrPtr)node)->ns = new_ns;
}
else
return;
}
static void ReassignNamespace(xmlNsPtr ns, xmlNodePtr node,bool keep = false,int recursion = -1) {
if(recursion >= 0) keep = true;
xmlNsPtr ns_cur = node->nsDef;
xmlNsPtr ns_prev = NULL;
for (; ns_cur;) {
if (ns == ns_cur) {
ns_prev = ns_cur;
ns_cur = ns_cur->next;
continue;
}
if (ns->href && ns_cur->href && (xmlStrcmp(ns->href, ns_cur->href) == 0)) {
ReplaceNamespace(ns_cur, node, ns);
if(!keep) {
// Unlinking namespace from tree
if (ns_prev)
ns_prev->next = ns_cur->next;
else
node->nsDef = ns_cur->next;
xmlNsPtr ns_tmp = ns_cur;
ns_cur = ns_cur->next;
xmlFreeNs(ns_tmp);
} else {
ns_cur = ns_cur->next;
}
continue;
}
ns_prev = ns_cur;
ns_cur = ns_cur->next;
}
if(recursion == 0) return;
if(recursion > 0) --recursion;
for (xmlNodePtr node_ = node->children; node_; node_ = node_->next) {
ReassignNamespace(ns, node_, keep, recursion);
}
}
// Adds new 'namespaces' to namespace definitions of 'node_'.
// The 'node_' and its children are converted to new prefixes.
// If keep == false all existing namespaces with same href
// defined in 'node_' or children are removed.
// 'recursion' limits how deep to follow children nodes. 0 for
// 'node_' only. -1 for unlimited depth. If 'recursion' is set
// to >=0 then existing namespaces always kept disregarding
// value of 'keep'. Otherwise some XML node would be left
// without valid namespaces.
static void SetNamespaces(const NS& namespaces, xmlNodePtr node_,bool keep = false,int recursion = -1) {
for (NS::const_iterator ns = namespaces.begin();
ns != namespaces.end(); ++ns) {
// First check maybe this namespace is already defined
xmlNsPtr ns_ = xmlSearchNsByHref(node_->doc, node_, (const xmlChar*)(ns->second.c_str()));
if (ns_) {
const char *prefix = (const char*)(ns_->prefix);
if (!prefix) prefix = "";
if (ns->first == prefix) {
// Same namespace with same prefix - doing nothing
}
else {
// Change to new prefix
ns_ = NULL;
}
}
if (!ns_) {
// New namespace needed
// If the namespace's name is defined then pass it to the libxml function else set the value as default namespace
ns_ = xmlNewNs(node_, (const xmlChar*)(ns->second.c_str()), ns->first.empty() ? NULL : (const xmlChar*)(ns->first.c_str()));
if (ns_ == NULL)
// There is already namespace with same prefix (or some other error)
// TODO: optional change of prefix
return;
}
// Go through all children removing same namespaces and reassigning elements to this one.
ReassignNamespace(ns_, node_, keep, recursion);
}
}
static void GetNamespaces(NS& namespaces, xmlNodePtr node_) {
if (node_ == NULL) return;
if (node_->type != XML_ELEMENT_NODE) return;
// TODO: Check for duplicate prefixes
xmlNsPtr ns = node_->nsDef;
for (; ns; ns = ns->next) {
std::string prefix = ns->prefix ? (char*)(ns->prefix) : "";
if (ns->href) {
if (namespaces[prefix].empty()) namespaces[prefix] = (char*)(ns->href);
}
}
GetNamespaces(namespaces, node_->parent);
}
// Finds all namespaces defined in XML subtree specified by node_.
static void CollectLocalNamespaces(xmlNodePtr node_, std::map<xmlNsPtr,xmlNsPtr>& localns) {
if (node_ == NULL) return;
if (node_->type != XML_ELEMENT_NODE) return;
xmlNodePtr node = node_;
for(;;) {
if(node->type == XML_ELEMENT_NODE) {
for(xmlNsPtr ns = node->nsDef; ns ; ns = ns->next) {
localns[ns] = NULL;
}
}
// 1. go down
if(node->children) {
node = node->children;
continue;
}
// 2. if impossible go next
if(node->next) {
node = node->next;
continue;
}
// 3. if impossible go up till next exists and then to next
for(;;) {
if((node == node_) || (!node)) return;
node = node->parent;
if((node == node_) || (!node)) return;
if(node->next) {
node = node->next;
break;
}
}
}
}
// Finds all namespaces referenced in XML subtree specified by node_ which
// are not defined there.
static void CollectExternalNamespaces(xmlNodePtr node_, std::map<xmlNsPtr,xmlNsPtr>& extns) {
if (node_ == NULL) return;
if (node_->type != XML_ELEMENT_NODE) return;
std::map<xmlNsPtr,xmlNsPtr> localns;
xmlNodePtr node = node_;
for(;;) {
if(node->type == XML_ELEMENT_NODE) {
for(xmlNsPtr ns = node->nsDef; ns ; ns = ns->next) {
localns[ns] = NULL;
}
// Look for refered namespaces
if(node->ns) {
if(localns.find(node->ns) == localns.end()) extns[node->ns] = NULL;
}
for(xmlAttrPtr attr = node->properties; attr ; attr = attr->next) {
if(attr->ns) {
if(localns.find(attr->ns) == localns.end()) extns[attr->ns] = NULL;
}
}
}
// 1. go down
if(node->children) {
node = node->children;
continue;
}
// 2. if impossible go next
if(node->next) {
node = node->next;
continue;
}
// 3. if impossible go up till next exists and then to next
for(;;) {
if((node == node_) || (!node)) return;
node = node->parent;
if((node == node_) || (!node)) return;
if(node->next) {
node = node->next;
break;
}
}
}
}
static void AdjustNamespace(xmlNodePtr node_, xmlNsPtr& ns, std::map<xmlNsPtr,xmlNsPtr>& localns, std::map<xmlNsPtr,xmlNsPtr>& newns) {
if(!ns) return;
if(localns.find(ns) == localns.end()) {
std::map<xmlNsPtr,xmlNsPtr>::iterator ins = newns.find(ns);
if(ins == newns.end()) {
xmlNsPtr nns = xmlNewNs(node_, ns->href, ns->prefix);
newns[ns] = nns;
ns = nns;
} else {
// already copied
ns = ins->second;
}
}
}
static void LocalizeNamespaces(xmlNodePtr node_) {
if (node_ == NULL) return;
if (node_->type != XML_ELEMENT_NODE) return;
// First collect all locally defined namespaces
std::map<xmlNsPtr,xmlNsPtr> localns;
CollectLocalNamespaces(node_,localns);
// Identify referednamespaces and make copy if
// defined externally
std::map<xmlNsPtr,xmlNsPtr> newns;
xmlNodePtr node = node_;
for(;;) {
if(node->type == XML_ELEMENT_NODE) {
AdjustNamespace(node_, node->ns, localns, newns);
for(xmlAttrPtr attr = node->properties; attr ; attr = attr->next) {
AdjustNamespace(node_, attr->ns, localns, newns);
}
}
// 1. go down
if(node->children) {
node = node->children;
continue;
}
// 2. if impossible go next
if(node->next) {
node = node->next;
continue;
}
// 3. if impossible go up till next exists and then to next
for(;;) {
if((node == node_) || (!node)) return;
node = node->parent;
if((node == node_) || (!node)) return;
if(node->next) {
node = node->next;
break;
}
}
}
}
XMLNode::XMLNode(const std::string& xml)
: node_(NULL),
is_owner_(false),
is_temporary_(false) {
//xmlDocPtr doc = xmlParseMemory((char*)(xml.c_str()), xml.length());
xmlDocPtr doc = xmlReadMemory(xml.c_str(),xml.length(),NULL,NULL,
XML_PARSE_NODICT|XML_PARSE_NOERROR|XML_PARSE_NOWARNING);
if (!doc) return;
xmlNodePtr p = doc->children;
for (; p; p = p->next) {
if (p->type == XML_ELEMENT_NODE) break;
}
if (!p) {
xmlFreeDoc(doc);
return;
}
node_ = p;
is_owner_ = true;
}
XMLNode::XMLNode(const char *xml, int len)
: node_(NULL),
is_owner_(false),
is_temporary_(false) {
if (!xml) return;
if (len == -1) len = strlen(xml);
//xmlDocPtr doc = xmlParseMemory((char*)xml, len);
xmlDocPtr doc = xmlReadMemory(xml,len,NULL,NULL,
XML_PARSE_NODICT|XML_PARSE_NOERROR|XML_PARSE_NOWARNING);
if (!doc) return;
xmlNodePtr p = doc->children;
for (; p; p = p->next) {
if (p->type == XML_ELEMENT_NODE) break;
}
if (!p) {
xmlFreeDoc(doc);
return;
}
node_ = p;
is_owner_ = true;
}
XMLNode::XMLNode(long ptr_addr)
: node_(NULL),
is_owner_(false),
is_temporary_(false) {
XMLNode *other = (XMLNode *)ptr_addr;
(*other).New((*this));
}
XMLNode::XMLNode(const NS& ns, const char *name)
: node_(NULL),
is_owner_(false),
is_temporary_(false) {
xmlDocPtr doc = xmlNewDoc((const xmlChar*)"1.0");
if (!doc) return;
if (name == NULL) name = "";
const char *name_ = strchr(name, ':');
std::string node_ns_;
if (name_ != NULL) {
node_ns_.assign(name, name_ - name);
++name_;
} else {
name_ = name;
}
xmlNodePtr new_node = xmlNewNode(NULL, (const xmlChar*)name_);
if (new_node == NULL) {
xmlFreeDoc(doc);
return;
}
xmlDocSetRootElement(doc, new_node);
node_ = new_node;
is_owner_ = true;
SetNamespaces(ns, node_);
node_->ns = xmlSearchNs(node_->doc, node_,
(const xmlChar*)(node_ns_.empty()?NULL:node_ns_.c_str()));
}
XMLNode::~XMLNode(void) {
if (is_owner_ && node_)
xmlFreeDoc(node_->doc);
}
XMLNode XMLNode::operator[](int n) const {
if (!node_)
return XMLNode();
xmlNodePtr p = n < 0 ? NULL : node_;
for (; p; p = p->next) {
if ((p->type != XML_ELEMENT_NODE) &&
(p->type != XML_ATTRIBUTE_NODE))
continue;
if (node_->name) {
if (!(p->name))
continue;
if (!MatchXMLName(node_, p))
continue;
}
if ((--n) < 0)
break;
}
return XMLNode(p);
}
XMLNode XMLNode::operator[](const char *name) const {
if (!node_)
return XMLNode();
if ((node_->type != XML_ELEMENT_NODE) &&
(node_->type != XML_ATTRIBUTE_NODE))
return XMLNode();
xmlNodePtr p = node_->children;
for (; p; p = p->next) {
if ((p->type != XML_ELEMENT_NODE) &&
(p->type != XML_ATTRIBUTE_NODE))
continue;
if (MatchXMLName(p, name))
break;
}
return XMLNode(p);
}
void XMLNode::operator++(void) {
if (!node_)
return;
if (is_owner_) { // top node has no siblings
xmlFreeDoc(node_->doc);
node_ = NULL;
is_owner_ = false;
return;
}
xmlNodePtr p = node_->next;
for (; p; p = p->next) {
if (node_->type != p->type)
continue;
if (node_->name) {
if (!(p->name))
continue;
if (!MatchXMLName(node_, p))
continue;
}
break;
}
node_ = p;
}
void XMLNode::operator--(void) {
if (!node_)
return;
if (is_owner_) { // top node has no siblings
xmlFreeDoc(node_->doc);
node_ = NULL;
is_owner_ = false;
return;
}
xmlNodePtr p = node_->prev;
for (; p; p = p->prev) {
if (node_->type != p->type)
continue;
if (node_->name) {
if (!(p->name))
continue;
if (!MatchXMLName(node_, p))
continue;
}
break;
}
node_ = p;
}
int XMLNode::Size(void) const {
if (!node_)
return 0;
int n = 0;
xmlNodePtr p = node_->children;
for (; p; p = p->next) {
if (p->type != XML_ELEMENT_NODE)
continue;
++n;
}
return n;
}
std::string XMLNode::Name(void) const {
const char *name = (node_) ? ((node_->name) ? (char*)(node_->name) : "") : "";
return std::string(name);
}
int XMLNode::AttributesSize(void) const {
if (!node_)
return 0;
if (node_->type != XML_ELEMENT_NODE)
return 0;
int n = 0;
xmlAttrPtr p = node_->properties;
for (; p; p = p->next) {
if (p->type != XML_ATTRIBUTE_NODE)
continue;
++n;
}
return n;
}
XMLNode XMLNode::Attribute(int n) {
if (!node_)
return XMLNode();
if (node_->type != XML_ELEMENT_NODE)
return XMLNode();
xmlAttrPtr p = n < 0 ? NULL : node_->properties;
for (; p; p = p->next) {
if (p->type != XML_ATTRIBUTE_NODE)
continue;
if ((--n) < 0)
break;
}
return XMLNode((xmlNodePtr)p);
}
XMLNode XMLNode::Attribute(const char *name) {
if (!node_)
return XMLNode();
if (node_->type != XML_ELEMENT_NODE)
return XMLNode();
xmlNodePtr p = (xmlNodePtr)(node_->properties);
for (; p; p = p->next) {
if (p->type != XML_ATTRIBUTE_NODE)
continue;
if (MatchXMLName(p, name))
break;
}
if (p)
return XMLNode(p);
// New temporary node
return XMLNode(p);
}
XMLNode XMLNode::NewAttribute(const char *name) {
if (!node_)
return XMLNode();
if (node_->type != XML_ELEMENT_NODE)
return XMLNode();
const char *name_ = strchr(name, ':');
xmlNsPtr ns = NULL;
if ((name_ != NULL) && (name_ != name)) {
std::string ns_(name, name_ - name);
ns = xmlSearchNs(node_->doc, node_, (const xmlChar*)(ns_.c_str()));
++name_;
} else if(name_ != NULL) {
ns = xmlSearchNs(node_->doc, node_, (const xmlChar*)NULL);
++name_;
} else {
ns = xmlSearchNs(node_->doc, node_, (const xmlChar*)NULL);
name_ = name;
}
return XMLNode((xmlNodePtr)xmlNewNsProp(node_, ns, (const xmlChar*)name_, NULL));
}
std::string XMLNode::Prefix(void) const {
if (!node_)
return "";
xmlNsPtr ns = GetNamespace(node_);
if (!ns)
return "";
if (!(ns->prefix))
return "";
return (const char*)(ns->prefix);
}
void XMLNode::Prefix(const std::string& prefix, int recursion) {
SetPrefix(node_, prefix.c_str(), recursion);
}
void XMLNode::StripNamespace(int recursion) {
SetPrefix(node_, NULL, recursion);
}
std::string XMLNode::Namespace(void) const {
if (!node_)
return "";
xmlNsPtr ns = GetNamespace(node_);
if (!ns)
return "";
if (!(ns->href))
return "";
return (const char*)(ns->href);
}
void XMLNode::Name(const char *name) {
if (!node_) return;
const char *name_ = strchr(name, ':');
xmlNsPtr ns = NULL;
if (name_ != NULL) {
std::string ns_(name, name_ - name);
SetName(node_, name_+1, ns_.c_str());
}
else {
SetName(node_, name, "");
}
}
XMLNode XMLNode::Child(int n) {
if (!node_)
return XMLNode();
if (node_->type != XML_ELEMENT_NODE)
return XMLNode();
xmlNodePtr p = n < 0 ? NULL : node_->children;
for (; p; p = p->next) {
if (p->type != XML_ELEMENT_NODE)
continue;
if ((--n) < 0)
break;
}
return XMLNode(p);
}
XMLNode::operator std::string(void) const {
std::string content;
if (!node_)
return content;
for (xmlNodePtr p = node_->children; p; p = p->next) {
if (p->type != XML_TEXT_NODE)
continue;
xmlChar *buf = xmlNodeGetContent(p);
if (!buf)
continue;
content += (char*)buf;
xmlFree(buf);
}
return content;
}
XMLNode& XMLNode::operator=(const char *content) {
if (!node_)
return *this;
if (!content)
content = "";
xmlChar *encode = xmlEncodeSpecialChars(node_->doc, (xmlChar*)content);
if (!encode)
encode = (xmlChar*)"";
xmlNodeSetContent(node_, encode);
xmlFree(encode);
return *this;
}
XMLNode XMLNode::NewChild(const char *name, const NS& namespaces, int n, bool global_order) {
XMLNode x = NewChild("", n, global_order); // placeholder
x.Namespaces(namespaces);
x.Name(name);
return x;
}
XMLNode XMLNode::NewChild(const char *name, int n, bool global_order) {
if (node_ == NULL)
return XMLNode();
if (node_->type != XML_ELEMENT_NODE)
return XMLNode();
const char *name_ = strchr(name, ':');
xmlNsPtr ns = NULL;
if ((name_ != NULL) && (name_ != name)) {
std::string ns_(name, name_ - name);
ns = xmlSearchNs(node_->doc, node_, (const xmlChar*)(ns_.c_str()));
++name_;
} else if(name_ != NULL) {
ns = xmlSearchNs(node_->doc, node_, (const xmlChar*)NULL);
++name_;
} else {
ns = xmlSearchNs(node_->doc, node_, (const xmlChar*)NULL);
name_ = name;
}
xmlNodePtr new_node = xmlNewNode(ns, (const xmlChar*)name_);
if (new_node == NULL) return XMLNode();
if (n < 0) {
return XMLNode(xmlAddChild(node_, new_node));
}
XMLNode old_node = global_order ? Child(n) : operator[](name)[n];
if (!old_node) {
// TODO: find last old_node
return XMLNode(xmlAddChild(node_, new_node));
}
if (old_node) {
return XMLNode(xmlAddPrevSibling(old_node.node_, new_node));
}
return XMLNode(xmlAddChild(node_, new_node));
}
XMLNode XMLNode::NewChild(const XMLNode& node, int n, bool global_order) {
if (node_ == NULL)
return XMLNode();
if (node.node_ == NULL)
return XMLNode();
if (node_->type != XML_ELEMENT_NODE)
return XMLNode();
// TODO: Add new attribute if 'node' is attribute
if (node.node_->type != XML_ELEMENT_NODE)
return XMLNode();
xmlNodePtr new_node = xmlDocCopyNode(node.node_, node_->doc, 1);
if (new_node == NULL)
return XMLNode();
if (n < 0)
return XMLNode(xmlAddChild(node_, new_node));
std::string name;
xmlNsPtr ns = GetNamespace(new_node);
if (ns != NULL) {
if (ns->prefix != NULL)
name = (char*)ns->prefix;
name += ":";
}
if (new_node->name)
name += (char*)(new_node->name);
XMLNode old_node = global_order ? Child(n) : operator[](name)[n];
if (!old_node)
// TODO: find last old_node
return XMLNode(xmlAddChild(node_, new_node));
if (old_node)
return XMLNode(xmlAddPrevSibling(old_node.node_, new_node));
return XMLNode(xmlAddChild(node_, new_node));
}
void XMLNode::Replace(const XMLNode& node) {
if (node_ == NULL)
return;
if (node.node_ == NULL)
return;
if (node_->type != XML_ELEMENT_NODE)
return;
if (node.node_->type != XML_ELEMENT_NODE)
return;
xmlNodePtr new_node = xmlDocCopyNode(node.node_, node_->doc, 1);
if (new_node == NULL)
return;
xmlReplaceNode(node_, new_node);
xmlFreeNode(node_);
node_ = new_node;
return;
}
void XMLNode::New(XMLNode& new_node) const {
if (new_node.is_owner_ && new_node.node_)
xmlFreeDoc(new_node.node_->doc);
new_node.is_owner_ = false;
new_node.node_ = NULL;
if (node_ == NULL)
return;
// TODO: Copy attribute node too
if (node_->type != XML_ELEMENT_NODE)
return;
xmlDocPtr doc = xmlNewDoc((const xmlChar*)"1.0");
if (doc == NULL)
return;
new_node.node_ = xmlDocCopyNode(node_, doc, 1);
if (new_node.node_ == NULL)
return;
xmlDocSetRootElement(doc, new_node.node_);
new_node.is_owner_ = true;
return;
}
void XMLNode::Move(XMLNode& node) {
if (node.is_owner_ && node.node_) xmlFreeDoc(node.node_->doc);
node.is_owner_ = false;
node.node_ = NULL;
if (node_ == NULL) return;
// TODO: Copy attribute node too
if (node_->type != XML_ELEMENT_NODE) {
return;
}
if(is_owner_) {
// Owner also means top level. So just copy and clean.
node.node_=node_;
node.is_owner_=true;
node_=NULL; is_owner_=false;
return;
}
// Otherwise unlink this node and make a new document of it
// New(node); Destroy();
xmlDocPtr doc = xmlNewDoc((const xmlChar*)"1.0");
if (doc == NULL) return;
xmlUnlinkNode(node_);
// Unlinked node still may contain references to namespaces
// defined in parent nodes. Those must be copied.
LocalizeNamespaces(node_);
node.node_ = node_; node_ = NULL;
xmlDocSetRootElement(doc, node.node_);
node.is_owner_ = true;
return;
}
void XMLNode::Swap(XMLNode& node) {
xmlNodePtr tmp_node_ = node.node_;
bool tmp_is_owner_ = node.is_owner_;
node.node_ = node_;
node.is_owner_ = is_owner_;
node_ = tmp_node_;
is_owner_ = tmp_is_owner_;
}
void XMLNode::Exchange(XMLNode& node) {
xmlNodePtr node1 = node_;
xmlNodePtr node2 = node.node_;
bool owner1 = is_owner_;
bool owner2 = node.is_owner_;
if(((node1 == NULL) || owner1) &&
((node2 == NULL) || owner2)) {
Swap(node); // ?
return;
}
if(node1 && (node1->type != XML_ELEMENT_NODE)) return;
if(node2 && (node2->type != XML_ELEMENT_NODE)) return;
node_ = NULL; node.node_ = NULL;
xmlNodePtr neighb1 = node1?(node1->next):NULL;
xmlNodePtr neighb2 = node2?(node2->next):NULL;
xmlNodePtr parent1 = node1?(node1->parent):NULL;
xmlNodePtr parent2 = node2?(node2->parent):NULL;
xmlDocPtr doc1 = node1?(node1->doc):NULL;
xmlDocPtr doc2 = node2?(node2->doc):NULL;
// In current implementation it is dangerous to move
// top level element if node is not owning document
if(node1 && (parent1 == NULL) && (!owner1)) return;
if(node2 && (parent2 == NULL) && (!owner2)) return;
if(node1) {
xmlUnlinkNode(node1);
if(doc1 != doc2) LocalizeNamespaces(node1);
}
if(node2) {
xmlUnlinkNode(node2);
if(doc1 != doc2) LocalizeNamespaces(node2);
}
if(node2) {
if(parent1) {
if(neighb1) {
xmlAddPrevSibling(neighb1,node2);
} else {
xmlAddChild(parent1,node2);
}
} else if(doc1) {
xmlDocSetRootElement(doc1,node2);
} else {
// Make document to store node
doc1 = xmlNewDoc((const xmlChar*)"1.0");
if(doc1) {
xmlDocSetRootElement(doc1,node2);
is_owner_ = true;
} else {
// Should not happen
xmlFreeNode(node2); node2 = NULL;
}
}
} else {
// Prevent memleaking document
if(doc1 && !parent1) {
xmlFreeDoc(doc1);
}
}
if(node1) {
if(parent2) {
if(neighb2) {
xmlAddPrevSibling(neighb2,node1);
} else {
xmlAddChild(parent2,node1);
}
} else if(doc2) {
xmlDocSetRootElement(doc2,node1);
} else {
// Make document to store node
doc2 = xmlNewDoc((const xmlChar*)"1.0");
if(doc2) {
xmlDocSetRootElement(doc2,node1);
node.is_owner_ = true;
} else {
// Should not happen
xmlFreeNode(node1); node1 = NULL;
}
}
} else {
// Prevent memleaking document
if(doc2 && !parent2) {
xmlFreeDoc(doc2);
}
}
node_ = node2;
node.node_ = node1;
}
void XMLNode::Namespaces(const NS& namespaces, bool keep, int recursion) {
if (node_ == NULL)
return;
if (node_->type != XML_ELEMENT_NODE)
return;
SetNamespaces(namespaces, node_, keep, recursion);
}
NS XMLNode::Namespaces(void) {
NS namespaces;
if (node_ == NULL) return namespaces;
if (node_->type != XML_ELEMENT_NODE) return namespaces;
GetNamespaces(namespaces, node_);
return namespaces;
}
std::string XMLNode::NamespacePrefix(const char *urn) {
if (node_ == NULL) return "";
xmlNsPtr ns_ = xmlSearchNsByHref(node_->doc, node_, (const xmlChar*)urn);
if (!ns_) return "";
if (!(ns_->prefix)) return "";
return (char*)(ns_->prefix);
}
void XMLNode::Destroy(void) {
if (node_ == NULL)
return;
if (is_owner_) {
xmlFreeDoc(node_->doc);
node_ = NULL;
is_owner_ = false;
return;
}
if (node_->type == XML_ELEMENT_NODE) {
xmlNodePtr p = node_->prev;
if(p && (p->type == XML_TEXT_NODE)) {
xmlChar *buf = xmlNodeGetContent(p);
if (buf) {
while(*buf) {
if(!isspace(*buf)) {
p = NULL;
break;
}
++buf;
}
}
} else {
p = NULL;
}
xmlUnlinkNode(node_);
xmlFreeNode(node_);
node_ = NULL;
// Remove beautyfication text too.
if(p) {
xmlUnlinkNode(p);
xmlFreeNode(p);
}
return;
}
if (node_->type == XML_ATTRIBUTE_NODE) {
xmlRemoveProp((xmlAttrPtr)node_);
node_ = NULL;
return;
}
}
XMLNodeList XMLNode::Path(const std::string& path) {
XMLNodeList res;
std::string::size_type name_s = 0;
std::string::size_type name_e = path.find('/', name_s);
if (name_e == std::string::npos)
name_e = path.length();
res.push_back(*this);
for (;;) {
if (res.size() <= 0)
return res;
XMLNodeList::iterator node = res.begin();
std::string node_name = path.substr(name_s, name_e - name_s);
int nodes_num = res.size();
for (int n = 0; n < nodes_num; ++n) {
for (int cn = 0;; ++cn) {
XMLNode cnode = (*node).Child(cn);
if (!cnode)
break;
if (MatchXMLName(cnode, node_name))
res.push_back(cnode);
}
++node;
}
res.erase(res.begin(), node);
if (name_e >= path.length())
break;
name_s = name_e + 1;
name_e = path.find('/', name_s);
if (name_e == std::string::npos)
name_e = path.length();
}
return res;
}
XMLNodeList XMLNode::XPathLookup(const std::string& xpathExpr, const NS& nsList) {
std::list<XMLNode> retlist;
if (node_ == NULL) return retlist;
if (node_->type != XML_ELEMENT_NODE) return retlist;
xmlDocPtr doc = node_->doc;
if (doc == NULL) return retlist;
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
for (NS::const_iterator ns = nsList.begin(); ns != nsList.end(); ++ns) {
// Note: XPath in libxml does not allow default namesapces.
// So it does not matter if NULL or empty string is used. It still
// will not work. But for consistency we use NULL here.
xmlXPathRegisterNs(xpathCtx, (xmlChar*)(ns->first.empty()?NULL:ns->first.c_str()), (xmlChar*)ns->second.c_str());
}
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression((const xmlChar*)(xpathExpr.c_str()), xpathCtx);
if (xpathObj && xpathObj->nodesetval && xpathObj->nodesetval->nodeNr) {
xmlNodeSetPtr nodes = xpathObj->nodesetval;
int size = nodes->nodeNr;
for (int i = 0; i < size; ++i) {
if (nodes->nodeTab[i]->type == XML_ELEMENT_NODE) {
xmlNodePtr cur = nodes->nodeTab[i];
xmlNodePtr parent = cur;
for (; parent; parent = parent->parent)
if (parent == node_)
break;
if (parent)
retlist.push_back(XMLNode(cur));
}
}
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);
return retlist;
}
XMLNode XMLNode::GetRoot(void) {
if (node_ == NULL)
return XMLNode();
xmlDocPtr doc = node_->doc;
if (doc == NULL)
return XMLNode();
return XMLNode(doc->children);
}
XMLNode XMLNode::Parent(void) {
if (node_ == NULL)
return XMLNode();
if (node_->type == XML_ELEMENT_NODE)
return XMLNode(node_->parent);
if (node_->type == XML_ATTRIBUTE_NODE)
return XMLNode(((xmlAttrPtr)node_)->parent);
return XMLNode();
}
XMLNode& XMLNode::operator=(const XMLNode& node) {
if (is_owner_ && node_) {
xmlDocPtr doc = node_->doc;
if (doc != NULL)
xmlFreeDoc(doc);
}
node_ = node.node_;
is_owner_ = false;
is_temporary_ = node.is_temporary_;
return *this;
}
static int write_to_string(void* context,const char* buffer,int len) {
if(!context) return -1;
std::string* str = (std::string*)context;
if(len <= 0) return 0;
if(!buffer) return -1;
str->append(buffer,len);
return len;
}
static int close_string(void* context) {
if(!context) return -1;
return 0;
}
void XMLNode::GetDoc(std::string& out_xml_str, bool user_friendly) const {
out_xml_str.resize(0);
if (!node_)
return;
xmlDocPtr doc = node_->doc;
if (doc == NULL)
return;
xmlOutputBufferPtr buf =
xmlOutputBufferCreateIO(&write_to_string,&close_string,&out_xml_str,NULL);
if(buf == NULL)
return;
/*
xmlChar *buf = NULL;
int bufsize = 0;
if (user_friendly)
xmlDocDumpFormatMemory(doc, &buf, &bufsize, 1);
else
xmlDocDumpMemory(doc, &buf, &bufsize);
if (buf) {
out_xml_str = (char*)buf;
xmlFree(buf);
}
*/
// Note xmlSaveFormatFileTo/xmlSaveFileTo call xmlOutputBufferClose
if (user_friendly)
xmlSaveFormatFileTo(buf, doc, (const char*)(doc->encoding), 1);
else
xmlSaveFileTo(buf, doc, (const char*)(doc->encoding));
}
static void NamespacesToString(std::map<xmlNsPtr,xmlNsPtr>& extns, std::string& ns_str) {
for(std::map<xmlNsPtr,xmlNsPtr>::iterator ns = extns.begin(); ns != extns.end(); ++ns) {
char* prefix = (char*)(ns->first->prefix);
char* href = (char*)(ns->first->href);
if(prefix && prefix[0]) {
ns_str+=" xmlns:"; ns_str+=prefix; ns_str+="=";
} else {
ns_str+=" xmlns=";
}
ns_str+="\"";
ns_str+=(href?href:"");
ns_str+="\"";
}
}
static void InsertExternalNamespaces(std::string& out_xml_str, const std::string& ns_str) {
// Find end of first name " <node ...| <node>| <node/>
std::string::size_type p = out_xml_str.find('<'); // tag start
if(p == std::string::npos) return;
//if(p < ns_str.length()) return;
++p;
if(p >= out_xml_str.length()) return;
if(out_xml_str[p] == '?') { // <?xml...?>
p = out_xml_str.find("?>",p); // tag end
if(p == std::string::npos) return;
p+=2;
p = out_xml_str.find('<',p); //tag start
if(p == std::string::npos) return;
++p;
}
p = out_xml_str.find_first_not_of(" \t",p); // name start
if(p == std::string::npos) return;
p = out_xml_str.find_first_of(" \t>/",p); //name end
if(p == std::string::npos) return;
std::string namestr = out_xml_str.substr(ns_str.length(),p-ns_str.length());
out_xml_str.replace(0,p,namestr+ns_str);
}
void XMLNode::GetXML(std::string& out_xml_str, bool user_friendly) const {
out_xml_str.resize(0);
if (!node_) return;
if (node_->type != XML_ELEMENT_NODE) return;
xmlDocPtr doc = node_->doc;
if (doc == NULL) return;
// Printing non-root node omits namespaces defined at higher level.
// So we need to create temporary namespace definitions and place them
// at node being printed
std::map<xmlNsPtr,xmlNsPtr> extns;
CollectExternalNamespaces(node_, extns);
// It is easier to insert namespaces into final text. Hence
// allocating place for them.
std::string ns_str;
NamespacesToString(extns, ns_str);
out_xml_str.append(ns_str.length(),' ');
/*
xmlBufferPtr buf = xmlBufferCreate();
xmlNodeDump(buf, doc, node_, 0, user_friendly ? 1 : 0);
out_xml_str = (char*)(buf->content);
xmlBufferFree(buf);
*/
xmlOutputBufferPtr buf =
xmlOutputBufferCreateIO(&write_to_string,&close_string,&out_xml_str,NULL);
if(buf == NULL) return;
xmlNodeDumpOutput(buf, doc, node_, 0, user_friendly ? 1 : 0, (const char*)(doc->encoding));
xmlOutputBufferClose(buf);
// Insert external namespaces into final string using allocated space
InsertExternalNamespaces(out_xml_str, ns_str);
}
void XMLNode::GetXML(std::string& out_xml_str, const std::string& encoding, bool user_friendly) const {
out_xml_str.resize(0);
if (!node_) return;
if (node_->type != XML_ELEMENT_NODE) return;
xmlDocPtr doc = node_->doc;
if (doc == NULL) return;
xmlCharEncodingHandlerPtr handler = NULL;
handler = xmlFindCharEncodingHandler(encoding.c_str());
if (handler == NULL) return;
std::map<xmlNsPtr,xmlNsPtr> extns;
CollectExternalNamespaces(node_, extns);
std::string ns_str;
NamespacesToString(extns, ns_str);
out_xml_str.append(ns_str.length(),' ');
//xmlOutputBufferPtr buf = xmlAllocOutputBuffer(handler);
xmlOutputBufferPtr buf =
xmlOutputBufferCreateIO(&write_to_string,&close_string,&out_xml_str,NULL);
if(buf == NULL) return;
xmlNodeDumpOutput(buf, doc, node_, 0, user_friendly ? 1 : 0, encoding.c_str());
xmlOutputBufferFlush(buf);
//out_xml_str = (char*)(buf->conv ? buf->conv->content : buf->buffer->content);
xmlOutputBufferClose(buf);
InsertExternalNamespaces(out_xml_str, ns_str);
}
bool XMLNode::SaveToStream(std::ostream& out) const {
std::string s;
GetXML(s);
out << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl;
out << s;
return (bool)out;
}
bool XMLNode::SaveToFile(const std::string& file_name) const {
InterruptGuard guard;
std::ofstream out(file_name.c_str(), std::ios::out);
if (!out)
return false;
bool r = SaveToStream(out);
out.close();
return r;
}
std::ostream& operator<<(std::ostream& out, const XMLNode& node) {
node.SaveToStream(out);
return out;
}
bool XMLNode::ReadFromStream(std::istream& in) {
std::string s;
std::getline<char>(in, s, 0);
if (!in)
return false;
//xmlDocPtr doc = xmlParseMemory((char*)(s.c_str()), s.length());
xmlDocPtr doc = xmlReadMemory(s.c_str(),s.length(),NULL,NULL,
XML_PARSE_NODICT|XML_PARSE_NOERROR|XML_PARSE_NOWARNING);
if (doc == NULL)
return false;
xmlNodePtr p = doc->children;
for (; p; p = p->next)
if (p->type == XML_ELEMENT_NODE) break;
if (!p) {
xmlFreeDoc(doc);
return false;
}
if (node_ != NULL)
if (is_owner_) {
xmlFreeDoc(node_->doc);
node_ = NULL;
is_owner_ = false;
}
node_ = p;
if (node_)
is_owner_ = true;
return true;
}
bool XMLNode::ReadFromFile(const std::string& file_name) {
std::ifstream in(file_name.c_str(), std::ios::in);
if (!in)
return false;
bool r = ReadFromStream(in);
in.close();
return r;
}
std::istream& operator>>(std::istream& in, XMLNode& node) {
node.ReadFromStream(in);
return in;
}
bool XMLNode::Validate(XMLNode schema_doc, std::string &err_msg) {
if(!node_) return false;
XMLNode doc;
// Making copy of schema because it may be changed during parsing.
schema_doc.New(doc);
if((!doc.node_) || (!doc.node_->doc)) {
err_msg = "XML schema is invalid";
return false;
}
xmlSchemaParserCtxtPtr schemaParser = xmlSchemaNewDocParserCtxt(doc.node_->doc);
if (!schemaParser) {
err_msg = "Can not aquire XML schema";
return false;
}
// parse schema
xmlSchemaPtr schema = xmlSchemaParse(schemaParser);
if (!schema) {
xmlSchemaFreeParserCtxt(schemaParser);
err_msg = "Can not parse schema";
return false;
}
xmlSchemaFreeParserCtxt(schemaParser);
return Validate(schema, err_msg);
}
bool XMLNode::Validate(const std::string& schema_file, std::string &err_msg) {
if(!node_) return false;
// create parser ctxt for schema accessible on schemaPath
xmlSchemaParserCtxtPtr schemaParser = xmlSchemaNewParserCtxt(schema_file.c_str());
if (!schemaParser) {
err_msg = "Can not load schema from file "+schema_file;
return false;
}
// parse schema
xmlSchemaPtr schema = xmlSchemaParse(schemaParser);
if (!schema) {
xmlSchemaFreeParserCtxt(schemaParser);
err_msg = "Can not parse schema";
return false;
}
xmlSchemaFreeParserCtxt(schemaParser);
return Validate(schema, err_msg);
}
void XMLNode::LogError(void * ctx, const char * msg, ...) {
std::string* str = (std::string*)ctx;
va_list ap;
va_start(ap, msg);
const size_t bufsize = 256;
char* buf = new char[bufsize];
buf[0] = 0;
vsnprintf(buf, bufsize, msg, ap);
buf[bufsize-1] = 0;
//if(!str.empty()) str += ;
*str += buf;
delete[] buf;
va_end(ap);
}
bool XMLNode::Validate(xmlSchemaPtr schema, std::string &err_msg) {
if(!node_) return false;
// create schema validation context
xmlSchemaValidCtxtPtr validityCtx = xmlSchemaNewValidCtxt(schema);
if (!validityCtx) {
xmlSchemaFree(schema);
err_msg = "Can not create validation context";
return false;
}
// Set context collectors
xmlSchemaSetValidErrors(validityCtx,&LogError,&LogError,&err_msg);
// validate against schema
bool result = false;
if(node_->parent == (xmlNodePtr)node_->doc) {
result = (xmlSchemaValidateDoc(validityCtx, node_->doc) == 0);
} else {
// It lookslike a bug in libxml makes xmlSchemaValidateOneElement
// behave like xmlSchemaValidateDoc.
// So fake doc is needed
//result = (xmlSchemaValidateOneElement(validityCtx, node_) == 0);
xmlDocPtr olddoc = node_->doc;
xmlDocPtr newdoc = xmlNewDoc((const xmlChar*)"1.0");
if(newdoc) {
newdoc->children = node_;
node_->parent = (xmlNodePtr)newdoc;
node_->doc = newdoc;
result = (xmlSchemaValidateDoc(validityCtx, node_->doc) == 0);
node_->parent = (xmlNodePtr)olddoc;
node_->doc = olddoc;
newdoc->children = NULL;
xmlFreeDoc(newdoc);
}
}
// free resources and return result
xmlSchemaFreeValidCtxt(validityCtx);
xmlSchemaFree(schema);
return result;
}
XMLNodeContainer::XMLNodeContainer(void) {}
XMLNodeContainer::XMLNodeContainer(const XMLNodeContainer& container) {
operator=(container);
}
XMLNodeContainer::~XMLNodeContainer(void) {
for (std::vector<XMLNode*>::iterator n = nodes_.begin();
n != nodes_.end(); ++n)
delete *n;
}
XMLNodeContainer& XMLNodeContainer::operator=(const XMLNodeContainer& container) {
for (std::vector<XMLNode*>::iterator n = nodes_.begin();
n != nodes_.end(); ++n)
delete *n;
for (std::vector<XMLNode*>::const_iterator n = container.nodes_.begin();
n != container.nodes_.end(); ++n) {
if ((*n)->is_owner_)
AddNew(*(*n));
else
Add(*(*n));
}
return *this;
}
void XMLNodeContainer::Add(const XMLNode& node) {
XMLNode *new_node = new XMLNode(node);
nodes_.push_back(new_node);
}
void XMLNodeContainer::Add(const std::list<XMLNode>& nodes) {
for (std::list<XMLNode>::const_iterator n = nodes.begin();
n != nodes.end(); ++n)
Add(*n);
}
void XMLNodeContainer::AddNew(const XMLNode& node) {
XMLNode *new_node = new XMLNode();
node.New(*new_node);
nodes_.push_back(new_node);
}
void XMLNodeContainer::AddNew(const std::list<XMLNode>& nodes) {
for (std::list<XMLNode>::const_iterator n = nodes.begin();
n != nodes.end(); ++n)
AddNew(*n);
}
int XMLNodeContainer::Size(void) const {
return nodes_.size();
}
XMLNode XMLNodeContainer::operator[](int n) {
if (n < 0)
return XMLNode();
if (n >= nodes_.size())
return XMLNode();
return *nodes_[n];
}
std::list<XMLNode> XMLNodeContainer::Nodes(void) {
std::list<XMLNode> r;
for (std::vector<XMLNode*>::iterator n = nodes_.begin();
n != nodes_.end(); ++n)
r.push_back(**n);
return r;
}
} // namespace Arc
| 29.847368 | 137 | 0.588873 | [
"vector"
] |
c17e0d593b6f723d2ab2ca72d74d9ad7fcbb109c | 4,312 | cpp | C++ | logdevice/common/test/AppendProbeControllerTest.cpp | majra20/LogDevice | dea0df7991120d567354d7a29d832b0e10be7477 | [
"BSD-3-Clause"
] | 1,831 | 2018-09-12T15:41:52.000Z | 2022-01-05T02:38:03.000Z | logdevice/common/test/AppendProbeControllerTest.cpp | majra20/LogDevice | dea0df7991120d567354d7a29d832b0e10be7477 | [
"BSD-3-Clause"
] | 183 | 2018-09-12T16:14:59.000Z | 2021-12-07T15:49:43.000Z | logdevice/common/test/AppendProbeControllerTest.cpp | majra20/LogDevice | dea0df7991120d567354d7a29d832b0e10be7477 | [
"BSD-3-Clause"
] | 228 | 2018-09-12T15:41:51.000Z | 2022-01-05T08:12:09.000Z | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/AppendProbeController.h"
#include <chrono>
#include <folly/Random.h>
#include <gtest/gtest.h>
#include "logdevice/common/debug.h"
#include "logdevice/common/settings/Settings.h"
using namespace facebook::logdevice;
class TestAppendProbeController : public AppendProbeController {
public:
using TimePoint = AppendProbeController::TimePoint;
TestAppendProbeController(std::chrono::milliseconds recovery_interval,
std::function<TimePoint()> time_cb)
: AppendProbeController(recovery_interval), time_cb_(time_cb) {}
protected:
TimePoint now() const override {
return TimePoint(time_cb_());
}
private:
std::function<TimePoint()> time_cb_;
};
TEST(AppendProbeControllerTest, Basic) {
std::chrono::milliseconds t(0);
auto time_cb = [&]() { return TestAppendProbeController::TimePoint(t); };
TestAppendProbeController controller(std::chrono::seconds(1), time_cb);
const NodeID N1(1, 1), N2(2, 1);
const logid_t LOG_ID(1);
// No probes initially
ASSERT_FALSE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
// t=100ms: append fails
t = std::chrono::milliseconds(100);
controller.onAppendReply(N1, LOG_ID, E::SEQNOBUFS);
// t=100ms: append to N1 should probe
ASSERT_TRUE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
// t=150ms: still should probe
t = std::chrono::milliseconds(150);
ASSERT_TRUE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
// t=200ms: append succeeded, still should probe
t = std::chrono::milliseconds(200);
controller.onAppendReply(N1, LOG_ID, E::OK);
ASSERT_TRUE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
// t=400ms: failure and success should reset recovery interval
t = std::chrono::milliseconds(400);
controller.onAppendReply(N1, LOG_ID, E::SEQNOBUFS);
controller.onAppendReply(N1, LOG_ID, E::OK);
ASSERT_TRUE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
// t=1399ms: still should probe (recovery interval 1s)
t = std::chrono::milliseconds(1399);
ASSERT_TRUE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
// t=1400ms: recovery interval elapsed, stop probing
t = std::chrono::milliseconds(1400);
ASSERT_FALSE(controller.shouldProbe(N1, LOG_ID));
ASSERT_FALSE(controller.shouldProbe(N2, LOG_ID));
}
// Test that nothing crashes or locks up under stress
TEST(AppendProbeControllerTest, MultiThreadedStressTest) {
// dbg::currentLevel = dbg::Level::DEBUG;
using namespace std::chrono;
const duration<double> TEST_DURATION(0.2);
const seconds RECOVERY_INTERVAL(1);
const int NNODES = 10;
auto random_node = [] {
node_index_t node_index = folly::Random::rand32(1, NNODES + 1);
return NodeID(node_index, 1);
};
const int NTHREADS = 16;
std::atomic<int> time_ms(0);
auto time_cb = [&]() {
// Advance time occasionally
if (folly::Random::oneIn(10000)) {
time_ms += duration_cast<milliseconds>(RECOVERY_INTERVAL).count();
} else if (folly::Random::oneIn(100)) {
++time_ms;
}
return TestAppendProbeController::TimePoint(milliseconds(time_ms.load()));
};
TestAppendProbeController controller(RECOVERY_INTERVAL, time_cb);
const auto deadline = steady_clock::now() + TEST_DURATION;
auto client_thread_fn = [&]() {
for (int64_t i = 0;; ++i) {
if (i % 1024 == 0 && steady_clock::now() >= deadline) {
fprintf(stderr, "Client thread exiting after %ld calls\n", i);
break;
}
bool failure = folly::Random::oneIn(100);
controller.onAppendReply(
random_node(), logid_t(1), failure ? E::SEQNOBUFS : E::OK);
controller.shouldProbe(random_node(), logid_t(1));
}
};
std::vector<std::thread> threads;
while (threads.size() < NTHREADS) {
threads.emplace_back(client_thread_fn);
}
for (auto& th : threads) {
th.join();
}
}
| 33.426357 | 78 | 0.705241 | [
"vector"
] |
c17f0ce66d4964fc7832af14e719c7d2ba024148 | 3,700 | cc | C++ | 2019/day10.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | 2019/day10.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | 2019/day10.cc | triglav/advent_of_code | e96bd0aea417076d997eeb4e49bf6e1cc04b31e0 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <map>
#include <vector>
using Map = std::vector<bool>;
int width = 0;
int height = 0;
inline int index(int x, int y) { return y * width + x; }
bool ReadMapRow(Map *map) {
std::string row;
if (!std::getline(std::cin, row)) {
return false;
}
for (auto c : row) {
map->push_back(c == '#');
}
return true;
}
float CalculateAngle(int const ax, int const ay, int const x, int const y) {
auto const v0_x = 0;
auto const v0_y = -1;
auto const v1_x = x - ax;
auto const v1_y = y - ay;
auto angle = std::atan2(v1_y, v1_x) - std::atan2(v0_y, v0_x);
while (angle < 0) {
angle += 2 * M_PI;
}
while (angle >= 2 * M_PI) {
angle -= 2 * M_PI;
}
return angle;
}
std::map<float, int> Check2(Map const &map, int const ax, int const ay) {
Map hit_map(width * height, false);
hit_map[index(ax, ay)] = true;
std::map<float, int> r;
for (int i = 1; i < height + width; ++i) {
auto const min_y = std::max(0, ay - i);
auto const max_y = std::min(height, ay + i);
for (int y = min_y; y < max_y; ++y) {
auto const min_x = std::max(0, ax - i);
auto const max_x = std::min(width, ax + i);
for (int x = min_x; x < max_x; ++x) {
if (hit_map[index(x, y)]) {
continue;
}
auto const dx = x - ax;
auto const dy = y - ay;
int shadow = 0;
int k = 1;
while (true) {
auto const x2 = ax + dx * k;
auto const y2 = ay + dy * k;
if (x2 < 0 || x2 >= width || y2 < 0 || y2 >= height) {
break;
}
auto const idx = index(x2, y2);
hit_map[idx] = true;
if (map[idx]) {
auto const a = CalculateAngle(ax, ay, x2, y2);
auto const v = x2 * 100 + y2;
r.emplace(a + M_PI * 2 * shadow++, v);
}
++k;
}
}
}
}
return r;
}
int Check(Map const &map, int const ax, int const ay) {
Map hit_map(width * height, false);
hit_map[index(ax, ay)] = true;
int asteroid_count = 0;
for (int i = 1; i < height + width; ++i) {
auto const min_y = std::max(0, ay - i);
auto const max_y = std::min(height, ay + i);
for (int y = min_y; y < max_y; ++y) {
auto const min_x = std::max(0, ax - i);
auto const max_x = std::min(width, ax + i);
for (int x = min_x; x < max_x; ++x) {
if (hit_map[index(x, y)]) {
continue;
}
auto const dx = x - ax;
auto const dy = y - ay;
bool shadow = false;
int k = 1;
while (true) {
auto const x2 = ax + dx * k;
auto const y2 = ay + dy * k;
if (x2 < 0 || x2 >= width || y2 < 0 || y2 >= height) {
break;
}
auto const idx = index(x2, y2);
hit_map[idx] = true;
if (!shadow && map[idx]) {
++asteroid_count;
shadow = true;
}
++k;
}
}
}
}
return asteroid_count;
}
int main() {
Map map;
ReadMapRow(&map);
width = map.size();
while (ReadMapRow(&map)) {
// nope
}
height = map.size() / width;
int max_x, max_y;
int max_asteroids = 0;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
if (!map[index(x, y)]) {
continue;
}
auto const z = Check(map, x, y);
if (z > max_asteroids) {
max_asteroids = z;
max_x = x;
max_y = y;
}
}
}
std::cout << max_asteroids << "\n";
auto const asteroids = Check2(map, max_x, max_y);
auto it = asteroids.cbegin();
std::advance(it, 199);
std::cout << it->second << "\n";
return 0;
}
| 24.025974 | 76 | 0.489459 | [
"vector"
] |
c18306e1ea059d025271ec1003eb53b59156ca10 | 4,536 | hpp | C++ | Contrib-Intel/RSD-PSME-RMM/application/include/psme/rest/constants/constants_templates.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/application/include/psme/rest/constants/constants_templates.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/application/include/psme/rest/constants/constants_templates.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2018-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file constants_templates.hpp
*
* @brief Definition of resource's IDs as templates of the resource type.
* */
#pragma once
#include "constants.hpp"
#include "agent-framework/module/model/model_chassis.hpp"
#include "agent-framework/module/model/model_common.hpp"
#include "agent-framework/module/model/model_storage.hpp"
#include "agent-framework/module/model/model_compute.hpp"
#include "agent-framework/module/model/model_network.hpp"
#include "agent-framework/module/model/model_pnc.hpp"
#include <type_traits>
namespace psme {
namespace rest {
namespace constants {
template<typename T>
constexpr const char* RESOURCE_ID = "";
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Memory> = PathParam::MEMORY_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::System> = PathParam::SYSTEM_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Volume> = PathParam::VOLUME_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Chassis> = PathParam::CHASSIS_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Drive> = PathParam::DRIVE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Acl> = PathParam::ACL_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::EthernetSwitch> = PathParam::ETHERNET_SWITCH_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::EthernetSwitchPort> = PathParam::SWITCH_PORT_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::EthernetSwitchPortVlan> = PathParam::VLAN_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::AclRule> = PathParam::RULE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::StaticMac> = PathParam::STATIC_MAC_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Endpoint> = PathParam::ENDPOINT_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::StorageService> = PathParam::SERVICE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::StorageSubsystem> = PathParam::STORAGE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Manager> = PathParam::MANAGER_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::NetworkInterface> = PathParam::NIC_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Fabric> = PathParam::FABRIC_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Switch> = PathParam::SWITCH_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Port> = PathParam::PORT_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Zone> = PathParam::ZONE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::StoragePool> = PathParam::STORAGE_POOL_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::NetworkDevice> = PathParam::NETWORK_INTERFACE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Task> = PathParam::TASK_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::NetworkDeviceFunction> = PathParam::NETWORK_DEVICE_FUNCTION_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::MetricDefinition> = PathParam::METRIC_DEFINITION_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::Processor> = PathParam::PROCESSOR_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::PcieDevice> = PathParam::DEVICE_ID;
template<>
constexpr const char* RESOURCE_ID<agent_framework::model::PcieFunction> = PathParam::FUNCTION_ID;
template <typename T>
constexpr const char* get_resource_id() {
static_assert(RESOURCE_ID<T> != nullptr, "RESOURCE_ID<T> for T template type is not defined.");
return RESOURCE_ID<T>;
}
}
}
}
| 32.4 | 121 | 0.786155 | [
"model"
] |
c18e3600f620dbe21af9047306acde6c05be3d23 | 1,373 | hpp | C++ | core/src/api/CosmosLikeMultiSendInput.hpp | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 92 | 2016-11-13T01:28:34.000Z | 2022-03-25T01:11:37.000Z | core/src/api/CosmosLikeMultiSendInput.hpp | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 242 | 2016-11-28T11:13:09.000Z | 2022-03-04T13:02:53.000Z | core/src/api/CosmosLikeMultiSendInput.hpp | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 91 | 2017-06-20T10:35:28.000Z | 2022-03-09T14:15:40.000Z | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from messages.djinni
#ifndef DJINNI_GENERATED_COSMOSLIKEMULTISENDINPUT_HPP
#define DJINNI_GENERATED_COSMOSLIKEMULTISENDINPUT_HPP
#include "CosmosLikeAmount.hpp"
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace ledger { namespace core { namespace api {
struct CosmosLikeMultiSendInput final {
std::string fromAddress;
std::vector<CosmosLikeAmount> coins;
CosmosLikeMultiSendInput(std::string fromAddress_,
std::vector<CosmosLikeAmount> coins_)
: fromAddress(std::move(fromAddress_))
, coins(std::move(coins_))
{}
CosmosLikeMultiSendInput(const CosmosLikeMultiSendInput& cpy) {
this->fromAddress = cpy.fromAddress;
this->coins = cpy.coins;
}
CosmosLikeMultiSendInput() = default;
CosmosLikeMultiSendInput& operator=(const CosmosLikeMultiSendInput& cpy) {
this->fromAddress = cpy.fromAddress;
this->coins = cpy.coins;
return *this;
}
template <class Archive>
void load(Archive& archive) {
archive(fromAddress, coins);
}
template <class Archive>
void save(Archive& archive) const {
archive(fromAddress, coins);
}
};
} } } // namespace ledger::core::api
#endif //DJINNI_GENERATED_COSMOSLIKEMULTISENDINPUT_HPP
| 26.403846 | 78 | 0.701384 | [
"vector"
] |
c19247e7b9810d1a55734794686e9addaa61adfd | 1,207 | cpp | C++ | sdk/rms_sdk/Consent/ServiceUrlConsent.cpp | AzureAD/rms-sdk-for-cpp | 0e5d54a030008c5c0f70d8d3d0695fa0722b6ab6 | [
"MIT"
] | 30 | 2015-06-22T23:59:02.000Z | 2021-09-12T05:51:34.000Z | sdk/rms_sdk/Consent/ServiceUrlConsent.cpp | AnthonyCSheehy/rms-sdk-for-cpp | 42985c0b5d93da5bef6bd6c847ddced4be008843 | [
"MIT"
] | 115 | 2015-06-22T18:26:34.000Z | 2022-03-24T16:57:46.000Z | sdk/rms_sdk/Consent/ServiceUrlConsent.cpp | AnthonyCSheehy/rms-sdk-for-cpp | 42985c0b5d93da5bef6bd6c847ddced4be008843 | [
"MIT"
] | 32 | 2015-06-22T08:39:29.000Z | 2022-03-24T16:49:20.000Z | /*
* ======================================================================
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the MIT License.
* See LICENSE.md in the project root for license information.
* ======================================================================
*/
#include "ServiceUrlConsent.h"
#include "../ModernAPI/ConsentType.h"
namespace rmscore { namespace consent {
ServiceUrlConsent::ServiceUrlConsent(const std::string& email, const std::vector<std::string> &urls)
{
for_each(
urls.begin(), urls.end(),
[&](std::string url)
{
auto urlProtocolLength = url.length();
if (urlProtocolLength > 4) urlProtocolLength = 4;
std::string urlProtocol = url.substr(0, urlProtocolLength);
std::transform(urlProtocol.begin(), urlProtocol.end(),
urlProtocol.begin(), tolower);
if (urlProtocol.compare("http") != 0) url.insert(0, "https://");
this->urls_.push_back(url);
});
this->user_ = email;
this->type_ = modernapi::ConsentType::ServiceUrlConsent;
}
} // namespace consent
} // namespace rmscore
| 30.175 | 100 | 0.550124 | [
"vector",
"transform"
] |
c194888d83e9529191950dbec217a6e342574a43 | 17,790 | cpp | C++ | dyros_jet_controller/src/control_base.cpp | DonghyunSung-MS/dyros_jet_avatar | 32d04a2bfd55ad5d95cac09fbaa67799dab68fc8 | [
"BSD-2-Clause"
] | 1 | 2021-04-09T01:17:43.000Z | 2021-04-09T01:17:43.000Z | dyros_jet_controller/src/control_base.cpp | DonghyunSung-MS/dyros_jet_avatar | 32d04a2bfd55ad5d95cac09fbaa67799dab68fc8 | [
"BSD-2-Clause"
] | null | null | null | dyros_jet_controller/src/control_base.cpp | DonghyunSung-MS/dyros_jet_avatar | 32d04a2bfd55ad5d95cac09fbaa67799dab68fc8 | [
"BSD-2-Clause"
] | null | null | null |
#include "dyros_jet_controller/control_base.h"
namespace dyros_jet_controller
{
// Constructor
ControlBase::ControlBase(ros::NodeHandle &nh, double Hz) :
ui_update_count_(0), is_first_boot_(true), Hz_(Hz), control_mask_{}, total_dof_(DyrosJetModel::HW_TOTAL_DOF),
shutdown_flag_(false),
joint_controller_(q_, q_dot_filtered_, control_time_),
task_controller_(model_, q_, q_dot_filtered_, Hz, control_time_),
haptic_controller_(model_,q_,Hz, control_time_),
walking_controller_(model_, q_, q_dot_filtered_, Hz, control_time_),
moveit_controller_(model_, q_, Hz),
joint_control_as_(nh, "/dyros_jet/joint_control", false), // boost::bind(&ControlBase::jointControlActionCallback, this, _1), false
retarget_controller_(nh, model_, q_, q_dot_filtered_, Hz, control_time_)
{
//walking_cmd_sub_ = nh.subscribe
makeIDInverseList();
//joint_control_as_
joint_control_as_.start();
joint_state_pub_.init(nh, "/dyros_jet/joint_state", 3);
joint_state_pub_.msg_.name.resize(DyrosJetModel::HW_TOTAL_DOF);
joint_state_pub_.msg_.angle.resize(DyrosJetModel::HW_TOTAL_DOF);
joint_state_pub_.msg_.velocity.resize(DyrosJetModel::HW_TOTAL_DOF);
joint_state_pub_.msg_.current.resize(DyrosJetModel::HW_TOTAL_DOF);
joint_state_pub_.msg_.error.resize(DyrosJetModel::HW_TOTAL_DOF);
joint_robot_state_pub_.init(nh, "/joint_states", 3);
joint_robot_state_pub_.msg_.name.resize(DyrosJetModel::HW_TOTAL_DOF-4);
joint_robot_state_pub_.msg_.position.resize(DyrosJetModel::HW_TOTAL_DOF-4);
//joint_robot_state_pub_.msg_.velocity.resize(DyrosJetModel::HW_TOTAL_DOF-4);
//joint_robot_state_pub_.msg_.effort.resize(DyrosJetModel::HW_TOTAL_DOF-4);
for (int i=0; i< DyrosJetModel::HW_TOTAL_DOF; i++)
{
joint_state_pub_.msg_.name[i] = DyrosJetModel::JOINT_NAME[i];
}
for (int i=0; i< DyrosJetModel::HW_TOTAL_DOF-4; i++)
{
joint_robot_state_pub_.msg_.name[i] = DyrosJetModel::JOINT_NAME[i];
}
smach_pub_.init(nh, "/dyros_jet/smach/transition", 1);
walkingstate_command_pub_ = nh.advertise<std_msgs::Bool>("/dyros_jet/walking_state",1);
smach_sub_ = nh.subscribe("/dyros_jet/smach/container_status", 3, &ControlBase::smachCallback, this);
task_comamnd_sub_ = nh.subscribe("/dyros_jet/task_command", 3, &ControlBase::taskCommandCallback, this);
haptic_command_sub_ = nh.subscribe("/dyros_jet/haptic_command", 3, &ControlBase::hapticCommandCallback, this);
joint_command_sub_ = nh.subscribe("/dyros_jet/joint_command", 3, &ControlBase::jointCommandCallback, this);
walking_command_sub_ = nh.subscribe("/dyros_jet/walking_command",3, &ControlBase::walkingCommandCallback,this);
shutdown_command_sub_ = nh.subscribe("/dyros_jet/shutdown_command", 1, &ControlBase::shutdownCommandCallback,this);
//retarget subscriber
hmd_posture_sub = nh.subscribe("/HMD", 100, &ControlBase::HmdCallback, this);
lhand_tracker_posture_sub = nh.subscribe("/TRACKER3", 100, &ControlBase::LeftHandTrackerCallback, this);
rhand_tracker_posture_sub = nh.subscribe("/TRACKER5", 100, &ControlBase::RightHandTrackerCallback, this);
lelbow_tracker_posture_sub = nh.subscribe("/TRACKER2", 100, &ControlBase::LeftElbowTrackerCallback, this);
relbow_tracker_posture_sub = nh.subscribe("/TRACKER4", 100, &ControlBase::RightElbowTrackerCallback, this);
chest_tracker_posture_sub = nh.subscribe("/TRACKER1", 100, &ControlBase::ChestTrackerCallback, this);
pelvis_tracker_posture_sub = nh.subscribe("/TRACKER0", 100, &ControlBase::PelvisTrackerCallback, this);
tracker_status_sub = nh.subscribe("/TRACKERSTATUS", 100, &ControlBase::TrackerStatusCallback, this);
vive_tracker_pose_calibration_sub = nh.subscribe("/CALIBMODE", 100, &ControlBase::PoseCalibrationCallback, this);
parameterInitialize();
model_.test();
}
bool ControlBase::checkStateChanged()
{
if(previous_state_ != current_state_)
{
previous_state_ = current_state_;
return true;
}
return false;
}
void ControlBase::makeIDInverseList()
{
for(int i=0;i<DyrosJetModel::HW_TOTAL_DOF; i++)
{
joint_id_[i] = DyrosJetModel::JOINT_ID[i];
joint_id_inversed_[DyrosJetModel::JOINT_ID[i]] = i;
}
}
void ControlBase::update()
{
if(extencoder_init_flag_ == false && q_ext_.transpose()*q_ext_ !=0 && q_.transpose()*q_ !=0)
{
for (int i=0; i<12; i++)
extencoder_offset_(i) = q_(i)-q_ext_(i);
//extencoder_offset_(i) = 0;
//cout<<"extencoder_offset_"<<extencoder_offset_<<endl;
//cout<<"q_ext_"<<q_ext_<<endl;
//cout<<"q_"<<q_<<endl;
extencoder_init_flag_ = true;
}
if(extencoder_init_flag_ == true)
{
q_ext_offset_ = q_ext_ + extencoder_offset_;
}
DyrosMath::toEulerAngle(imu_data_.x(), imu_data_.y(), imu_data_.z(), imu_data_.w(), imu_grav_rpy_(0), imu_grav_rpy_(1), imu_grav_rpy_(2));
model_.updateSensorData(right_foot_ft_, left_foot_ft_, q_ext_offset_, accelometer_, gyro_, imu_grav_rpy_);
Eigen::Matrix<double, DyrosJetModel::MODEL_WITH_VIRTUAL_DOF, 1> q_vjoint, q_vjoint_dot;
q_vjoint.setZero();
q_vjoint_dot.setZero();
q_vjoint.segment<DyrosJetModel::MODEL_DOF>(6) = q_.head<DyrosJetModel::MODEL_DOF>();
q_dot_filtered_ = q_dot_;//DyrosMath::lowPassFilter<DyrosJetModel::HW_TOTAL_DOF>(q_dot_, q_dot_filtered_, 1.0 / Hz_, 0.05);
q_vjoint_dot.segment<DyrosJetModel::MODEL_DOF>(6) = q_dot_filtered_.head<DyrosJetModel::MODEL_DOF>();
//q_vjoint.segment<12>(6) = q_ext_offset_;
//q_vjoint.segment<12>(6) = WalkingController::desired_q_not_compensated_;
model_.updateKinematics(q_vjoint, q_vjoint_dot); // Update end effector positions and Jacobians
stateChangeEvent();
}
void ControlBase::stateChangeEvent()
{
if(checkStateChanged())
{
if(current_state_ == "move1")
{
/*
task_controller_.setEnable(DyrosJetModel::EE_LEFT_HAND, true);
task_controller_.setEnable(DyrosJetModel::EE_RIGHT_HAND, false);
task_controller_.setEnable(DyrosJetModel::EE_LEFT_FOOT, false);
task_controller_.setEnable(DyrosJetModel::EE_RIGHT_FOOT, false);
Eigen::Isometry3d target;
target.linear() = Eigen::Matrix3d::Identity();
target.translation() << 1.0, 0.0, 1.0;
task_controller_.setTarget(DyrosJetModel::EE_LEFT_HAND, target, 5.0);
*/
}
}
}
void ControlBase::compute()
{
task_controller_.compute();
haptic_controller_.compute();
joint_controller_.compute();
walking_controller_.compute();
moveit_controller_.compute();
retarget_controller_.compute();
task_controller_.updateControlMask(control_mask_);
haptic_controller_.updateControlMask(control_mask_);
joint_controller_.updateControlMask(control_mask_);
walking_controller_.updateControlMask(control_mask_);
moveit_controller_.updateControlMask(control_mask_);
// retarget_controller_.updateControlMask(control_mask_);
task_controller_.writeDesired(control_mask_, desired_q_);
haptic_controller_.writeDesired(control_mask_, desired_q_);
joint_controller_.writeDesired(control_mask_, desired_q_);
walking_controller_.writeDesired(control_mask_, desired_q_);
moveit_controller_.writeDesired(control_mask_, desired_q_);
retarget_controller_.writeDesired(control_mask_, desired_q_);
tick_ ++;
control_time_ = tick_ / Hz_;
//cout << "current_q_ext" << q_ext_ <<endl;
/*
if ((tick_ % 200) == 0 )
{
ROS_INFO ("1 sec, %lf sec", control_time_);
}
*/
}
void ControlBase::reflect()
{
dyros_jet_msgs::WalkingState msg;
joint_robot_state_pub_.msg_.header.stamp = ros::Time::now();
for (int i=0; i<DyrosJetModel::HW_TOTAL_DOF; i++)
{
joint_state_pub_.msg_.angle[i] = q_(i);
joint_state_pub_.msg_.velocity[i] = q_dot_(i);
joint_state_pub_.msg_.current[i] = torque_(i);
}
for (int i=0; i<DyrosJetModel::HW_TOTAL_DOF - 4; i++)
{
joint_robot_state_pub_.msg_.position[i] = q_(i);
//joint_robot_state_pub_.msg_.velocity[i] = q_dot_(i);
//joint_robot_state_pub_.msg_.effort[i] = torque_(i);
}
if(joint_state_pub_.trylock())
{
joint_state_pub_.unlockAndPublish();
}
if(joint_robot_state_pub_.trylock())
{
joint_robot_state_pub_.unlockAndPublish();
}
if(joint_control_as_.isActive())
{
bool all_disabled = true;
for (int i=0; i<DyrosJetModel::HW_TOTAL_DOF; i++)
{
if (joint_controller_.isEnabled(i))
{
all_disabled = false;
}
}
if (all_disabled)
{
joint_control_result_.is_reached = true;
joint_control_as_.setSucceeded(joint_control_result_);
}
}
if (walking_controller_.walking_state_send == true)
{
walkingState_msg.data = walking_controller_.walking_end_;
walkingstate_command_pub_.publish(walkingState_msg);
}
}
void ControlBase::parameterInitialize()
{
q_.setZero();
q_dot_.setZero();
q_dot_filtered_.setZero();
torque_.setZero();
left_foot_ft_.setZero();
left_foot_ft_.setZero();
desired_q_.setZero();
extencoder_init_flag_ = false;
}
void ControlBase::readDevice()
{
ros::spinOnce();
// Action
if (joint_control_as_.isNewGoalAvailable())
{
jointControlActionCallback(joint_control_as_.acceptNewGoal());
}
}
void ControlBase::smachCallback(const smach_msgs::SmachContainerStatusConstPtr& msg)
{
current_state_ = msg->active_states[0];
}
void ControlBase::taskCommandCallback(const dyros_jet_msgs::TaskCommandConstPtr& msg)
{
for(unsigned int i=0; i<4; i++)
{
if(msg->end_effector[i])
{
Eigen::Isometry3d target;
tf::poseMsgToEigen(msg->pose[i], target);
if(msg->mode[i] == dyros_jet_msgs::TaskCommand::RELATIVE)
{
const auto ¤t = model_.getCurrentTransform((DyrosJetModel::EndEffector)i);
target.translation() = target.translation() + current.translation();
target.linear() = current.linear() * target.linear();
}
task_controller_.setTarget((DyrosJetModel::EndEffector)i, target, msg->duration[i]);
task_controller_.setEnable((DyrosJetModel::EndEffector)i, true);
}
}
}
void ControlBase::hapticCommandCallback(const dyros_jet_msgs::TaskCommandConstPtr& msg)
{
for(unsigned int i=2; i<4; i++)
{
if(msg->end_effector[i])
{
Eigen::Isometry3d target;
tf::poseMsgToEigen(msg->pose[i], target);
if(msg->mode[i] == dyros_jet_msgs::TaskCommand::ABSOLUTE)
{
const auto ¤t = model_.getCurrentTransform((DyrosJetModel::EndEffector)i);
target.translation() = target.translation() + current.translation();
target.linear() = current.linear() * target.linear();
}
if(msg->mode[i] == dyros_jet_msgs::TaskCommand::RELATIVE)
{
const auto ¤t = model_.getCurrentTransform((DyrosJetModel::EndEffector)i);
target.translation() = current.linear()*target.translation() + current.translation();
target.linear() = current.linear() * target.linear();
}
if(msg->end_effector[i])
{
haptic_controller_.setTarget((DyrosJetModel::EndEffector)i, target, msg->duration[i]);
haptic_controller_.setEnable((DyrosJetModel::EndEffector)i, true);
if (i==2)
haptic_controller_.setEnable((DyrosJetModel::EndEffector)3, false);
else
haptic_controller_.setEnable((DyrosJetModel::EndEffector)2, false);
}
}
}
}
void ControlBase::jointCommandCallback(const dyros_jet_msgs::JointCommandConstPtr& msg)
{
for (unsigned int i=0; i<msg->name.size(); i++)
{
if(model_.isPossibleIndex(msg->name[i]))
{
joint_controller_.setTarget(model_.getIndex(msg->name[i]), msg->position[i], msg->duration[i]);
joint_controller_.setEnable(model_.getIndex(msg->name[i]), true);
}
}
}
void ControlBase::walkingCommandCallback(const dyros_jet_msgs::WalkingCommandConstPtr& msg)
{
vector<bool> compensate_v;
compensate_v.reserve(2);
for (int i =0; i<2; i++)
{
compensate_v[i]=msg->compensator_mode[i];
}
if(msg->walk_mode == dyros_jet_msgs::WalkingCommand::STATIC_WALKING)
{
walking_controller_.setEnable(true);
walking_controller_.setTarget(msg->walk_mode, msg->compensator_mode[0], msg->compensator_mode[1], msg->ik_mode, msg->heel_toe, msg->first_foot_step,
msg->x, msg->y, msg->z, msg->height, msg->theta, msg-> step_length_x, msg-> step_length_y, msg->walking_pattern);
}
else
{
walking_controller_.setEnable(false);
}
}
void ControlBase::shutdownCommandCallback(const std_msgs::StringConstPtr &msg)
{
if (msg->data == "Shut up, JET.")
{
shutdown_flag_ = true;
}
}
void ControlBase::jointControlActionCallback(const dyros_jet_msgs::JointControlGoalConstPtr &goal)
{
for (unsigned int i=0; i<goal->command.name.size(); i++)
{
if(model_.isPossibleIndex(goal->command.name[i]))
{
joint_controller_.setTarget(model_.getIndex(goal->command.name[i]), goal->command.position[i], goal->command.duration[i]);
joint_controller_.setEnable(model_.getIndex(goal->command.name[i]), true);
}
}
joint_control_feedback_.percent_complete = 0.0;
}
void ControlBase::LeftHandTrackerCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_lhand_pose_raw_;
hmd_lhand_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_lhand_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_lhand_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_lhand_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_lhand_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_lhand_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setTrackerTarget(hmd_lhand_pose_raw_, 3);
}
void ControlBase::RightHandTrackerCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_rhand_pose_raw_;
hmd_rhand_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_rhand_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_rhand_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_rhand_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_rhand_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_rhand_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setTrackerTarget(hmd_rhand_pose_raw_, 5);
}
void ControlBase::LeftElbowTrackerCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_lupperarm_pose_raw_;
hmd_lupperarm_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_lupperarm_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_lupperarm_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_lupperarm_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_lupperarm_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_lupperarm_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setTrackerTarget(hmd_lupperarm_pose_raw_, 2);
}
void ControlBase::RightElbowTrackerCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_rupperarm_pose_raw_;
hmd_rupperarm_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_rupperarm_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_rupperarm_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_rupperarm_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_rupperarm_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_rupperarm_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setTrackerTarget(hmd_rupperarm_pose_raw_, 4);
}
void ControlBase::HmdCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_head_pose_raw_;
hmd_head_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_head_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_head_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_head_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_head_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_head_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setHMDTarget(hmd_head_pose_raw_);
}
void ControlBase::ChestTrackerCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_chest_pose_raw_;
hmd_chest_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_chest_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_chest_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_chest_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_chest_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_chest_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setTrackerTarget(hmd_chest_pose_raw_, 1);
}
void ControlBase::PelvisTrackerCallback(const VR::matrix_3_4 &msg)
{
Eigen::Isometry3d hmd_pelv_pose_raw_;
hmd_pelv_pose_raw_.linear().block(0, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.firstRow.data(), 3);
hmd_pelv_pose_raw_.linear().block(1, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.secondRow.data(), 3);
hmd_pelv_pose_raw_.linear().block(2, 0, 1, 3) = Eigen::RowVectorXd::Map(msg.thirdRow.data(), 3);
hmd_pelv_pose_raw_.translation()(0) = msg.firstRow[3];
hmd_pelv_pose_raw_.translation()(1) = msg.secondRow[3];
hmd_pelv_pose_raw_.translation()(2) = msg.thirdRow[3];
retarget_controller_.setTrackerTarget(hmd_pelv_pose_raw_, 0);
}
void ControlBase::PoseCalibrationCallback(const std_msgs::Int8 &msg)
{
retarget_controller_.setPoseCalibrationStatus(msg.data);
}
void ControlBase::TrackerStatusCallback(const std_msgs::Bool &msg)
{
retarget_controller_.setTrackerStatus(msg.data);
}
} | 36.012146 | 152 | 0.731816 | [
"vector"
] |
c195e97a85936392e8472c6d62e5621c30e9ba93 | 4,656 | cc | C++ | src/Data_Structure/List/DoubleLinkedList/dsal_double_linked_list.cc | Samukawa-T1/Common-DS-and-Alg-Lib | f77c929aa1da163cdba6552257c707d2bc884b26 | [
"Apache-2.0"
] | null | null | null | src/Data_Structure/List/DoubleLinkedList/dsal_double_linked_list.cc | Samukawa-T1/Common-DS-and-Alg-Lib | f77c929aa1da163cdba6552257c707d2bc884b26 | [
"Apache-2.0"
] | null | null | null | src/Data_Structure/List/DoubleLinkedList/dsal_double_linked_list.cc | Samukawa-T1/Common-DS-and-Alg-Lib | f77c929aa1da163cdba6552257c707d2bc884b26 | [
"Apache-2.0"
] | null | null | null | #include "dsal_double_linked_list.h"
namespace dsal{
template<typename T>
DoubleLinkedList<T>::DoubleLinkedList(){
size_ = 0;
head_ = new DoubleLinkedListNode();
tail_ = new DoubleLinkedListNode();
head_ -> NextNode = tail_;
tail_ -> PrevNode = head_;
}
template<typename T>
DoubleLinkedList<T>::DoubleLinkedList(const DoubleLinkedList<T>& kOther){
size_ = kOther.GetSize();
for(size_t i = 0; i < size_; i++)
Append(kOther[i]);
}
template<typename T>
DoubleLinkedList<T>::~DoubleLinkedList(){
Clear();
delete head_;
delete tail_;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::operator=(const DoubleLinkedList<T>& kOther){
size_ = kOther.GetSize();
for(size_t i = 0; i < size_; i++)
Append(kOther[i]);
return *this;
}
template<typename T>
T& DoubleLinkedList<T>::operator[](const size_t kIndex){
auto target = GetNode(kIndex);
if(target == tail_)
throw "Over Bounds";
return target -> Value;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Append(const T& kData){
return InsertBefore(size_, kData);
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::InsertBefore
(const size_t kIndex, const T& kData){
auto before_new = GetNode();
return InsertBefore(before_new, kData);
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::InsertBefore
(DoubleLinkedListNode<T>* after_new, const T& kData){
auto new_node = new DoubleLinkedListNode(kData);
auto before_new = after_new ->PrevNode;
new_node -> PrevNode = before_new;
new_node -> NextNode = after_new;
before_new -> NextNode = new_node;
after_new -> PrevNode = new_node;
++size_;
return *this;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Erase(const size_t kIndex){
auto target = GetNode(kIndex);
auto prev_node = target -> PrevNode;
auto next_node = target -> NextNode;
prev_node -> NextNode = next_node;
next_node -> PrevNode = prev_node;
delete target;
-- size_;
return *this;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Replace
(const size_t kIndex, const T& kData){
auto target = GetNode(kIndex);
target -> Value = kData;
return *this;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Swap
(const size_t kLeft,const size_t kRight){
auto node_a = GetNode(kLeft);
auto node_b = GetNode(kRight);
Swap(node_a, node_b);
return *this;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Swap
(DoubleLinkedListNode<T>* node_a, DoubleLinkedListNode<T>* node_b){
auto swap_temp = node_a -> Value;
node_a -> Value = node_b -> Value;
node_b -> Value = node_a -> Value;
return *this;
}
template<typename T>
DoubleLinkedListNode<T>* DoubleLinkedList<T>::Search(const T& kData) const{
auto current = head_ -> NextNode;
while(current != tail_){
if(current -> Value == kData)
break;
current = current -> NextNode;
}
return current;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Sort
(const size_t kBegin, const size_t kEnd,int (func)(const T&,const T&)){
if(kBegin + 1 >= kEnd)
return *this;
Vector<T> &self = *this;
size_t index = kBegin;
int count = 0
for(; index <= kEnd; index++)
if(func(self[kBegin], self[index]) == 1)
count++;
Swap(kBegin, count);
auto small_index = kBegin, big_index = count;
while(self[small_index] < self[count])
++small_index;
while(self[big_index] >= self[count])
++big_index;
while(!(small_index >= count && big_index >= kEnd))
swap(small_index, big_index);
while(self[small_index] < self[count])
++small_index;
while(self[big_index] >= self[count])
++big_index;
Sort(kBegin, count);
Sort(count + 1, kEnd);
}
template<typename T>
size_t DoubleLinkedList<T>::GetSize() const{
return size_;
}
template<typename T>
bool DoubleLinkedList<T>::IsEmpty() const{
return size_ == 0;
}
template<typename T>
DoubleLinkedList<T>& DoubleLinkedList<T>::Clear(){
auto current = head_ -> NextNode;
while(current != tail_){
auto current_next = current -> NextNode;
delete current;
current = current_next;
}
head_ -> NextNode = tail_;
tail_ -> PrevNode = head_;
return *this;
}
template<typename T>
DoubleLinkedListNode<T>* DoubleLinkedList<T>::GetNode(const size_t kIndex){
auto mid == size_ << 2;
auto current = head_;
if(kIndex <= mid){
size_t jumps = kIndex + 1;
while(--jumps >= 0)
current = current -> NextNode;
}
else{
size_t jumps = size_ - kIndex + 1;
current = tail_;
while(--jumps >= 0)
current = current -> PrevNode;
}
}
} | 25.582418 | 87 | 0.680842 | [
"vector"
] |
c19c0930adfd199387da6e481c559f77edd06f62 | 800 | hpp | C++ | lib/interfaces/Vector3d.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | lib/interfaces/Vector3d.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | lib/interfaces/Vector3d.hpp | benjyup/cpp_arcade | 4b755990b64156148e529da1c39efe8a8c0c5d1f | [
"MIT"
] | null | null | null | //
// Created by puente_t on 13/03/17.
//
#ifndef ARCADE_VECTOR3D_HPP
#define ARCADE_VECTOR3D_HPP
#include <cstdint>
#include <ostream>
namespace arcade
{
class Vector3d
{
private:
int32_t _x;
int32_t _y;
int32_t _z;
public:
Vector3d(int32_t x, int32_t y, int32_t z = 0);
Vector3d(Vector3d const &other);
~Vector3d(void);
Vector3d &operator=(Vector3d const &other);
int32_t getX(void) const;
int32_t getY(void) const;
int32_t getZ(void) const;
void setX(int32_t x);
void setY(int32_t y);
void setZ(int32_t z);
bool operator==(Vector3d const &other) const;
Vector3d operator+(Vector3d const &other) const;
};
std::ostream &operator<<(std::ostream &os, const Vector3d &vector);
};
#endif //ARCADE_VECTOR3D_HPP
| 16 | 70 | 0.66375 | [
"vector"
] |
c19d5015050e6350e020b28ea25ac48189e7d2a4 | 8,573 | hpp | C++ | ext/PaSGAL/csr_char.hpp | cartoonist/PairG | db7d28a5b9d01368dbfd2d9ae97a1d5179605be0 | [
"Apache-2.0"
] | 2 | 2020-07-08T09:10:19.000Z | 2020-09-01T17:54:41.000Z | ext/PaSGAL/csr_char.hpp | cartoonist/PairG | db7d28a5b9d01368dbfd2d9ae97a1d5179605be0 | [
"Apache-2.0"
] | 1 | 2020-10-14T09:09:05.000Z | 2021-03-28T04:38:17.000Z | ext/PaSGAL/csr_char.hpp | cartoonist/PairG | db7d28a5b9d01368dbfd2d9ae97a1d5179605be0 | [
"Apache-2.0"
] | 1 | 2020-08-28T09:02:56.000Z | 2020-08-28T09:02:56.000Z | /**
* @file csr_char.hpp
* @brief routines to store graph in CSR format
* (single character per vertex)
* @author Chirag Jain <cjain7@gatech.edu>
*/
#ifndef CSR_CHAR_CONTAINER_HPP
#define CSR_CHAR_CONTAINER_HPP
#include <cassert>
#include <iostream>
//Own includes
#include "PaSGAL/csr.hpp"
#include "PaSGAL/graph_iter.hpp"
namespace psgl
{
/**
* @brief class to support storage of directed graph in CSR format
* each vertex holds a character label
* @details CSR is a popular graph storage format-
* - vertex numbering starts from 0
* - Adjacency list (incoming edges) of vertex i is stored in
* array 'adjcny_in' starting at index offsets_in[i] and
* ending at (but not including) index offsets_in[i+1]
* - CSR_char_container should be built using existing
* CSR_container (see class constructor)
*
* - Assumption: count of vertices and edges < 2B because we are
* using int32_t type everywhere
*/
class CSR_char_container
{
public:
//Count of edges and vertices in the graph
int32_t numVertices;
int32_t numEdges;
//contiguous adjacency list of all vertices, size = numEdges
std::vector<int32_t> adjcny_in;
std::vector<int32_t> adjcny_out;
//offsets in adjacency list for each vertex, size = numVertices + 1
std::vector<int32_t> offsets_in;
std::vector<int32_t> offsets_out;
//Container to hold character label of all vertices in graph
std::vector<char> vertex_label;
//Container to hold original vertexi, and character offset (0-based)
std::vector< std::pair<int32_t, int32_t> > originalVertexId;
/**
* @brief build complete CSR_char graph
* @param[in] csr CSR graph container
*/
void build (CSR_container &csr)
{
this->numVertices = csr.totalRefLength();
vertex_label.reserve (csr.totalRefLength());
originalVertexId.reserve (csr.totalRefLength());
adjcny_in.reserve (csr.totalRefLength() + csr.numEdges - csr.numVertices);
adjcny_out.reserve (csr.totalRefLength() + csr.numEdges - csr.numVertices);
offsets_in.reserve (csr.totalRefLength() + 1);
offsets_out.reserve (csr.totalRefLength() + 1);
//Save vertex labels and original ids
{
for(int32_t i = 0; i < csr.numVertices; i++)
{
for(int32_t j = 0; j < csr.vertex_metadata[i].length(); j++)
{
vertex_label.push_back ( csr.vertex_metadata[i].at(j) );
originalVertexId.emplace_back (csr.originalVertexId[i],j);
}
}
}
//Init edges:
{
// in edges
{
offsets_in.push_back(0);
std::vector<int32_t> inNeighbors;
for (graphIterFwd g(csr); !g.end(); g.next())
{
//get preceeding dependency offsets from graph
inNeighbors.clear();
g.getInNeighborOffsets(inNeighbors);
for(auto &e : inNeighbors)
adjcny_in.push_back(e);
offsets_in.push_back (adjcny_in.size());
}
}
// out edges
{
offsets_out.push_back(0);
std::vector<int32_t> outNeighbors;
for (graphIterFwd g(csr); !g.end(); g.next())
{
//get preceeding dependency offsets from graph
outNeighbors.clear();
g.getOutNeighborOffsets(outNeighbors);
for(auto &e : outNeighbors)
adjcny_out.push_back(e);
offsets_out.push_back (adjcny_out.size());
}
}
}
this->numEdges = adjcny_in.size();
assert(vertex_label.size() == this->numVertices);
assert(originalVertexId.size() == this->numVertices);
assert(adjcny_in.size() == csr.totalRefLength() + csr.numEdges - csr.numVertices);
assert(adjcny_out.size() == csr.totalRefLength() + csr.numEdges - csr.numVertices);
assert(offsets_in.size() == csr.totalRefLength() + 1);
assert(offsets_out.size() == csr.totalRefLength() + 1);
#ifndef NDEBUG
this->verify();
#endif
std::cout << "INFO, psgl::CSR_char_container::build, graph converted to CSR format with character labels, n = " << this->numVertices << ", m = " << this->numEdges << std::endl;
}
/**
* @brief compute and print histogram of degree values
*/
void printDegreeHistogram () const
{
std::cout << "Printing degree distribution ..." << "\n";
int32_t maxDegree = 0;
//compute maximum degree in the graph
for(int32_t i = 0; i < this->numVertices; i++)
for(auto j = offsets_in[i]; j < offsets_in[i+1]; j++)
maxDegree = std::max (maxDegree, offsets_in[i+1] - offsets_in[i]);
std::vector<int32_t> degreeHist (maxDegree + 1, 0);
//compute histogram
for(int32_t i = 0; i < this->numVertices; i++)
for(auto j = offsets_in[i]; j < offsets_in[i+1]; j++)
degreeHist [offsets_in[i+1] - offsets_in[i] ]++;
for(int32_t i = 0; i <= maxDegree; i++)
if (degreeHist[i] > 0)
std::cout << i << " : " << degreeHist[i] << "\n";
std::cout.flush();
}
/**
* @brief compute and print histogram of hop distances in
* the sorted order
*/
void printHopLengthHistogram() const
{
std::cout << "Printing hop length distribution ..." << "\n";
//get maximum hop length
int32_t maxHopLength = this->directedBandwidth();
std::vector<int32_t> hopLengthHist (maxHopLength + 1, 0);
//compute histogram
for(int32_t i = 0; i < this->numVertices; i++)
for(auto j = offsets_in[i]; j < offsets_in[i+1]; j++)
hopLengthHist [ i - adjcny_in[j] ] ++;
for(int32_t i = 0; i <= maxHopLength; i++)
if (hopLengthHist[i] > 0)
std::cout << i << " : " << hopLengthHist[i] << "\n";
std::cout.flush();
}
private:
/**
* @brief compute maximum distance between connected vertices in the graph (a.k.a.
* directed bandwidth)
* @return directed graph bandwidth
*/
std::size_t directedBandwidth() const
{
std::size_t bandwidth = 0; //temporary value
//iterate over all vertices in graph to compute bandwidth
for(int32_t i = 0; i < this->numVertices; i++)
{
for(auto j = offsets_in[i]; j < offsets_in[i+1]; j++)
{
auto from_pos = adjcny_in[j];
auto to_pos = i;
assert(to_pos > from_pos);
if (to_pos - from_pos > bandwidth)
bandwidth = to_pos - from_pos;
}
}
return bandwidth;
}
/**
* @brief sanity check for correctness of graph storage in CSR format
*/
void verify() const
{
assert(this->numVertices > 0);
assert(this->numEdges > 0);
//labels
{
assert(vertex_label.size() == this->numVertices);
for(auto &c : vertex_label)
{
assert(std::isupper(c));
assert(c == 'A' || c == 'T' || c == 'G' || c == 'C' || c == 'N');
}
}
//adjacency list
{
assert(adjcny_in.size() == this->numEdges);
assert(adjcny_out.size() == this->numEdges);
for(auto vId : adjcny_in)
assert(vId >=0 && vId < this->numVertices);
for(auto vId : adjcny_out)
assert(vId >=0 && vId < this->numVertices);
}
//offset array
{
assert(offsets_in.size() == this->numVertices + 1);
assert(std::is_sorted(offsets_in.begin(), offsets_in.end()));
assert(offsets_in.front() == 0 && offsets_in.back() == this->numEdges);
assert(offsets_out.size() == this->numVertices + 1);
assert(std::is_sorted(offsets_out.begin(), offsets_out.end()));
assert(offsets_out.front() == 0 && offsets_out.back() == this->numEdges);
for(auto off : offsets_out)
assert(off >=0 && off <= this->numEdges);
}
}
};
}
#endif
| 31.288321 | 184 | 0.544384 | [
"vector"
] |
c19dc8ca54a4b636d73a8e89f81f81af258fc3f7 | 4,196 | cpp | C++ | lib/DirManager/dirman.cpp | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | 1 | 2021-10-10T09:09:26.000Z | 2021-10-10T09:09:26.000Z | src/dirman.cpp | WohlSoft/DirManager | ca8c736925b8b20614b02223dba97049be99233f | [
"MIT"
] | null | null | null | src/dirman.cpp | WohlSoft/DirManager | ca8c736925b8b20614b02223dba97049be99233f | [
"MIT"
] | null | null | null | /*
DirMan - A small crossplatform class to manage directories
Copyright (c) 2017 Vitaliy Novichkov <admin@wohlnet.ru>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <locale>
#include "dirman.h"
#include "dirman_private.h"
bool matchSuffixFilters(const std::string &name, const std::vector<std::string> &suffixFilters)
{
bool found = false;
std::locale loc;
if(suffixFilters.empty())
return true;//If no filter, grand everything
for(const std::string &suffix : suffixFilters)
{
if(suffix.size() > name.size())
continue;
std::string f;
f.reserve(name.size());
for(const char &c : name)
f.push_back(std::tolower(c, loc));
found |= (f.compare(f.size() - suffix.size(), suffix.size(), suffix) == 0);
if(found)
return true;
}
return found;
}
DirMan::DirMan(const std::string &dirPath) :
d(new DirMan_private)
{
setPath(dirPath);
}
DirMan::DirMan(const DirMan &dir) :
d(new DirMan_private)
{
setPath(dir.d->m_dirPath);
}
DirMan::~DirMan()
{}
void DirMan::setPath(const std::string &dirPath)
{
d->setPath(dirPath);
}
bool DirMan::getListOfFiles(std::vector<std::string> &list, const std::vector<std::string> &suffix_filters)
{
return d->getListOfFiles(list, suffix_filters);
}
bool DirMan::getListOfFolders(std::vector<std::string> &list, const std::vector<std::string> &suffix_filters)
{
return d->getListOfFolders(list, suffix_filters);
}
std::string DirMan::absolutePath()
{
return d->m_dirPath;
}
bool DirMan::exists()
{
return exists(d->m_dirPath);
}
bool DirMan::existsRel(const std::string &dirPath)
{
return exists(d->m_dirPath + "/" + dirPath);
}
bool DirMan::mkdir(const std::string &dirPath)
{
return mkAbsDir(d->m_dirPath + "/" + dirPath);
}
bool DirMan::rmdir(const std::string &dirPath)
{
return rmAbsDir(d->m_dirPath + "/" + dirPath);
}
bool DirMan::mkpath(const std::string &dirPath)
{
return mkAbsPath(d->m_dirPath + "/" + dirPath);
}
bool DirMan::rmpath(const std::string &dirPath)
{
return rmAbsPath(d->m_dirPath + "/" + dirPath);
}
bool DirMan::beginWalking(const std::vector<std::string> &suffix_filters)
{
std::locale loc;
#ifdef _WIN32
std::wstring &m_dirPath = d->m_dirPathW;
#else
std::string &m_dirPath = d->m_dirPath;
#endif
DirMan_private::DirWalkerState &m_walkerState = d->m_walkerState;
// Clear previous state
while(!m_walkerState.digStack.empty())
m_walkerState.digStack.pop();
// Initialize suffix filters
m_walkerState.suffix_filters.clear();
m_walkerState.suffix_filters.reserve(suffix_filters.size());
for(const std::string &filter : suffix_filters)
{
std::string f;
f.reserve(filter.size());
for(const char &c : filter)
f.push_back(std::tolower(c, loc));
m_walkerState.suffix_filters.push_back(f);
}
// Push initial path
m_walkerState.digStack.push(m_dirPath);
return true;
}
bool DirMan::fetchListFromWalker(std::string &curPath, std::vector<std::string> &list)
{
return d->fetchListFromWalker(curPath, list);
}
| 26.897436 | 109 | 0.68756 | [
"vector"
] |
c1a96e642b284e02c1fbfdfa9ac14866fc1a0484 | 25,504 | cpp | C++ | src/Particle/ParticleSet.cpp | recohen/qmcpack | 66c894da2e3108d709dfb4ae5cdf4f756f517763 | [
"NCSA"
] | null | null | null | src/Particle/ParticleSet.cpp | recohen/qmcpack | 66c894da2e3108d709dfb4ae5cdf4f756f517763 | [
"NCSA"
] | null | null | null | src/Particle/ParticleSet.cpp | recohen/qmcpack | 66c894da2e3108d709dfb4ae5cdf4f756f517763 | [
"NCSA"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign
// Luke Shulenburger, lshulen@sandia.gov, Sandia National Laboratories
// Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
// Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
// Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory
// Ye Luo, yeluo@anl.gov, Argonne National Laboratory
// Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
// Mark Dewing, markdewing@gmail.com, University of Illinois at Urbana-Champaign
//
// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
#include <numeric>
#include <iomanip>
#include "Particle/ParticleSet.h"
#include "Particle/DistanceTableData.h"
#include "Particle/createDistanceTable.h"
#include "LongRange/StructFact.h"
#include "Utilities/IteratorUtility.h"
#include "Utilities/RandomGenerator.h"
#include "ParticleBase/RandomSeqGenerator.h"
//#define PACK_DISTANCETABLES
namespace qmcplusplus
{
//using namespace particle_info;
#ifdef QMC_CUDA
template<>
int ParticleSet::Walker_t::cuda_DataSize = 0;
#endif
const TimerNameList_t<ParticleSet::PSTimers> ParticleSet::PSTimerNames = {{PS_newpos, "ParticleSet::computeNewPosDT"},
{PS_donePbyP, "ParticleSet::donePbyP"},
{PS_setActive, "ParticleSet::setActive"},
{PS_update, "ParticleSet::update"}};
ParticleSet::ParticleSet()
: quantum_domain(classical),
IsGrouped(true),
SameMass(true),
ThreadID(0),
activePtcl(-1),
SK(0),
myTwist(0.0),
ParentName("0"),
TotalNum(0)
{
initPropertyList();
setup_timers(myTimers, PSTimerNames, timer_level_fine);
}
ParticleSet::ParticleSet(const ParticleSet& p)
: IsGrouped(p.IsGrouped),
SameMass(true),
ThreadID(0),
activePtcl(-1),
mySpecies(p.getSpeciesSet()),
SK(0),
myTwist(0.0),
ParentName(p.parentName())
{
set_quantum_domain(p.quantum_domain);
assign(p); //only the base is copied, assumes that other properties are not assignable
//need explicit copy:
Mass = p.Mass;
Z = p.Z;
//std::ostringstream o;
//o<<p.getName()<<ObjectTag;
//this->setName(o.str());
//app_log() << " Copying a particle set " << p.getName() << " to " << this->getName() << " groups=" << groups() << std::endl;
myName = p.getName();
PropertyList.Names = p.PropertyList.Names;
PropertyList.Values = p.PropertyList.Values;
PropertyHistory = p.PropertyHistory;
Collectables = p.Collectables;
//construct the distance tables with the same order
for (int i = 0; i < p.DistTables.size(); ++i)
{
addTable(p.DistTables[i]->origin(), p.DistTables[i]->DTType);
DistTables[i]->Need_full_table_loadWalker = p.DistTables[i]->Need_full_table_loadWalker;
}
if (p.SK)
{
LRBox = p.LRBox; //copy LRBox
SK = new StructFact(*p.SK); //safe to use the copy constructor
//R.InUnit=p.R.InUnit;
//createSK();
//SK->DoUpdate=p.SK->DoUpdate;
}
setup_timers(myTimers, PSTimerNames, timer_level_fine);
myTwist = p.myTwist;
RSoA = p.RSoA;
G = p.G;
L = p.L;
}
ParticleSet::~ParticleSet()
{
DEBUG_MEMORY("ParticleSet::~ParticleSet");
delete_iter(DistTables.begin(), DistTables.end());
if (SK)
delete SK;
}
void ParticleSet::create(int numPtcl) { resize(numPtcl); }
void ParticleSet::create(const std::vector<int>& agroup)
{
SubPtcl.resize(agroup.size() + 1);
SubPtcl[0] = 0;
for (int is = 0; is < agroup.size(); is++)
SubPtcl[is + 1] = SubPtcl[is] + agroup[is];
size_t nsum = SubPtcl[agroup.size()];
resize(nsum);
TotalNum = nsum;
int loc = 0;
for (int i = 0; i < agroup.size(); i++)
{
for (int j = 0; j < agroup[i]; j++, loc++)
GroupID[loc] = i;
}
}
void ParticleSet::set_quantum_domain(quantum_domains qdomain)
{
if (quantum_domain_valid(qdomain))
quantum_domain = qdomain;
else
APP_ABORT("ParticleSet::set_quantum_domain\n input quantum domain is not valid for particles");
}
void ParticleSet::resetGroups()
{
int nspecies = mySpecies.getTotalNum();
if (nspecies == 0)
{
APP_ABORT("ParticleSet::resetGroups() Failed. No species exisits");
}
int natt = mySpecies.numAttributes();
int qind = mySpecies.addAttribute("charge");
if (natt == qind)
{
app_log() << " Missing charge attribute of the SpeciesSet " << myName << " particleset" << std::endl;
app_log() << " Assume neutral particles Z=0.0 " << std::endl;
for (int ig = 0; ig < nspecies; ig++)
mySpecies(qind, ig) = 0.0;
}
for (int iat = 0; iat < Z.size(); iat++)
Z[iat] = mySpecies(qind, GroupID[iat]);
natt = mySpecies.numAttributes();
int massind = mySpecies.addAttribute("mass");
if (massind == natt)
{
for (int ig = 0; ig < nspecies; ig++)
mySpecies(massind, ig) = 1.0;
}
SameMass = true;
double m0 = mySpecies(massind, 0);
for (int ig = 1; ig < nspecies; ig++)
SameMass &= (mySpecies(massind, ig) == m0);
if (SameMass)
app_log() << " All the species have the same mass " << m0 << std::endl;
else
app_log() << " Distinctive masses for each species " << std::endl;
for (int iat = 0; iat < Mass.size(); iat++)
Mass[iat] = mySpecies(massind, GroupID[iat]);
std::vector<int> ng(nspecies, 0);
for (int iat = 0; iat < GroupID.size(); iat++)
{
if (GroupID[iat] < nspecies)
ng[GroupID[iat]]++;
else
APP_ABORT("ParticleSet::resetGroups() Failed. GroupID is out of bound.");
}
SubPtcl.resize(nspecies + 1);
SubPtcl[0] = 0;
for (int i = 0; i < nspecies; ++i)
SubPtcl[i + 1] = SubPtcl[i] + ng[i];
int membersize = mySpecies.addAttribute("membersize");
for (int ig = 0; ig < nspecies; ++ig)
mySpecies(membersize, ig) = ng[ig];
//orgID=ID;
//orgGroupID=GroupID;
int new_id = 0;
for (int i = 0; i < nspecies; ++i)
for (int iat = 0; iat < GroupID.size(); ++iat)
if (GroupID[iat] == i)
IndirectID[new_id++] = ID[iat];
IsGrouped = true;
for (int iat = 0; iat < ID.size(); ++iat)
IsGrouped &= (IndirectID[iat] == ID[iat]);
}
void ParticleSet::randomizeFromSource(ParticleSet& src)
{
SpeciesSet& srcSpSet(src.getSpeciesSet());
SpeciesSet& spSet(getSpeciesSet());
int srcChargeIndx = srcSpSet.addAttribute("charge");
int srcMemberIndx = srcSpSet.addAttribute("membersize");
int ChargeIndex = spSet.addAttribute("charge");
int MemberIndx = spSet.addAttribute("membersize");
int Nsrc = src.getTotalNum();
int Nptcl = getTotalNum();
int NumSpecies = spSet.TotalNum;
int NumSrcSpecies = srcSpSet.TotalNum;
//Store information about charges and number of each species
std::vector<int> Zat, Zspec, NofSpecies, NofSrcSpecies, CurElec;
Zat.resize(Nsrc);
Zspec.resize(NumSrcSpecies);
NofSpecies.resize(NumSpecies);
CurElec.resize(NumSpecies);
NofSrcSpecies.resize(NumSrcSpecies);
for (int spec = 0; spec < NumSrcSpecies; spec++)
{
Zspec[spec] = (int)round(srcSpSet(srcChargeIndx, spec));
NofSrcSpecies[spec] = (int)round(srcSpSet(srcMemberIndx, spec));
}
for (int spec = 0; spec < NumSpecies; spec++)
{
NofSpecies[spec] = (int)round(spSet(MemberIndx, spec));
CurElec[spec] = first(spec);
}
int totQ = 0;
for (int iat = 0; iat < Nsrc; iat++)
totQ += Zat[iat] = Zspec[src.GroupID[iat]];
app_log() << " Total ion charge = " << totQ << std::endl;
totQ -= Nptcl;
app_log() << " Total system charge = " << totQ << std::endl;
// Now, loop over ions, attaching electrons to them to neutralize
// charge
int spToken = 0;
// This is decremented when we run out of electrons in each species
int spLeft = NumSpecies;
std::vector<PosType> gaussRand(Nptcl);
makeGaussRandom(gaussRand);
for (int iat = 0; iat < Nsrc; iat++)
{
// Loop over electrons to add, selecting round-robin from the
// electron species
int z = Zat[iat];
while (z > 0 && spLeft)
{
int sp = spToken++ % NumSpecies;
if (NofSpecies[sp])
{
NofSpecies[sp]--;
z--;
int elec = CurElec[sp]++;
app_log() << " Assigning " << (sp ? "down" : "up ") << " electron " << elec << " to ion " << iat
<< " with charge " << z << std::endl;
double radius = 0.5 * std::sqrt((double)Zat[iat]);
R[elec] = src.R[iat] + radius * gaussRand[elec];
}
else
spLeft--;
}
}
// Assign remaining electrons
int ion = 0;
for (int sp = 0; sp < NumSpecies; sp++)
{
for (int ie = 0; ie < NofSpecies[sp]; ie++)
{
int iat = ion++ % Nsrc;
double radius = std::sqrt((double)Zat[iat]);
int elec = CurElec[sp]++;
R[elec] = src.R[iat] + radius * gaussRand[elec];
}
}
}
///write to a std::ostream
bool ParticleSet::get(std::ostream& os) const
{
os << " ParticleSet '" << getName() << "' contains " << TotalNum << " particles : ";
if (SubPtcl.size() > 0)
for (int i = 0; i < SubPtcl.size() - 1; i++)
os << " " << mySpecies.speciesName[i] << "(" << SubPtcl[i + 1] - SubPtcl[i] << ")";
os << std::endl;
if (!IsGrouped)
os << " Particles are not grouped by species in the input file. Algorithms may not be optimal!" << std::endl;
os << std::endl;
const size_t maxParticlesToPrint = 10;
size_t numToPrint = std::min(TotalNum, maxParticlesToPrint);
for (int i = 0; i < numToPrint; i++)
{
os << " " << mySpecies.speciesName[GroupID[i]] << R[i] << std::endl;
}
if (numToPrint < TotalNum)
{
os << " (... and " << (TotalNum - numToPrint) << " more particle positions ...)" << std::endl;
}
os << std::endl;
for (const std::string& description : distTableDescriptions)
os << description;
os << std::endl;
return true;
}
///read from std::istream
bool ParticleSet::put(std::istream& is) { return true; }
///reset member data
void ParticleSet::reset() { app_log() << "<<<< going to set properties >>>> " << std::endl; }
///read the particleset
bool ParticleSet::put(xmlNodePtr cur) { return true; }
int ParticleSet::addTable(const ParticleSet& psrc, int dt_type, bool need_full_table_loadWalker)
{
if (myName == "none" || psrc.getName() == "none")
APP_ABORT("ParticleSet::addTable needs proper names for both source and target particle sets.");
if (DistTables.size() > 0 && dt_type != DT_SOA_PREFERRED && !DistTables[0]->is_same_type(dt_type))
APP_ABORT("ParticleSet::addTable Cannot mix AoS and SoA distance tables.\n");
int tid;
std::map<std::string, int>::iterator tit(myDistTableMap.find(psrc.getName()));
if (tit == myDistTableMap.end())
{
std::ostringstream description;
tid = DistTables.size();
int dt_type_in_use = (tid == 0 ? dt_type : DistTables[0]->DTType);
if (myName == psrc.getName())
DistTables.push_back(createDistanceTable(*this, dt_type_in_use, description));
else
DistTables.push_back(createDistanceTable(psrc, *this, dt_type_in_use, description));
distTableDescriptions.push_back(description.str());
myDistTableMap[psrc.getName()] = tid;
app_debug() << " ... ParticleSet::addTable Create Table #" << tid << " " << DistTables[tid]->Name << std::endl;
}
else
{
tid = (*tit).second;
app_debug() << " ... ParticleSet::addTable Reuse Table #" << tid << " " << DistTables[tid]->Name << std::endl;
}
DistTables[tid]->Need_full_table_loadWalker =
(DistTables[tid]->Need_full_table_loadWalker || need_full_table_loadWalker);
app_log().flush();
return tid;
}
void ParticleSet::update(bool skipSK)
{
ScopedTimer update_scope(myTimers[PS_update]);
RSoA.copyIn(R);
for (int i = 0; i < DistTables.size(); i++)
DistTables[i]->evaluate(*this);
if (!skipSK && SK)
SK->UpdateAllPart(*this);
activePtcl = -1;
}
void ParticleSet::setActive(int iat)
{
ScopedTimer set_active_scope(myTimers[PS_setActive]);
for (size_t i = 0; i < DistTables.size(); i++)
if (DistTables[i]->DTType == DT_SOA)
DistTables[i]->evaluate(*this, iat);
}
void ParticleSet::flex_setActive(const RefVector<ParticleSet>& P_list, int iat)
{
if (P_list.size() > 1)
{
ScopedTimer local_timer(P_list[0].get().myTimers[PS_setActive]);
int dist_tables_size = P_list[0].get().DistTables.size();
#pragma omp parallel
{
for (size_t i = 0; i < dist_tables_size; i++)
{
#pragma omp for
for (int iw = 0; iw < P_list.size(); iw++)
{
P_list[iw].get().DistTables[i]->evaluate(P_list[iw], iat);
}
}
}
}
else if (P_list.size() == 1)
P_list[0].get().setActive(iat);
}
void ParticleSet::makeMove(Index_t iat, const SingleParticlePos_t& displ)
{
activePtcl = iat;
activePos = R[iat] + displ;
computeNewPosDistTablesAndSK(iat, activePos);
}
void ParticleSet::makeMoveWithSpin(Index_t iat, const SingleParticlePos_t& displ, const RealType& sdispl)
{
makeMove(iat, displ);
activeSpinVal = spins[iat] + sdispl;
}
void ParticleSet::flex_makeMove(const RefVector<ParticleSet>& P_list,
Index_t iat,
const std::vector<SingleParticlePos_t>& displs)
{
if (P_list.size() > 1)
{
std::vector<SingleParticlePos_t> new_positions;
new_positions.reserve(displs.size());
for (int iw = 0; iw < P_list.size(); iw++)
{
P_list[iw].get().activePtcl = iat;
P_list[iw].get().activePos = P_list[iw].get().R[iat] + displs[iw];
new_positions.push_back(P_list[iw].get().activePos);
}
mw_computeNewPosDistTablesAndSK(P_list, iat, new_positions);
}
else if (P_list.size() == 1)
P_list[0].get().makeMove(iat, displs[0]);
}
bool ParticleSet::makeMoveAndCheck(Index_t iat, const SingleParticlePos_t& displ)
{
activePtcl = iat;
activePos = R[iat] + displ;
bool is_valid = true;
if (Lattice.explicitly_defined)
{
if (Lattice.outOfBound(Lattice.toUnit(displ)))
is_valid = false;
else
{
newRedPos = Lattice.toUnit(activePos);
if (!Lattice.isValid(newRedPos))
is_valid = false;
}
}
computeNewPosDistTablesAndSK(iat, activePos);
return is_valid;
}
bool ParticleSet::makeMoveAndCheckWithSpin(Index_t iat, const SingleParticlePos_t& displ, const RealType& sdispl)
{
activeSpinVal = spins[iat] + sdispl;
return makeMoveAndCheck(iat, displ);
}
void ParticleSet::computeNewPosDistTablesAndSK(Index_t iat, const SingleParticlePos_t& newpos)
{
ScopedTimer compute_newpos_scope(myTimers[PS_newpos]);
for (int i = 0; i < DistTables.size(); ++i)
DistTables[i]->move(*this, newpos);
//Do not change SK: 2007-05-18
//Change SK only if DoUpdate is true: 2008-09-12
if (SK && SK->DoUpdate)
SK->makeMove(iat, newpos);
}
void ParticleSet::mw_computeNewPosDistTablesAndSK(const RefVector<ParticleSet>& P_list,
Index_t iat,
const std::vector<SingleParticlePos_t>& new_positions)
{
ScopedTimer compute_newpos_scope(P_list[0].get().myTimers[PS_newpos]);
int dist_tables_size = P_list[0].get().DistTables.size();
#pragma omp parallel
{
for (int i = 0; i < dist_tables_size; ++i)
{
#pragma omp for
for (int iw = 0; iw < P_list.size(); iw++)
P_list[iw].get().DistTables[i]->move(P_list[iw], new_positions[iw]);
}
StructFact* SK = P_list[0].get().SK;
if (SK && SK->DoUpdate)
{
#pragma omp for
for (int iw = 0; iw < P_list.size(); iw++)
P_list[iw].get().SK->makeMove(iat, new_positions[iw]);
}
}
}
bool ParticleSet::makeMoveAllParticles(const Walker_t& awalker, const ParticlePos_t& deltaR, RealType dt)
{
activePtcl = -1;
if (Lattice.explicitly_defined)
{
for (int iat = 0; iat < deltaR.size(); ++iat)
{
SingleParticlePos_t displ(dt * deltaR[iat]);
if (Lattice.outOfBound(Lattice.toUnit(displ)))
return false;
SingleParticlePos_t newpos(awalker.R[iat] + displ);
if (!Lattice.isValid(Lattice.toUnit(newpos)))
return false;
R[iat] = newpos;
}
}
else
{
for (int iat = 0; iat < deltaR.size(); ++iat)
R[iat] = awalker.R[iat] + dt * deltaR[iat];
}
RSoA.copyIn(R);
for (int i = 0; i < DistTables.size(); i++)
DistTables[i]->evaluate(*this);
if (SK)
SK->UpdateAllPart(*this);
//every move is valid
return true;
}
bool ParticleSet::makeMoveAllParticles(const Walker_t& awalker,
const ParticlePos_t& deltaR,
const std::vector<RealType>& dt)
{
activePtcl = -1;
if (Lattice.explicitly_defined)
{
for (int iat = 0; iat < deltaR.size(); ++iat)
{
SingleParticlePos_t displ(dt[iat] * deltaR[iat]);
if (Lattice.outOfBound(Lattice.toUnit(displ)))
return false;
SingleParticlePos_t newpos(awalker.R[iat] + displ);
if (!Lattice.isValid(Lattice.toUnit(newpos)))
return false;
R[iat] = newpos;
}
}
else
{
for (int iat = 0; iat < deltaR.size(); ++iat)
R[iat] = awalker.R[iat] + dt[iat] * deltaR[iat];
}
RSoA.copyIn(R);
for (int i = 0; i < DistTables.size(); i++)
DistTables[i]->evaluate(*this);
if (SK)
SK->UpdateAllPart(*this);
//every move is valid
return true;
}
/** move a walker by dt*deltaR + drift
* @param awalker initial walker configuration
* @param drift drift vector
* @param deltaR random displacement
* @param dt timestep
* @return true, if all the particle moves are legal under the boundary conditions
*/
bool ParticleSet::makeMoveAllParticlesWithDrift(const Walker_t& awalker,
const ParticlePos_t& drift,
const ParticlePos_t& deltaR,
RealType dt)
{
activePtcl = -1;
if (Lattice.explicitly_defined)
{
for (int iat = 0; iat < deltaR.size(); ++iat)
{
SingleParticlePos_t displ(dt * deltaR[iat] + drift[iat]);
if (Lattice.outOfBound(Lattice.toUnit(displ)))
return false;
SingleParticlePos_t newpos(awalker.R[iat] + displ);
if (!Lattice.isValid(Lattice.toUnit(newpos)))
return false;
R[iat] = newpos;
}
}
else
{
for (int iat = 0; iat < deltaR.size(); ++iat)
R[iat] = awalker.R[iat] + dt * deltaR[iat] + drift[iat];
}
RSoA.copyIn(R);
for (int i = 0; i < DistTables.size(); i++)
DistTables[i]->evaluate(*this);
if (SK)
SK->UpdateAllPart(*this);
//every move is valid
return true;
}
bool ParticleSet::makeMoveAllParticlesWithDrift(const Walker_t& awalker,
const ParticlePos_t& drift,
const ParticlePos_t& deltaR,
const std::vector<RealType>& dt)
{
activePtcl = -1;
if (Lattice.explicitly_defined)
{
for (int iat = 0; iat < deltaR.size(); ++iat)
{
SingleParticlePos_t displ(dt[iat] * deltaR[iat] + drift[iat]);
if (Lattice.outOfBound(Lattice.toUnit(displ)))
return false;
SingleParticlePos_t newpos(awalker.R[iat] + displ);
if (!Lattice.isValid(Lattice.toUnit(newpos)))
return false;
R[iat] = newpos;
}
}
else
{
for (int iat = 0; iat < deltaR.size(); ++iat)
R[iat] = awalker.R[iat] + dt[iat] * deltaR[iat] + drift[iat];
}
RSoA.copyIn(R);
for (int i = 0; i < DistTables.size(); i++)
DistTables[i]->evaluate(*this);
if (SK)
SK->UpdateAllPart(*this);
//every move is valid
return true;
}
/** update the particle attribute by the proposed move
*@param iat the particle index
*
*When the activePtcl is equal to iat, overwrite the position and update the
*content of the distance tables.
*/
void ParticleSet::acceptMove(Index_t iat)
{
if (iat == activePtcl)
{
//Update position + distance-table
for (int i = 0, n = DistTables.size(); i < n; i++)
DistTables[i]->update(iat);
//Do not change SK: 2007-05-18
if (SK && SK->DoUpdate)
SK->acceptMove(iat, GroupID[iat], R[iat]);
R[iat] = activePos;
RSoA(iat) = activePos;
spins[iat] = activeSpinVal;
activePtcl = -1;
}
else
{
std::ostringstream o;
o << " Illegal acceptMove " << iat << " != " << activePtcl;
APP_ABORT(o.str());
}
}
void ParticleSet::flex_donePbyP(const RefVector<ParticleSet>& P_list)
{
for (int iw = 0; iw < P_list.size(); iw++)
P_list[iw].get().donePbyP();
}
void ParticleSet::donePbyP()
{
ScopedTimer donePbyP_scope(myTimers[PS_donePbyP]);
if (SK && !SK->DoUpdate)
SK->UpdateAllPart(*this);
activePtcl = -1;
}
void ParticleSet::makeVirtualMoves(const SingleParticlePos_t& newpos)
{
activePtcl = -1;
activePos = newpos;
for (size_t i = 0; i < DistTables.size(); ++i)
DistTables[i]->move(*this, newpos);
}
void ParticleSet::loadWalker(Walker_t& awalker, bool pbyp)
{
R = awalker.R;
RSoA.copyIn(R);
#if !defined(SOA_MEMORY_OPTIMIZED)
G = awalker.G;
L = awalker.L;
#endif
if (pbyp)
{
// in certain cases, full tables must be ready
for (int i = 0; i < DistTables.size(); i++)
if (DistTables[i]->DTType == DT_AOS || DistTables[i]->Need_full_table_loadWalker)
DistTables[i]->evaluate(*this);
//computed so that other objects can use them, e.g., kSpaceJastrow
if (SK && SK->DoUpdate)
SK->UpdateAllPart(*this);
}
activePtcl = -1;
}
void ParticleSet::saveWalker(Walker_t& awalker)
{
awalker.R = R;
#if !defined(SOA_MEMORY_OPTIMIZED)
awalker.G = G;
awalker.L = L;
#endif
//PAOps<RealType,OHMMS_DIM>::copy(G,awalker.Drift);
//if (SK)
// SK->UpdateAllPart(*this);
//awalker.DataSet.rewind();
}
void ParticleSet::flex_saveWalker(RefVector<ParticleSet>& psets, RefVector<Walker_t>& walkers)
{
int num_sets = psets.size();
auto saveWalker = [](ParticleSet& pset, Walker_t& walker) {
walker.R = pset.R;
#if !defined(SOA_MEMORY_OPTIMIZED)
walker.G = pset.G;
walker.L = pset.L;
#endif
};
for (int iw = 0; iw < num_sets; ++iw)
saveWalker(psets[iw], walkers[iw]);
}
void ParticleSet::initPropertyList()
{
PropertyList.clear();
//Need to add the default Properties according to the enumeration
PropertyList.add("LogPsi");
PropertyList.add("SignPsi");
PropertyList.add("UmbrellaWeight");
PropertyList.add("R2Accepted");
PropertyList.add("R2Proposed");
PropertyList.add("DriftScale");
PropertyList.add("AltEnergy");
PropertyList.add("LocalEnergy");
PropertyList.add("LocalPotential");
if (PropertyList.size() != NUMPROPERTIES)
{
app_error() << "The number of default properties for walkers is not consistent." << std::endl;
app_error() << "NUMPROPERTIES " << NUMPROPERTIES << " size of PropertyList " << PropertyList.size() << std::endl;
APP_ABORT("ParticleSet::initPropertyList");
}
}
void ParticleSet::clearDistanceTables()
{
//Physically remove the tables
delete_iter(DistTables.begin(), DistTables.end());
DistTables.clear();
//for(int i=0; i< DistTables.size(); i++) DistanceTable::removeTable(DistTables[i]->getName());
//DistTables.erase(DistTables.begin(),DistTables.end());
}
int ParticleSet::addPropertyHistory(int leng)
{
int newL = PropertyHistory.size();
std::vector<FullPrecRealType> newVecHistory = std::vector<FullPrecRealType>(leng, 0.0);
PropertyHistory.push_back(newVecHistory);
PHindex.push_back(0);
return newL;
}
// void ParticleSet::resetPropertyHistory( )
// {
// for(int i=0;i<PropertyHistory.size();i++)
// {
// PHindex[i]=0;
// for(int k=0;k<PropertyHistory[i].size();k++)
// {
// PropertyHistory[i][k]=0.0;
// }
// }
// }
// void ParticleSet::addPropertyHistoryPoint(int index, RealType data)
// {
// PropertyHistory[index][PHindex[index]]=(data);
// PHindex[index]++;
// if (PHindex[index]==PropertyHistory[index].size()) PHindex[index]=0;
// // PropertyHistory[index].pop_back();
// }
// void ParticleSet::rejectedMove()
// {
// for(int dindex=0;dindex<PropertyHistory.size();dindex++){
// int lastIndex=PHindex[dindex]-1;
// if (lastIndex<0) lastIndex+=PropertyHistory[dindex].size();
// PropertyHistory[dindex][PHindex[dindex]]=PropertyHistory[dindex][lastIndex];
// PHindex[dindex]++;
// if (PHindex[dindex]==PropertyHistory[dindex].size()) PHindex[dindex]=0;
// // PropertyHistory[dindex].push_front(PropertyHistory[dindex].front());
// // PropertyHistory[dindex].pop_back();
// }
// }
} // namespace qmcplusplus
| 31.447596 | 128 | 0.615707 | [
"vector"
] |
c1b5276abe9bb2d802473b2058521903eb9e4896 | 4,209 | cpp | C++ | dev/floyd_speak/parts/immer-master/benchmark/vector/misc/take.cpp | lemonad/floyd | 736d21f20d1bdab7082b4461d7b6330cb4b10224 | [
"MIT"
] | null | null | null | dev/floyd_speak/parts/immer-master/benchmark/vector/misc/take.cpp | lemonad/floyd | 736d21f20d1bdab7082b4461d7b6330cb4b10224 | [
"MIT"
] | null | null | null | dev/floyd_speak/parts/immer-master/benchmark/vector/misc/take.cpp | lemonad/floyd | 736d21f20d1bdab7082b4461d7b6330cb4b10224 | [
"MIT"
] | null | null | null | //
// immer - immutable data structures for C++
// Copyright (C) 2016, 2017 Juan Pedro Bolivar Puente
//
// This file is part of immer.
//
// immer is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// immer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with immer. If not, see <http://www.gnu.org/licenses/>.
//
#include "benchmark/vector/take.hpp"
#include <immer/vector.hpp>
#include <immer/flex_vector.hpp>
#include <immer/vector_transient.hpp>
#include <immer/flex_vector_transient.hpp>
#include <immer/heap/gc_heap.hpp>
#include <immer/refcount/no_refcount_policy.hpp>
#include <immer/refcount/unsafe_refcount_policy.hpp>
#if IMMER_BENCHMARK_LIBRRB
extern "C" {
#define restrict __restrict__
#include <rrb.h>
#undef restrict
}
#endif
#if IMMER_BENCHMARK_LIBRRB
NONIUS_BENCHMARK("librrb", benchmark_take_librrb(make_librrb_vector))
NONIUS_BENCHMARK("librrb/F", benchmark_take_librrb(make_librrb_vector_f))
NONIUS_BENCHMARK("l/librrb", benchmark_take_lin_librrb(make_librrb_vector))
NONIUS_BENCHMARK("l/librrb/F", benchmark_take_lin_librrb(make_librrb_vector_f))
NONIUS_BENCHMARK("t/librrb", benchmark_take_mut_librrb(make_librrb_vector))
NONIUS_BENCHMARK("t/librrb/F", benchmark_take_mut_librrb(make_librrb_vector_f))
#endif
NONIUS_BENCHMARK("vector/4B", benchmark_take<immer::vector<unsigned,def_memory,4>>())
NONIUS_BENCHMARK("vector/5B", benchmark_take<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("vector/6B", benchmark_take<immer::vector<unsigned,def_memory,6>>())
NONIUS_BENCHMARK("vector/GC", benchmark_take<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("vector/NO", benchmark_take<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("vector/UN", benchmark_take<immer::vector<unsigned,unsafe_memory,5>>())
NONIUS_BENCHMARK("vector_s/GC", benchmark_take<immer::vector<std::size_t,gc_memory,5>>())
NONIUS_BENCHMARK("flex/F/5B", benchmark_take<immer::flex_vector<unsigned,def_memory,5>, push_front_fn>())
NONIUS_BENCHMARK("flex/F/GC", benchmark_take<immer::flex_vector<unsigned,gc_memory,5>, push_front_fn>())
NONIUS_BENCHMARK("flex/F/GCF", benchmark_take<immer::flex_vector<unsigned,gcf_memory,5>, push_front_fn>())
NONIUS_BENCHMARK("flex_s/F/GC", benchmark_take<immer::flex_vector<std::size_t,gc_memory,5>, push_front_fn>())
NONIUS_BENCHMARK("l/vector/5B", benchmark_take_lin<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("l/vector/GC", benchmark_take_lin<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("l/vector/NO", benchmark_take_lin<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("l/vector/UN", benchmark_take_lin<immer::vector<unsigned,unsafe_memory,5>>())
NONIUS_BENCHMARK("l/flex/F/5B", benchmark_take_lin<immer::flex_vector<unsigned,def_memory,5>, push_front_fn>())
NONIUS_BENCHMARK("m/vector/5B", benchmark_take_move<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("m/vector/GC", benchmark_take_move<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("m/vector/NO", benchmark_take_move<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("m/vector/UN", benchmark_take_move<immer::vector<unsigned,unsafe_memory,5>>())
NONIUS_BENCHMARK("m/flex/F/5B", benchmark_take_move<immer::flex_vector<unsigned,def_memory,5>, push_front_fn>())
NONIUS_BENCHMARK("t/vector/5B", benchmark_take_mut<immer::vector<unsigned,def_memory,5>>())
NONIUS_BENCHMARK("t/vector/GC", benchmark_take_mut<immer::vector<unsigned,gc_memory,5>>())
NONIUS_BENCHMARK("t/vector/NO", benchmark_take_mut<immer::vector<unsigned,basic_memory,5>>())
NONIUS_BENCHMARK("t/vector/UN", benchmark_take_mut<immer::vector<unsigned,unsafe_memory,5>>())
NONIUS_BENCHMARK("t/flex/F/5B", benchmark_take_mut<immer::flex_vector<unsigned,def_memory,5>, push_front_fn>())
| 53.961538 | 112 | 0.791399 | [
"vector"
] |
c1b62e7400ffdd05f7100451106a5b9d0c3c7a07 | 20,846 | cpp | C++ | src/math/lp/nex_creator.cpp | CantelopePeel/z3 | 3caf8eb032c2099e06cf38d20e0a981ad8f9716d | [
"MIT"
] | null | null | null | src/math/lp/nex_creator.cpp | CantelopePeel/z3 | 3caf8eb032c2099e06cf38d20e0a981ad8f9716d | [
"MIT"
] | 16 | 2016-04-13T23:48:33.000Z | 2020-02-02T12:38:52.000Z | src/math/lp/nex_creator.cpp | CantelopePeel/z3 | 3caf8eb032c2099e06cf38d20e0a981ad8f9716d | [
"MIT"
] | null | null | null | /*++
Copyright (c) 2017 Microsoft Corporation
Module Name:
<name>
Abstract:
<abstract>
Author:
Nikolaj Bjorner (nbjorner)
Lev Nachmanson (levnach)
Revision History:
--*/
#include "util/lbool.h"
#include "math/lp/nex_creator.h"
#include <map>
using namespace nla;
// divides by variable j. A precondition is that a is a multiple of j.
nex * nex_creator::mk_div(const nex& a, lpvar j) {
SASSERT(is_simplified(a));
SASSERT(a.contains(j));
SASSERT(a.is_mul() || (a.is_var() && a.to_var().var() == j));
if (a.is_var())
return mk_scalar(rational(1));
mul_factory mf(*this);
bool seenj = false;
auto ma = a.to_mul();
for (auto& p : ma) {
const nex * c = p.e();
int pow = p.pow();
if (!seenj && c->contains(j)) {
SASSERT(!c->is_var() || c->to_var().var() == j);
if (!c->is_var()) {
mf *= nex_pow(mk_div(*c, j), 1);
}
if (pow != 1) {
mf *= nex_pow(clone(c), pow - 1);
}
seenj = true;
} else {
mf *= nex_pow(clone(c), pow);
}
}
mf *= ma.coeff();
return mf.mk_reduced();
}
// return true if p is a constant, update r with value of p raised to pow.
bool nex_creator::eat_scalar_pow(rational& r, const nex_pow& p, unsigned pow) {
if (p.e()->is_mul() && p.e()->to_mul().size() == 0) {
auto const& m = p.e()->to_mul();
if (!m.coeff().is_one()) {
r *= m.coeff().expt(p.pow() * pow);
}
return true;
}
if (!p.e()->is_scalar())
return false;
const nex_scalar &pe = p.e()->to_scalar();
if (!pe.value().is_one()) {
r *= pe.value().expt(p.pow() * pow);
}
return true;
}
void nex_creator::simplify_children_of_mul(vector<nex_pow> & children, rational& coeff) {
TRACE("grobner_d", print_vector(children, tout << "children_of_mul: "); tout << "\n";);
vector<nex_pow> to_promote;
unsigned j = 0;
for (nex_pow& p : children) {
if (eat_scalar_pow(coeff, p, 1)) {
continue;
}
p.e() = simplify(p.e());
if (p.e()->is_mul()) {
to_promote.push_back(p);
} else {
children[j++] = p;
}
}
children.shrink(j);
for (nex_pow & p : to_promote) {
TRACE("grobner_d", tout << p << "\n";);
nex_mul &pm = p.e()->to_mul();
for (nex_pow& pp : pm) {
TRACE("grobner_d", tout << pp << "\n";);
if (!eat_scalar_pow(coeff, pp, p.pow()))
children.push_back(nex_pow(pp.e(), pp.pow() * p.pow()));
}
coeff *= pm.coeff().expt(p.pow());
}
mul_to_powers(children);
TRACE("grobner_d", print_vector(children, tout););
}
template <typename T>
bool nex_creator::gt_on_powers_mul_same_degree(const T& a, const nex_mul& b) const {
bool ret = false;
unsigned a_pow = a.begin()->pow();
unsigned b_pow = b.begin()->pow();
for (auto it_a = a.begin(), it_b = b.begin(); it_a != a.end() && it_b != b.end(); ) {
if (gt(it_a->e(), it_b->e())){
ret = true;
break;
}
if (gt(it_b->e(), it_a->e())){
ret = false;
break;
}
if (a_pow > b_pow) {
ret = true;
break;
}
if (a_pow < b_pow) {
ret = false;
break;
}
++it_a;
++it_b;
if (it_a != a.end()) a_pow = it_a->pow();
if (it_b != b.end()) b_pow = it_b->pow();
}
TRACE("nex_gt", tout << "a = "; print_vector(a, tout) << (ret?" > ":" <= ") << b << "\n";);
return ret;
}
bool nex_creator::gt_on_mul_mul(const nex_mul& a, const nex_mul& b) const {
TRACE("grobner_d", tout << "a = " << a << " , b = " << b << "\n";);
SASSERT(is_simplified(a) && is_simplified(b));
unsigned a_deg = a.get_degree();
unsigned b_deg = b.get_degree();
return a_deg == b_deg ? gt_on_powers_mul_same_degree(a, b) : a_deg > b_deg;
}
bool nex_creator::gt_on_var_nex(const nex_var& a, const nex& b) const {
switch (b.type()) {
case expr_type::SCALAR:
return true;
case expr_type::VAR:
return gt(a.var(), b.to_var().var());
case expr_type::MUL:
return b.get_degree() <= 1 && gt_on_var_nex(a, *b.to_mul()[0].e());
case expr_type::SUM:
SASSERT(b.size() > 1);
return gt(&a, b.to_sum()[0]);
default:
UNREACHABLE();
return false;
}
}
bool nex_creator::gt_on_mul_nex(nex_mul const& m, nex const& b) const {
switch (b.type()) {
case expr_type::SCALAR:
return false;
case expr_type::VAR:
if (m.get_degree() > 1)
return true;
SASSERT(m[0].pow() == 1);
SASSERT(!m[0].e()->is_scalar());
return gt(m[0].e(), &b);
case expr_type::MUL:
return gt_on_mul_mul(m, b.to_mul());
case expr_type::SUM:
return gt_on_mul_nex(m, *b.to_sum()[0]);
default:
UNREACHABLE();
return false;
}
}
bool nex_creator::gt_on_sum_sum(const nex_sum& a, const nex_sum& b) const {
unsigned size = std::min(a.size(), b.size());
for (unsigned j = 0; j < size; j++) {
if (gt(a[j], b[j]))
return true;
if (gt(b[j], a[j]))
return false;
}
return a.size() > size;
}
// the only difference with gt() that it disregards the coefficient in nex_mul
bool nex_creator::gt_for_sort_join_sum(const nex* a, const nex* b) const {
TRACE("grobner_d_", tout << *a << " ? " << *b << "\n";);
if (a == b)
return false;
bool ret;
switch (a->type()) {
case expr_type::VAR:
ret = gt_on_var_nex(a->to_var(), *b);
break;
case expr_type::SCALAR:
if (b->is_scalar())
ret = a->to_scalar().value() > b->to_scalar().value();
else
ret = false; // the scalars are the largest
break;
case expr_type::MUL:
ret = gt_on_mul_nex(a->to_mul(), *b);
break;
case expr_type::SUM:
if (b->is_sum())
return gt_on_sum_sum(a->to_sum(), b->to_sum());
return gt(a->to_sum()[0], b);
default:
UNREACHABLE();
return false;
}
TRACE("grobner_d_", tout << *a << (ret?" < ":" >= ") << *b << "\n";);
return ret;
}
bool nex_creator::gt(const nex& a, const nex& b) const {
TRACE("grobner_d_", tout << a << " ? " << b << "\n";);
if (&a == &b)
return false;
bool ret;
switch (a.type()) {
case expr_type::VAR:
ret = gt_on_var_nex(a.to_var(), b);
break;
case expr_type::SCALAR:
ret = b.is_scalar() && a.to_scalar().value() > b.to_scalar().value();
// the scalars are the largest
break;
case expr_type::MUL:
ret = gt_on_mul_nex(a.to_mul(), b);
break;
case expr_type::SUM:
if (b.is_sum())
return gt_on_sum_sum(a.to_sum(), b.to_sum());
return gt(*a.to_sum()[0], b);
default:
UNREACHABLE();
return false;
}
TRACE("grobner_d_", tout << a << (ret?" < ":" >= ") << b << "\n";);
return ret;
}
bool nex_creator::is_sorted(const nex_mul& e) const {
for (unsigned j = 0; j < e.size() - 1; j++) {
if (!(gt_on_nex_pow(e[j], e[j+1]))) {
TRACE("grobner_d", tout << "not sorted e " << e << "\norder is incorrect " <<
e[j] << " >= " << e[j + 1]<< "\n";);
return false;
}
}
return true;
}
bool nex_creator::mul_is_simplified(const nex_mul& e) const {
TRACE("nla_cn_", tout << "e = " << e << "\n";);
if (e.size() == 0) {
TRACE("nla_cn", );
return false; // it has to be a scalar
}
if (e.size() == 1 && e.begin()->pow() == 1 && e.coeff().is_one()) {
TRACE("nla_cn", );
return false;
}
std::set<const nex*, nex_lt> s([this](const nex* a, const nex* b) {return gt(a, b); });
for (const auto &p : e) {
const nex* ee = p.e();
if (p.pow() == 0) {
TRACE("nla_cn", tout << "not simplified " << *ee << "\n";);
return false;
}
if (ee->is_mul()) {
TRACE("nla_cn", tout << "not simplified " << *ee << "\n";);
return false;
}
if (ee->is_scalar() && to_scalar(ee)->value().is_one()) {
TRACE("nla_cn", tout << "not simplified " << *ee << "\n";);
return false;
}
auto it = s.find(ee);
if (it == s.end()) {
s.insert(ee);
} else {
TRACE("nla_cn", tout << "not simplified " << *ee << "\n";);
return false;
}
}
return is_sorted(e);
}
nex * nex_creator::simplify_mul(nex_mul *e) {
TRACE("grobner_d", tout << *e << "\n";);
rational& coeff = e->m_coeff;
simplify_children_of_mul(e->m_children, coeff);
if (e->size() == 1 && (*e)[0].pow() == 1 && coeff.is_one())
return (*e)[0].e();
if (e->size() == 0 || e->coeff().is_zero())
return mk_scalar(e->coeff());
TRACE("grobner_d", tout << *e << "\n";);
SASSERT(is_simplified(*e));
return e;
}
nex* nex_creator::simplify_sum(nex_sum *e) {
TRACE("grobner_d", tout << "was e = " << *e << "\n";);
simplify_children_of_sum(*e);
nex *r;
if (e->size() == 1) {
r = const_cast<nex*>((*e)[0]);
} else if (e->size() == 0) {
r = mk_scalar(rational(0));
} else {
r = const_cast<nex_sum*>(e);
}
TRACE("grobner_d", tout << "became r = " << *r << "\n";);
return r;
}
bool nex_creator::sum_is_simplified(const nex_sum& e) const {
if (e.size() < 2) return false;
bool scalar = false;
for (nex const* ee : e) {
TRACE("nla_cn_details", tout << "ee = " << *ee << "\n";);
if (ee->is_sum()) {
TRACE("nla_cn", tout << "not simplified e = " << e << "\n"
<< " has a child which is a sum " << *ee << "\n";);
return false;
}
if (ee->is_scalar()) {
if (scalar) {
TRACE("nla_cn", tout << "not simplified e = " << e << "\n"
<< " have more than one scalar " << *ee << "\n";);
return false;
}
if (to_scalar(ee)->value().is_zero()) {
if (scalar) {
TRACE("nla_cn", tout << "have a zero scalar " << *ee << "\n";);
return false;
}
scalar = true;
}
}
if (!is_simplified(*ee))
return false;
}
return true;
}
void nex_creator::mul_to_powers(vector<nex_pow>& children) {
std::map<nex*, int, nex_lt> m([this](const nex* a, const nex* b) { return gt(a, b); });
for (auto & p : children) {
auto it = m.find(p.e());
if (it == m.end()) {
m[p.e()] = p.pow();
} else {
it->second += p.pow();
}
}
children.clear();
for (auto & p : m) {
children.push_back(nex_pow(p.first, p.second));
}
std::sort(children.begin(), children.end(), [this](const nex_pow& a, const nex_pow& b) {
return gt_on_nex_pow(a, b);
});
}
// returns true if the key exists already
bool nex_creator::register_in_join_map(std::map<nex const*, rational, nex_lt>& map, nex const* e, const rational& r) const{
TRACE("grobner_d", tout << *e << ", r = " << r << std::endl;);
auto map_it = map.find(e);
if (map_it == map.end()) {
map[e] = r;
TRACE("grobner_d", tout << "inserting " << std::endl;);
return false;
} else {
map_it->second += r;
TRACE("grobner_d", tout << "adding " << r << " , got " << map_it->second << std::endl;);
return true;
}
}
bool nex_creator::fill_join_map_for_sum(
nex_sum & sum,
std::map<nex const*, rational, nex_lt>& map,
std::unordered_set<nex const*>& existing_nex,
rational& common_scalar) {
bool simplified = false;
for (auto e : sum) {
if (e->is_scalar()) {
simplified = true;
common_scalar += e->to_scalar().value();
continue;
}
existing_nex.insert(e);
if (e->is_mul()) {
nex_mul const * m = to_mul(e);
simplified |= register_in_join_map(map, m, m->coeff());
} else {
SASSERT(e->is_var());
simplified |= register_in_join_map(map, e, rational(1));
}
}
return simplified;
}
// a + 3bc + 2bc => a + 5bc
void nex_creator::sort_join_sum(nex_sum& sum) {
TRACE("grobner_d", tout << sum << "\n";);
std::map<nex const*, rational, nex_lt> map([this](const nex *a , const nex *b)
{ return gt_for_sort_join_sum(a, b); });
std::unordered_set<nex const*> allocated_nexs; // handling (nex*) as numbers
rational common_scalar(0);
fill_join_map_for_sum(sum, map, allocated_nexs, common_scalar);
TRACE("grobner_d", for (auto & p : map ) { tout << "(" << *p.first << ", " << p.second << ") ";});
sum.m_children.reset();
for (auto& p : map) {
process_map_pair(const_cast<nex*>(p.first), p.second, sum, allocated_nexs);
}
if (!common_scalar.is_zero()) {
sum.m_children.push_back(mk_scalar(common_scalar));
}
TRACE("grobner_d",
tout << "map=";
for (auto & p : map ) tout << "(" << *p.first << ", " << p.second << ") ";
tout << "\nchildren=" << sum << "\n";);
}
void nex_creator::simplify_children_of_sum(nex_sum& s) {
ptr_vector<nex> to_promote;
unsigned k = 0;
for (unsigned j = 0; j < s.size(); j++) {
nex* e = s[j] = simplify(s[j]);
if (e->is_sum()) {
to_promote.push_back(e);
} else if (is_zero_scalar(e)) {
continue;
} else if (e->is_mul() && to_mul(e)->coeff().is_zero() ) {
continue;
} else {
s.m_children[k++] = e;
}
}
s.m_children.shrink(k);
for (nex *e : to_promote) {
for (nex const*ee : e->to_sum()) {
if (!is_zero_scalar(ee))
s.m_children.push_back(const_cast<nex*>(ee));
}
}
sort_join_sum(s);
}
bool nex_mul::all_factors_are_elementary() const {
for (auto & p : *this)
if (!p.e()->is_elementary())
return false;
return true;
}
nex * nex_creator::mk_div_sum_by_mul(const nex_sum& m, const nex_mul& b) {
sum_factory sf(*this);
for (auto e : m) {
sf += mk_div_by_mul(*e, b);
}
nex* r = sf.mk();
TRACE("grobner_d", tout << *r << "\n";);
return r;
}
nex * nex_creator::mk_div_mul_by_mul(const nex_mul& a, const nex_mul& b) {
SASSERT(a.all_factors_are_elementary() && b.all_factors_are_elementary());
b.get_powers_from_mul(m_powers);
m_mk_mul.reset();
for (auto& p_from_a : a) {
TRACE("grobner_d", tout << "p_from_a = " << p_from_a << "\n";);
const nex* e = p_from_a.e();
if (e->is_scalar()) {
m_mk_mul *= nex_pow(clone(e), p_from_a.pow());
TRACE("grobner_d", tout << "processed scalar\n";);
continue;
}
SASSERT(e->is_var());
lpvar j = to_var(e)->var();
auto it = m_powers.find(j);
if (it == m_powers.end()) {
m_mk_mul *= nex_pow(clone(e), p_from_a.pow());
} else {
unsigned pa = p_from_a.pow();
unsigned& pb = it->second;
SASSERT(pa);
if (pa > pb) {
m_mk_mul *= nex_pow(mk_var(j), pa - pb);
m_powers.erase(it);
} else if (pa == pb) {
m_powers.erase(it);
} else {
SASSERT(pa < pb);
// not adding the factor here, it was eaten by b,
// but the key j in m_powers remains
pb -= pa;
}
}
}
SASSERT(m_powers.size() == 0);
m_mk_mul *= (a.coeff() / b.coeff());
nex* ret = m_mk_mul.mk_reduced();
TRACE("grobner_d", tout << *ret << "\n";);
return ret;
}
nex * nex_creator::mk_div_by_mul(const nex& a, const nex_mul& b) {
SASSERT(!a.is_var() || (b.get_degree() == 1 && get_vars_of_expr(&a) == get_vars_of_expr(&b) && b.coeff().is_one()));
if (a.is_sum()) {
return mk_div_sum_by_mul(a.to_sum(), b);
}
if (a.is_var()) {
return mk_scalar(rational(1));
}
return mk_div_mul_by_mul(a.to_mul(), b);
}
nex * nex_creator::mk_div(const nex& a, const nex& b) {
TRACE("grobner_d", tout << a <<" / " << b << "\n";);
if (b.is_var()) {
return mk_div(a, b.to_var().var());
}
return mk_div_by_mul(a, b.to_mul());
}
nex* nex_creator::simplify(nex* e) {
nex* es;
TRACE("grobner_d", tout << *e << std::endl;);
if (e->is_mul())
es = simplify_mul(to_mul(e));
else if (e->is_sum())
es = simplify_sum(to_sum(e));
else
es = e;
TRACE("grobner_d", tout << "simplified = " << *es << std::endl;);
SASSERT(is_simplified(*es));
return es;
}
// adds to children the corrected expression and also adds to allocated the new expressions
void nex_creator::process_map_pair(nex*e, const rational& coeff, nex_sum & sum, std::unordered_set<nex const*>& allocated_nexs) {
TRACE("grobner_d", tout << "e=" << *e << " , coeff= " << coeff << "\n";);
if (coeff.is_zero()) {
TRACE("grobner_d", tout << "did nothing\n";);
return;
}
bool e_is_old = allocated_nexs.find(e) != allocated_nexs.end();
if (!e_is_old) {
add_to_allocated(e);
}
if (e->is_mul()) {
e->to_mul().m_coeff = coeff;
sum.m_children.push_back(simplify(e));
} else {
SASSERT(e->is_var());
if (coeff.is_one()) {
sum.m_children.push_back(e);
} else {
mul_factory mf(*this);
mf *= coeff;
mf *= e;
sum.m_children.push_back(mf.mk());
}
}
}
bool nex_creator::is_simplified(const nex& e) const {
TRACE("nla_cn_details", tout << "e = " << e << "\n";);
if (e.is_mul())
return mul_is_simplified(e.to_mul());
if (e.is_sum())
return sum_is_simplified(e.to_sum());
return true;
}
#ifdef Z3DEBUG
unsigned nex_creator::find_sum_in_mul(const nex_mul* a) const {
for (unsigned j = 0; j < a->size(); j++)
if ((*a)[j].e()->is_sum())
return j;
return -1;
}
nex* nex_creator::canonize_mul(nex_mul *a) {
TRACE("grobner_d", tout << "a = " << *a << "\n";);
unsigned j = find_sum_in_mul(a);
if (j + 1 == 0)
return a;
nex_pow& np = (*a)[j];
SASSERT(np.pow());
unsigned power = np.pow();
nex_sum const& s = np.e()->to_sum(); // s is going to explode
sum_factory sf(*this);
nex *sclone = power > 1 ? clone(&s) : nullptr;
for (nex const*e : s) {
mul_factory mf(*this);
if (power > 1)
mf *= nex_pow(sclone, power - 1);
mf *= nex_pow(e, 1);
for (unsigned k = 0; k < a->size(); k++) {
if (k == j)
continue;
mf *= nex_pow(clone((*a)[k].e()), (*a)[k].pow());
}
sf += mf.mk();
}
nex* r = sf.mk();
TRACE("grobner_d", tout << "canonized a = " << *r << "\n";);
return canonize(r);
}
nex* nex_creator::canonize(const nex *a) {
if (a->is_elementary())
return clone(a);
nex *t = simplify(clone(a));
if (t->is_sum()) {
nex_sum & s = t->to_sum();
for (unsigned j = 0; j < s.size(); j++) {
s[j] = canonize(s[j]);
}
t = simplify(&s);
TRACE("grobner_d", tout << *t << "\n";);
return t;
}
return canonize_mul(to_mul(t));
}
bool nex_creator::equal(const nex* a, const nex* b) {
TRACE("grobner_d", tout << *a << " against " << *b << "\n";);
nex_creator cn;
unsigned n = 0;
for (lpvar j : get_vars_of_expr(a)) {
n = std::max(j + 1, n);
}
for (lpvar j : get_vars_of_expr(b)) {
n = std::max(j + 1, n);
}
cn.set_number_of_vars(n);
for (lpvar j = 0; j < n; j++) {
cn.set_var_weight(j, j);
}
nex * ca = cn.canonize(a);
nex * cb = cn.canonize(b);
TRACE("grobner_d", tout << "a = " << *a << ", canonized a = " << *ca << "\n";);
TRACE("grobner_d", tout << "b = " << *b << ", canonized b = " << *cb << "\n";);
return !(cn.gt(ca, cb) || cn.gt(cb, ca));
}
#endif
| 30.746313 | 129 | 0.492804 | [
"vector"
] |
c1b67244496e5011c1a0d239c52e6fe565417ed6 | 3,228 | cpp | C++ | questions/49727462/assetlistmodel.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 302 | 2017-03-04T00:05:23.000Z | 2022-03-28T22:51:29.000Z | questions/49727462/assetlistmodel.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 30 | 2017-12-02T19:26:43.000Z | 2022-03-28T07:40:36.000Z | questions/49727462/assetlistmodel.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 388 | 2017-07-04T16:53:12.000Z | 2022-03-18T22:20:19.000Z | #include "assetlistmodel.h"
#include "nodemodel.h"
#include <QQmlContext>
AssetListModel::AssetListModel(QObject *parent) : QAbstractListModel(parent) {
model = new NodeModel{this};
}
void AssetListModel::register_objects(const QString &assetName,
const QString &nodeName,
QQmlContext *context) {
context->setContextProperty(assetName, this);
context->setContextProperty(nodeName, model);
}
bool AssetListModel::addAsset(QGeoCoordinate coord, int angle,
const QString &name) {
auto it =
std::find_if(mAssets.begin(), mAssets.end(),
[&](AssetItem const &obj) { return obj.name() == name; });
if (it != mAssets.end()) {
// append
int row = it - mAssets.begin();
QModelIndex ix = index(row);
QGeoCoordinate c = ix.data(AssetRole).value<QGeoCoordinate>();
int a = ix.data(AngleRole).toInt();
Data data{coord, angle};
bool result = setData(ix, QVariant::fromValue(data), AssetRole);
if (result)
model->appendNode(c, a);
return result;
}
return false;
}
bool AssetListModel::createAsset(QGeoCoordinate coord, const QColor &color,
const QString &name) {
beginInsertRows(QModelIndex(), rowCount(), rowCount());
AssetItem it;
it.setName(name);
it.setAsset(coord);
it.setColor(color);
mAssets << it;
endInsertRows();
return true;
}
int AssetListModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent)
return mAssets.count();
}
QVariant AssetListModel::data(const QModelIndex &index, int role) const {
if (!index.isValid())
return QVariant();
if (index.row() >= 0 && index.row() < rowCount()) {
const AssetItem &it = mAssets[index.row()];
if (role == NameRole)
return it.name();
else if (role == AssetRole)
return QVariant::fromValue(it.asset());
else if (role == HistoryRole) {
QVariantList history_list;
QList<QGeoCoordinate> coords = it.getHistory();
for (const QGeoCoordinate &coord : coords) {
history_list << QVariant::fromValue(coord);
}
history_list << QVariant::fromValue(it.asset());
return history_list;
} else if (role == ColorRole) {
return it.getColor();
} else if (role == AngleRole) {
return it.getAngle();
}
}
return QVariant();
}
QHash<int, QByteArray> AssetListModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[NameRole] = "nameData";
roles[AssetRole] = "assetData";
roles[HistoryRole] = "historyData";
roles[AngleRole] = "angleData";
roles[ColorRole] = "colorData";
return roles;
}
bool AssetListModel::setData(const QModelIndex &index, const QVariant &value,
int role) {
if (!index.isValid())
return false;
if (index.row() >= 0 && index.row() < rowCount()) {
if (role == AssetRole) {
const Data &data = value.value<Data>();
QGeoCoordinate new_asset(data.coord);
mAssets[index.row()].setAsset(new_asset);
mAssets[index.row()].setAngle(data.angle);
emit dataChanged(index, index, QVector<int>{AssetRole});
return true;
}
}
return false;
}
| 30.45283 | 78 | 0.627014 | [
"model"
] |
c1b83f4ea01582ca94dc9006281cd3aa97554d90 | 2,360 | hpp | C++ | src/viterbi_baseline.hpp | mjgerdes/paraterbi | 914c5430fc053788812cc5da7465b637de22458e | [
"MIT"
] | null | null | null | src/viterbi_baseline.hpp | mjgerdes/paraterbi | 914c5430fc053788812cc5da7465b637de22458e | [
"MIT"
] | null | null | null | src/viterbi_baseline.hpp | mjgerdes/paraterbi | 914c5430fc053788812cc5da7465b637de22458e | [
"MIT"
] | 1 | 2018-12-05T03:31:49.000Z | 2018-12-05T03:31:49.000Z |
#ifndef __VITERBI_BASELINE_HPP__
#define __VITERBI_BASELINE_HPP__
#include "utility.hpp"
#include <iostream>
#include <algorithm>
#include <vector>
template <typename probability_T, template <typename> class matrix_T>
class Viterbi {
public:
using Label_type = int;
using Emission_type = int;
using Probability_type = probability_T;
using Matrix_type = matrix_T<Probability_type>;
struct Model {
using Label_type = Label_type;
using Emission_type = Emission_type;
using Probability_type = Probability_type;
using Matrix_type = Matrix_type;
std::vector<Probability_type> start;
Matrix_type transitions;
Matrix_type emissions;
Model() = delete;
Model(int labels, int emissions, Probability_type defaultValue) : start(labels, defaultValue), transitions(labels, labels, defaultValue), emissions(labels, emissions, defaultValue) {}
}; // end class Model
public:
Viterbi() = delete;
Viterbi(const Model& m) : m_model(m) {}
Viterbi(Model&& m) : m_model(std::move(m)) {}
std::vector<Label_type> infer(std::vector<Emission_type> ts) {
auto labelCount = m_model.start.size();
auto trellis = Matrix_type(labelCount, ts.size(), log(0));
auto backpointers = matrix_T<int>(labelCount, ts.size(), 0);
for (auto i = 0; i < labelCount; ++i) {
trellis(i, 0) = m_model.start[i] + m_model.emissions(i, ts[0]);
}
for (auto j = 1; j < ts.size(); ++j) {
for (auto i = 0; i < labelCount; ++i) {
auto winner =
std::make_pair<Probability_type, Label_type>(log(0.0), 0);
auto candidate = winner;
for (auto prev = 0; prev < labelCount; ++prev) {
candidate.first = trellis(prev, j - 1) +
m_model.transitions(prev, i) +
m_model.emissions(i, ts[j]);
candidate.second = prev;
winner = std::max(winner, candidate);
}
trellis(i, j) = winner.first;
backpointers(i, j) = winner.second;
}
}
auto best = std::vector<Label_type>(ts.size(), 0);
auto tmp = std::make_pair<Probability_type, Label_type>(log(0.0), 0);
for (auto i = 0; i < labelCount; ++i) {
tmp = std::max(tmp, std::make_pair(trellis(i, ts.size() - 1), i));
}
best[ts.size() - 1] = tmp.second;
for (auto j = ts.size() - 1; j > 0; --j) {
best[j - 1] = backpointers(best[j], j);
}
return std::move(best);
} // end infer
private:
Model m_model;
}; // end class Viterbi
#endif
| 27.126437 | 185 | 0.661017 | [
"vector",
"model"
] |
c1bbdea862e463dc8c0828c1a0111b32a473b03f | 23,342 | hpp | C++ | src/sparse/impl/KokkosSparse_spgemm_mkl_impl.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 156 | 2017-03-01T23:38:10.000Z | 2022-03-27T21:28:03.000Z | src/sparse/impl/KokkosSparse_spgemm_mkl_impl.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 1,257 | 2017-03-03T15:25:16.000Z | 2022-03-31T19:46:09.000Z | src/sparse/impl/KokkosSparse_spgemm_mkl_impl.hpp | dialecticDolt/kokkos-kernels | 00189c0be23a70979aeaa162f0abd4c0e4d1c479 | [
"BSD-3-Clause"
] | 76 | 2017-03-01T17:03:59.000Z | 2022-03-03T21:04:41.000Z | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation 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 NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef _KOKKOSSPGEMMMKL_HPP
#define _KOKKOSSPGEMMMKL_HPP
#ifdef KOKKOSKERNELS_ENABLE_TPL_MKL
#include "mkl_spblas.h"
#include "mkl.h"
#endif
#include "KokkosKernels_Utils.hpp"
#include <Kokkos_Concepts.hpp>
namespace KokkosSparse{
namespace Impl{
template <typename KernelHandle,
typename in_row_index_view_type,
typename in_nonzero_index_view_type,
typename bin_row_index_view_type,
typename bin_nonzero_index_view_type,
typename cin_row_index_view_type>
void mkl_symbolic(
KernelHandle *handle,
typename KernelHandle::nnz_lno_t m,
typename KernelHandle::nnz_lno_t n,
typename KernelHandle::nnz_lno_t k,
in_row_index_view_type row_mapA,
in_nonzero_index_view_type entriesA,
bool transposeA,
bin_row_index_view_type row_mapB,
bin_nonzero_index_view_type entriesB,
bool transposeB,
cin_row_index_view_type row_mapC,
bool verbose = false){
#ifdef KOKKOSKERNELS_ENABLE_TPL_MKL
typedef typename KernelHandle::nnz_lno_t idx;
typedef typename KernelHandle::size_type size_type;
typedef typename KernelHandle::HandleTempMemorySpace HandleTempMemorySpace;
typedef typename Kokkos::View<int *, HandleTempMemorySpace> int_temp_work_view_t;
typedef typename KernelHandle::nnz_scalar_t value_type;
typedef typename KernelHandle::HandleExecSpace MyExecSpace;
/*
if (!(
(Kokkos::Impl::SpaceAccessibility<typename Kokkos::HostSpace::execution_space, typename device1::memory_space>::accessible) &&
(Kokkos::Impl::SpaceAccessibility<typename Kokkos::HostSpace::execution_space, typename device2::memory_space>::accessible) &&
(Kokkos::Impl::SpaceAccessibility<typename Kokkos::HostSpace::execution_space, typename device3::memory_space>::accessible) )
){
throw std::runtime_error ("MEMORY IS NOT ALLOCATED IN HOST DEVICE for MKL\n");
return;
}
*/
if (std::is_same<idx, int>::value){
int *a_xadj = NULL;
int *b_xadj = NULL;
int_temp_work_view_t a_xadj_v, b_xadj_v;
if (std::is_same<size_type, int>::value){
a_xadj = (int *)row_mapA.data();
b_xadj = (int *)row_mapB.data();
}
else {
//TODO test this case.
Kokkos::Impl::Timer copy_time;
const int max_integer = 2147483647;
if (entriesB.extent(0) > max_integer|| entriesA.extent(0) > max_integer){
throw std::runtime_error ("MKL requires integer values for size type for SPGEMM. Copying to integer will cause overflow.\n");
return;
}
a_xadj_v = int_temp_work_view_t("tmpa", m + 1);
a_xadj = (int *) a_xadj_v.data();
b_xadj_v = int_temp_work_view_t("tmpb", n + 1);
b_xadj = (int *) b_xadj_v.data();
KokkosKernels::Impl::copy_vector<
in_row_index_view_type,
int_temp_work_view_t,
MyExecSpace> (m+1, row_mapA, a_xadj_v);
KokkosKernels::Impl::copy_vector<
bin_row_index_view_type,
int_temp_work_view_t,
MyExecSpace> (m+1, row_mapB, b_xadj_v);
if (verbose)
std::cout << "MKL COPY size type to int TIME:" << copy_time.seconds() << std::endl;
}
int *a_adj = (int *)entriesA.data();
int *b_adj = (int *)entriesB.data();
std::vector <value_type> tmp_values (KOKKOSKERNELS_MACRO_MAX(entriesB.extent(0), entriesA.extent(0)));
value_type *ptmp_values = &(tmp_values[0]);
value_type *a_ew = ptmp_values;
value_type *b_ew = ptmp_values;
sparse_matrix_t A;
sparse_matrix_t B;
sparse_matrix_t C;
if (std::is_same<value_type, float>::value){
if (SPARSE_STATUS_SUCCESS != mkl_sparse_s_create_csr (&A, SPARSE_INDEX_BASE_ZERO, m, n, a_xadj, a_xadj + 1, a_adj, (float *)a_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr A matrix\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_s_create_csr (&B, SPARSE_INDEX_BASE_ZERO, n, k, b_xadj, b_xadj + 1, b_adj, (float *)b_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr B matrix\n");
return;
}
sparse_operation_t operation;
if (transposeA && transposeB){
operation = SPARSE_OPERATION_TRANSPOSE;
}
else if (!(transposeA || transposeB)){
operation = SPARSE_OPERATION_NON_TRANSPOSE;
}
else {
throw std::runtime_error ("MKL either transpose both matrices, or none for SPGEMM\n");
return;
}
Kokkos::Impl::Timer timer1;
bool success = SPARSE_STATUS_SUCCESS != mkl_sparse_spmm (operation, A, B, &C);
if (verbose)
std::cout << "Actual FLOAT MKL SPMM Time in symbolic:" << timer1.seconds() << std::endl;
if (success){
throw std::runtime_error ("ERROR at SPGEMM multiplication in mkl_sparse_spmm\n");
return;
}
else{
sparse_index_base_t c_indexing;
MKL_INT c_rows, c_cols, *rows_start, *rows_end, *columns;
float *values;
if (SPARSE_STATUS_SUCCESS !=
mkl_sparse_s_export_csr (C,
&c_indexing, &c_rows, &c_cols, &rows_start, &rows_end, &columns, &values)){
throw std::runtime_error ("ERROR at exporting result matrix in mkl_sparse_spmm\n");
return;
}
if (SPARSE_INDEX_BASE_ZERO != c_indexing){
throw std::runtime_error ("C is not zero based indexed\n");
return;
}
KokkosKernels::Impl::copy_vector<MKL_INT *, typename cin_row_index_view_type::non_const_type, MyExecSpace> (m, rows_start, row_mapC);
idx nnz = row_mapC(m) = rows_end[m - 1];
handle->set_c_nnz(nnz);
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (A)){
throw std::runtime_error ("Error at mkl_sparse_destroy A\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (B)){
throw std::runtime_error ("Error at mkl_sparse_destroy B\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (C)){
throw std::runtime_error ("Error at mkl_sparse_destroy C\n");
return;
}
}
else if (std::is_same<value_type, double>::value){
/*
std::cout << "create a" << std::endl;
std::cout << "m:" << m << " n:" << n << std::endl;
std::cout << "a_xadj[0]:" << a_xadj[0] << " a_xadj[m]:" << a_xadj[m] << std::endl;
std::cout << "a_adj[a_xadj[m] - 1]:" << a_adj[a_xadj[m] - 1] << " a_ew[a_xadj[m] - 1]:" << a_ew[a_xadj[m] - 1] << std::endl;
*/
if (SPARSE_STATUS_SUCCESS != mkl_sparse_d_create_csr (&A, SPARSE_INDEX_BASE_ZERO, m, n, a_xadj, a_xadj + 1, a_adj, (double *)a_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr A matrix\n");
return;
}
//std::cout << "create b" << std::endl;
if (SPARSE_STATUS_SUCCESS != mkl_sparse_d_create_csr (&B, SPARSE_INDEX_BASE_ZERO, n, k, b_xadj, b_xadj + 1, b_adj, (double *) b_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr B matrix\n");
return;
}
sparse_operation_t operation;
if (transposeA && transposeB){
operation = SPARSE_OPERATION_TRANSPOSE;
}
else if (!(transposeA || transposeB)){
operation = SPARSE_OPERATION_NON_TRANSPOSE;
}
else {
throw std::runtime_error ("MKL either transpose both matrices, or none for SPGEMM\n");
return;
}
Kokkos::Impl::Timer timer1;
bool success = SPARSE_STATUS_SUCCESS != mkl_sparse_spmm (operation, A, B, &C);
if (verbose)
std::cout << "Actual DOUBLE MKL SPMM Time Without Free:" << timer1.seconds() << std::endl;
mkl_free_buffers();
if (verbose)
std::cout << "Actual DOUBLE MKL SPMM Time:" << timer1.seconds() << std::endl;
if (success){
throw std::runtime_error ("ERROR at SPGEMM multiplication in mkl_sparse_spmm\n");
return;
}
else{
sparse_index_base_t c_indexing;
MKL_INT c_rows, c_cols, *rows_start, *rows_end, *columns;
double *values;
if (SPARSE_STATUS_SUCCESS !=
mkl_sparse_d_export_csr (C,
&c_indexing, &c_rows, &c_cols, &rows_start, &rows_end, &columns, &values)){
throw std::runtime_error ("ERROR at exporting result matrix in mkl_sparse_spmm\n");
return;
}
if (SPARSE_INDEX_BASE_ZERO != c_indexing){
throw std::runtime_error ("C is not zero based indexed\n");
return;
}
if (handle->mkl_keep_output)
{
Kokkos::Impl::Timer copy_time;
KokkosKernels::Impl::copy_vector<MKL_INT *, typename cin_row_index_view_type::non_const_type, MyExecSpace> (m, rows_start, row_mapC);
idx nnz = row_mapC(m) = rows_end[m - 1];
handle->set_c_nnz(nnz);
double copy_time_d = copy_time.seconds();
if (verbose)
std::cout << "MKL COPYTIME:" << copy_time_d << std::endl;
}
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (A)){
throw std::runtime_error ("Error at mkl_sparse_destroy A\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (B)){
throw std::runtime_error ("Error at mkl_sparse_destroy B\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (C)){
throw std::runtime_error ("Error at mkl_sparse_destroy C\n");
return;
}
}
else {
throw std::runtime_error ("MKL requires float or double values. Complex values are not implemented yet.\n");
return;
}
}
else {
throw std::runtime_error ("MKL requires local ordinals to be integer.\n");
return;
}
#else
(void)handle;
(void)m; (void)n; (void)k;
(void)row_mapA; (void)row_mapB; (void)row_mapC;
(void)entriesA; (void)entriesB;
(void)transposeA; (void)transposeB;
(void)verbose;
throw std::runtime_error ("MKL IS NOT DEFINED\n");
//return;
#endif
}
template <typename KernelHandle,
typename in_row_index_view_type,
typename in_nonzero_index_view_type,
typename in_nonzero_value_view_type,
typename bin_row_index_view_type,
typename bin_nonzero_index_view_type,
typename bin_nonzero_value_view_type,
typename cin_row_index_view_type,
typename cin_nonzero_index_view_type,
typename cin_nonzero_value_view_type>
void mkl_apply(
KernelHandle *handle,
typename KernelHandle::nnz_lno_t m,
typename KernelHandle::nnz_lno_t n,
typename KernelHandle::nnz_lno_t k,
in_row_index_view_type row_mapA,
in_nonzero_index_view_type entriesA,
in_nonzero_value_view_type valuesA,
bool transposeA,
bin_row_index_view_type row_mapB,
bin_nonzero_index_view_type entriesB,
bin_nonzero_value_view_type valuesB,
bool transposeB,
cin_row_index_view_type row_mapC,
cin_nonzero_index_view_type entriesC,
cin_nonzero_value_view_type valuesC,
bool verbose = false){
#ifdef KOKKOSKERNELS_ENABLE_TPL_MKL
typedef typename KernelHandle::nnz_lno_t idx;
typedef typename KernelHandle::size_type size_type;
typedef typename KernelHandle::HandleTempMemorySpace HandleTempMemorySpace;
typedef typename Kokkos::View<int *, HandleTempMemorySpace> int_temp_work_view_t;
typedef typename KernelHandle::nnz_scalar_t value_type;
typedef typename KernelHandle::HandleExecSpace MyExecSpace;
/*
if (!(
(Kokkos::Impl::SpaceAccessibility<typename Kokkos::HostSpace::execution_space, typename device1::memory_space>::accessible) &&
(Kokkos::Impl::SpaceAccessibility<typename Kokkos::HostSpace::execution_space, typename device2::memory_space>::accessible) &&
(Kokkos::Impl::SpaceAccessibility<typename Kokkos::HostSpace::execution_space, typename device3::memory_space>::accessible) )
){
throw std::runtime_error ("MEMORY IS NOT ALLOCATED IN HOST DEVICE for MKL\n");
return;
}
*/
if (std::is_same<idx, int>::value){
int *a_xadj = NULL;
int *b_xadj = NULL;
int_temp_work_view_t a_xadj_v, b_xadj_v;
if (std::is_same<size_type, int>::value){
a_xadj = (int *)row_mapA.data();
b_xadj = (int *)row_mapB.data();
}
else {
//TODO test this case.
Kokkos::Impl::Timer copy_time;
const int max_integer = 2147483647;
if (entriesB.extent(0) > max_integer|| entriesA.extent(0) > max_integer){
throw std::runtime_error ("MKL requires integer values for size type for SPGEMM. Copying to integer will cause overflow.\n");
return;
}
a_xadj_v = int_temp_work_view_t("tmpa", m + 1);
a_xadj = (int *) a_xadj_v.data();
b_xadj_v = int_temp_work_view_t("tmpb", n + 1);
b_xadj = (int *) b_xadj_v.data();
KokkosKernels::Impl::copy_vector<
in_row_index_view_type,
int_temp_work_view_t,
MyExecSpace> (m+1, row_mapA, a_xadj_v);
KokkosKernels::Impl::copy_vector<
bin_row_index_view_type,
int_temp_work_view_t,
MyExecSpace> (m+1, row_mapB, b_xadj_v);
if (verbose)
std::cout << "MKL COPY size type to int TIME:" << copy_time.seconds() << std::endl;
}
int *a_adj = (int *)entriesA.data();
int *b_adj = (int *)entriesB.data();
const value_type *a_ew = valuesA.data();
const value_type *b_ew = valuesB.data();
sparse_matrix_t A;
sparse_matrix_t B;
sparse_matrix_t C;
if (std::is_same<value_type, float>::value){
if (SPARSE_STATUS_SUCCESS != mkl_sparse_s_create_csr (&A, SPARSE_INDEX_BASE_ZERO, m, n, a_xadj, a_xadj + 1, a_adj, (float *)a_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr A matrix\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_s_create_csr (&B, SPARSE_INDEX_BASE_ZERO, n, k, b_xadj, b_xadj + 1, b_adj, (float *)b_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr B matrix\n");
return;
}
sparse_operation_t operation;
if (transposeA && transposeB){
operation = SPARSE_OPERATION_TRANSPOSE;
}
else if (!(transposeA || transposeB)){
operation = SPARSE_OPERATION_NON_TRANSPOSE;
}
else {
throw std::runtime_error ("MKL either transpose both matrices, or none for SPGEMM\n");
return;
}
Kokkos::Impl::Timer timer1;
bool success = SPARSE_STATUS_SUCCESS != mkl_sparse_spmm (operation, A, B, &C);
if (verbose)
std::cout << "Actual FLOAT MKL SPMM Time:" << timer1.seconds() << std::endl;
if (success){
throw std::runtime_error ("ERROR at SPGEMM multiplication in mkl_sparse_spmm\n");
return;
}
else{
sparse_index_base_t c_indexing;
MKL_INT c_rows, c_cols, *rows_start, *rows_end, *columns;
float *values;
if (SPARSE_STATUS_SUCCESS !=
mkl_sparse_s_export_csr (C,
&c_indexing, &c_rows, &c_cols, &rows_start, &rows_end, &columns, &values)){
throw std::runtime_error ("ERROR at exporting result matrix in mkl_sparse_spmm\n");
return;
}
if (SPARSE_INDEX_BASE_ZERO != c_indexing){
throw std::runtime_error ("C is not zero based indexed\n");
return;
}
//KokkosKernels::Impl::copy_vector<MKL_INT *, typename cin_row_index_view_type::non_const_type, MyExecSpace> (m, rows_start, row_mapC);
//idx nnz = row_mapC(m) = rows_end[m - 1];
idx nnz = rows_end[m - 1];
using non_const_size_type = typename cin_row_index_view_type::non_const_value_type;
auto* tmpPtr = const_cast<non_const_size_type*>(row_mapC.data());
tmpPtr[m] = nnz;
KokkosKernels::Impl::copy_vector<MKL_INT *, typename cin_nonzero_index_view_type::non_const_type , MyExecSpace> (nnz, columns, entriesC);
KokkosKernels::Impl::copy_vector<float *, typename cin_nonzero_value_view_type::non_const_type, MyExecSpace> (nnz, values, valuesC);
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (A)){
throw std::runtime_error ("Error at mkl_sparse_destroy A\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (B)){
throw std::runtime_error ("Error at mkl_sparse_destroy B\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (C)){
throw std::runtime_error ("Error at mkl_sparse_destroy C\n");
return;
}
}
else if (std::is_same<value_type, double>::value){
/*
std::cout << "create a" << std::endl;
std::cout << "m:" << m << " n:" << n << std::endl;
std::cout << "a_xadj[0]:" << a_xadj[0] << " a_xadj[m]:" << a_xadj[m] << std::endl;
std::cout << "a_adj[a_xadj[m] - 1]:" << a_adj[a_xadj[m] - 1] << " a_ew[a_xadj[m] - 1]:" << a_ew[a_xadj[m] - 1] << std::endl;
*/
if (SPARSE_STATUS_SUCCESS != mkl_sparse_d_create_csr (&A, SPARSE_INDEX_BASE_ZERO, m, n, a_xadj, a_xadj + 1, a_adj, ( double *)a_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr A matrix\n");
return;
}
//std::cout << "create b" << std::endl;
if (SPARSE_STATUS_SUCCESS != mkl_sparse_d_create_csr (&B, SPARSE_INDEX_BASE_ZERO, n, k, b_xadj, b_xadj + 1, b_adj, ( double *) b_ew)){
throw std::runtime_error ("CANNOT CREATE mkl_sparse_s_create_csr B matrix\n");
return;
}
sparse_operation_t operation;
if (transposeA && transposeB){
operation = SPARSE_OPERATION_TRANSPOSE;
}
else if (!(transposeA || transposeB)){
operation = SPARSE_OPERATION_NON_TRANSPOSE;
}
else {
throw std::runtime_error ("MKL either transpose both matrices, or none for SPGEMM\n");
return;
}
Kokkos::Impl::Timer timer1;
bool success = SPARSE_STATUS_SUCCESS != mkl_sparse_spmm (operation, A, B, &C);
if (verbose)
std::cout << "Actual DOUBLE MKL SPMM Time Without Free:" << timer1.seconds() << std::endl;
mkl_free_buffers();
if (verbose)
std::cout << "Actual DOUBLE MKL SPMM Time:" << timer1.seconds() << std::endl;
if (success){
throw std::runtime_error ("ERROR at SPGEMM multiplication in mkl_sparse_spmm\n");
return;
}
else{
sparse_index_base_t c_indexing;
MKL_INT c_rows, c_cols, *rows_start, *rows_end, *columns;
double *values;
if (SPARSE_STATUS_SUCCESS !=
mkl_sparse_d_export_csr (C,
&c_indexing, &c_rows, &c_cols, &rows_start, &rows_end, &columns, &values)){
throw std::runtime_error ("ERROR at exporting result matrix in mkl_sparse_spmm\n");
return;
}
if (SPARSE_INDEX_BASE_ZERO != c_indexing){
throw std::runtime_error ("C is not zero based indexed\n");
return;
}
if (handle->mkl_keep_output)
{
Kokkos::Impl::Timer copy_time;
//KokkosKernels::Impl::copy_vector<MKL_INT *, typename cin_row_index_view_type::non_const_type, MyExecSpace> (m, rows_start, row_mapC);
//idx nnz = row_mapC(m) = rows_end[m - 1];
idx nnz = rows_end[m - 1];
using non_const_size_type = typename cin_row_index_view_type::non_const_value_type;
auto* tmpPtr = const_cast<non_const_size_type*>(row_mapC.data());
tmpPtr[m] = nnz;
KokkosKernels::Impl::copy_vector<MKL_INT *, typename cin_nonzero_index_view_type::non_const_type, MyExecSpace> (nnz, columns, entriesC);
KokkosKernels::Impl::copy_vector<double *, typename cin_nonzero_value_view_type::non_const_type, MyExecSpace> (nnz, values, valuesC);
double copy_time_d = copy_time.seconds();
if (verbose)
std::cout << "MKL COPYTIME:" << copy_time_d << std::endl;
}
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (A)){
throw std::runtime_error ("Error at mkl_sparse_destroy A\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (B)){
throw std::runtime_error ("Error at mkl_sparse_destroy B\n");
return;
}
if (SPARSE_STATUS_SUCCESS != mkl_sparse_destroy (C)){
throw std::runtime_error ("Error at mkl_sparse_destroy C\n");
return;
}
}
else {
throw std::runtime_error ("MKL requires float or double values. Complex values are not implemented yet.\n");
return;
}
}
else {
throw std::runtime_error ("MKL requires local ordinals to be integer.\n");
return;
}
#else
(void)handle;
(void)m; (void)n; (void)k;
(void)row_mapA; (void)row_mapB; (void)row_mapC;
(void)entriesA; (void)entriesB; (void)entriesC;
(void)valuesA; (void)valuesB; (void)valuesC;
(void)transposeA; (void)transposeB;
(void)verbose;
throw std::runtime_error ("MKL IS NOT DEFINED\n");
//return;
#endif
}
}
}
#endif
| 33.828986 | 148 | 0.637777 | [
"vector"
] |
c1c646cb10fab4d4266423be472456372d5b5f10 | 5,518 | cpp | C++ | networking/client.cpp | firngrod/firnlibs | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | [
"MIT"
] | null | null | null | networking/client.cpp | firngrod/firnlibs | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | [
"MIT"
] | null | null | null | networking/client.cpp | firngrod/firnlibs | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | [
"MIT"
] | null | null | null | #include "networking.hpp"
#ifdef __GNUC__
#include "unistd.h"
#endif
#include <iostream>
namespace FirnLibs {
Networking::Client::Client() :
sharedThis(new FirnLibs::Threading::GuardedVar<Client *>(this))
{
identifier = 0;
limboState = nullptr;
errorNo = 0;
}
Networking::Client::~Client()
{
{
auto token = sharedThis->Get("Client deconstructor");
token = nullptr;
}
if (limboState != nullptr)
{
#ifdef _MSC_VER
FirnLibs::Networking::GetInstance().
#endif
close(limboState->fd);
delete (sockaddr *)limboState->pAddr;
delete limboState;
}
else
{
Networking::GetInstance().SignalCloseSocket(identifier);
identifier = 0;
}
}
void Networking::Client::Commence(const std::function<void (const std::vector<unsigned char> &)> callback,
const std::function<void (const int &)> errorCallback)
{
// Sanity check
//if(callback == nullptr)
//return false;
// Save the identifier.
identifier = limboState->identifier;
// Save the callbacks.
this->callback = callback;
this->errorCallback = errorCallback;
// Message the socket to the polldancer
// Notice that we intercept the callback to do buffering and data interc...
// We do data treatment in this class before signalling the user.
// For their convenience. Nothing sinister.
auto sharedCpy = new std::shared_ptr<FirnLibs::Threading::GuardedVar<Client *> >(sharedThis);
auto lambda = [sharedCpy](const std::vector<unsigned char> &message) -> void
{
auto token = (*sharedCpy)->Get("Client data callback");
if((Client *)token != nullptr)
((Client *)token)->HandleIncData(message);
};
auto errorLambda = [sharedCpy](const int &errorNo) -> void
{
auto token = (*sharedCpy)->Get("Client error callback");
if((Client *)token != nullptr)
{
((Client *)token)->ErrorCallback(errorNo);
}
};
auto cleanupLambda = [sharedCpy]() -> void
{
// When this reaches the front of the queue, all callbacks on this class are either done or in progress.
// If we wait until we can lock, we should be good.
// This may still be capable of breakage if two threads start "simultaneously" and the other one gets the lock first.
{
auto token = (*sharedCpy)->Get("Client cleanup callback");
}
delete sharedCpy;
};
limboState->msg = ConnectionAdd;
limboState->pCallback = (void *) new std::function<void (const std::vector<unsigned char> &)>(lambda);
limboState->pErrorCallback = new std::function<void (const int &)>(errorLambda);
limboState->pCleanupCallback = new std::function<void ()>(cleanupLambda);
Networking::GetInstance().SignalSocket(*limboState);
// Clean up.
// NOTICE: Do not delete the addr. It will be deleted by the polldancer.
delete limboState;
limboState = nullptr;
}
void Networking::Client::HandleIncData(const std::vector<unsigned char> &data)
{
if(callback != nullptr)
callback(data);
}
void Networking::Client::ErrorCallback(const int &errorNo)
{
// If this has been called, something is wrong.
this->errorNo = errorNo;
this->identifier = identifier;
// If they gave us a callback method, relay
if(errorCallback != nullptr)
errorCallback(errorNo);
}
void Networking::Client::Send(const std::vector<unsigned char> &data)
{
auto lock = sharedThis->Get("Client Send");
PipeMessagePack messagePack;
messagePack.identifier = identifier;
messagePack.msg = ConnectionQueueData;
messagePack.pDataBuf = new std::vector<unsigned char>(data);
Networking::GetInstance().SignalSocket(messagePack);
}
bool Networking::Client::Connect(const int &port, const std::string &address, const std::string &localAddress,
const std::function<void (const std::vector<unsigned char> &)> &callback,
const std::function<void (const int &)> &errorCallback)
{
auto lock = sharedThis->Get("Client connect");
if(identifier != 0)
return false;
// Message the socket to the polldancer
// Notice that we intercept the callback to do buffering and data interc...
// We do data treatment in this class before signalling the user.
// For their convenience. Nothing sinister.
auto sharedCpy = new std::shared_ptr<FirnLibs::Threading::GuardedVar<Client *> >(sharedThis);
auto lambda = [sharedCpy](const std::vector<unsigned char> &message) -> void
{
auto token = (*sharedCpy)->Get("Client Connect data callback");
if((Client *)token != nullptr)
((Client *)token)->HandleIncData(message);
};
auto errorLambda = [sharedCpy](const int &errorNo) -> void
{
auto token = (*sharedCpy)->Get("Client Connect error callback");
if((Client *)token != nullptr)
{
((Client *)token)->ErrorCallback(errorNo);
}
};
auto cleanupLambda = [sharedCpy]() -> void
{
// When this reaches the front of the queue, all callbacks on this class are either done or in progress.
// If we wait until we can lock, we should be good.
// This may still be capable of breakage if two threads start "simultaneously" and the other one gets the lock first.
{
auto token = (*sharedCpy)->Get("Client Connect cleanup callback");
}
delete sharedCpy;
};
identifier = Networking::GetInstance().ConnectTCP(port, address, localAddress, callback, errorCallback, cleanupLambda);
if(identifier == 0)
return false;
this->callback = callback;
this->errorCallback = errorCallback;
return true;
}
}
| 30.655556 | 121 | 0.67597 | [
"vector"
] |
c1ce83ab732414685b2e287aec7e313521064042 | 8,074 | cpp | C++ | src/mesh/NetworkData.cpp | payano/mMesh | 151ab475ad6ea66a608566098755dbad39eca058 | [
"MIT"
] | null | null | null | src/mesh/NetworkData.cpp | payano/mMesh | 151ab475ad6ea66a608566098755dbad39eca058 | [
"MIT"
] | 37 | 2020-03-02T18:31:57.000Z | 2020-05-20T07:18:14.000Z | src/mesh/NetworkData.cpp | payano/mMesh | 151ab475ad6ea66a608566098755dbad39eca058 | [
"MIT"
] | 2 | 2020-03-10T17:35:27.000Z | 2020-04-24T10:51:47.000Z | /*
MIT License
Copyright (c) 2020 Johan Svensson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "NetworkData.h"
#include "SyscallsInterface.h"
namespace mesh {
NetworkData::NetworkData(syscalls::SyscallsInterface *syscalls) {
this->syscalls = syscalls;
syscalls::SyscallsInterface::mem_clr(&mac, sizeof(mac));
syscalls::SyscallsInterface::mem_clr(&parent.mac, sizeof(parent.mac));
pairedChildren = 0;
pairedNeighbours = 0;
registeredToMaster = false;
mPaired = false;
buffer_count = 0;
for(int i = 0 ; i < CHILDREN_SZ; ++i) {
syscalls::SyscallsInterface::mem_clr(&childs[i], sizeof(childs[i]));
}
for(int i = 0 ; i < NEIGHBOUR_SZ; ++i) {
syscalls::SyscallsInterface::mem_clr(&neighbours[i], sizeof(neighbours[i]));
}
// TODO Auto-generated constructor stub
}
NetworkData::~NetworkData() {
// TODO Auto-generated destructor stub
}
int NetworkData::queue_sz() { return buffer_count; }
void NetworkData::queue_clear(){buffer_count = 0;}
int NetworkData::queue_add(union mesh_internal_msg *msg)
{
if(buffer_count >= MSG_BUFFER) return -1;
syscalls::SyscallsInterface::copy_data(&queuedmsgs[buffer_count++], msg, sizeof(*msg));
return 0;
}
int NetworkData::queue_get(union mesh_internal_msg *msg)
{
/* take first one, move all one stop the the left in the queue
* for example: [1] -> [0]
*/
if(buffer_count <= 0) return 1;
syscalls::SyscallsInterface::copy_data(msg, &queuedmsgs[0], sizeof(*msg));
buffer_count--;
for(int i = 0 ; i < buffer_count; ++i) {
syscalls::SyscallsInterface::copy_data(&queuedmsgs[i], &queuedmsgs[i+1], sizeof(queuedmsgs[i]));
}
queuedmsgs[buffer_count].header.msgno = MSGNO::INVALID;
return 0;
}
int NetworkData::remove_child_node(struct node_data *node,
struct net_address *disband_node)
{
struct node_data *child = childs;
for(int i = 0; i < CHILDREN_SZ; ++i, child++) {
// NEEDED?
if(false == child->connected) continue;
if(syscalls::SyscallsInterface::cmp_data(&node->mac, &child->mac, sizeof(node->mac))) continue;
syscalls::SyscallsInterface::mem_clr(disband_node, sizeof(*disband_node));
syscalls::SyscallsInterface::copy_data(disband_node, &child->mac, sizeof(child->mac));
child->keepalive_count = 0;
syscalls::SyscallsInterface::mem_clr(&child->mac, sizeof(child->mac));
child->connected = false;
pairedChildren--;
return 0;
}
return -1;
}
void NetworkData::decrease_parent_timer(uint value)
{
if(parent.keepalive_count <= 0){
parent.keepalive_count = 0;
return;
}
parent.keepalive_count -= value;
}
void NetworkData::decrease_child_timers(uint value)
{
struct node_data *nwd_child = childs;
for(int i = 0; i < CHILDREN_SZ; ++i, ++nwd_child) {
if(false == nwd_child->connected) continue;
if(nwd_child->keepalive_count <= 0) {
nwd_child->keepalive_count = 0;
continue;
}
nwd_child->keepalive_count -= value;
}
}
void NetworkData::decrease_nb_timers(uint value)
{
struct node_data *nwd_nb = neighbours;
for(int i = 0; i < CHILDREN_SZ; ++i, ++nwd_nb) {
if(false == nwd_nb->connected) continue;
if(nwd_nb->keepalive_count <= 0) {
nwd_nb->keepalive_count = 0;
continue;
}
nwd_nb->keepalive_count -= value;
}
}
int NetworkData::iterateChilds(struct node_data **node)
{
/* one past last is okay, but not beyond that */
const struct node_data *last = &childs[CHILDREN_SZ];
if(nullptr == *node){
*node = childs;
return 1;
}
++(*node);
return *node == last ? 0 : 1;
}
int NetworkData::iterateNeighbours(struct node_data **node)
{
/* one past last is okay, but not beyond that */
const struct node_data *last = &neighbours[NEIGHBOUR_SZ];
if(nullptr == *node){
*node = neighbours;
return 1;
}
++(*node);
return *node == last ? 0 : 1;
}
int NetworkData::generate_child_address(struct net_address *address)
{
syscalls::SyscallsInterface::mem_clr(address, sizeof(*address));
int ret;
int child_addr = -1;
for(int i = 0; i < CHILDREN_SZ; ++i){
if(childs[i].connected == false) {
// Found a free slot
child_addr = i;
break;
}
}
// No addresses free.. here we might need to release one.
if(child_addr < 0) {return -1;}
// Assign it
childs[child_addr].connected = true;
childs[child_addr].keepalive_count = TIMER_KEEPALIVE;
// When using it we want to start with number 1 not 0
child_addr++;
pairedChildren++;
// Get new address
ret = getNewChildAddress(&mac, address, child_addr);
if(ret) {
return -1;
}
// Add it to parent neighbour list
syscalls::SyscallsInterface::copy_data(&childs[child_addr-1].mac, address, sizeof(*address));
return 0;
}
void NetworkData::updateChildCounter(const struct net_address *node)
{
struct node_data *child = findChild(node);
if(nullptr == child) return;
child->keepalive_count = TIMER_KEEPALIVE;
}
void NetworkData::updateParentCounter(const struct net_address *node)
{
if(syscalls::SyscallsInterface::cmp_data(node,&parent.mac, sizeof(parent.mac))) return;
parent.keepalive_count = TIMER_KEEPALIVE;
}
void NetworkData::updateNeighbourCounter(const struct net_address *node)
{
struct node_data *nb = findNeighbour(node);
if(nullptr == nb) return;
nb->keepalive_count = TIMER_KEEPALIVE;
}
struct node_data *NetworkData::findChild(const struct net_address *child)
{
struct node_data *nwd_child = childs;
for(int i = 0; i < CHILDREN_SZ; ++i, ++nwd_child) {
if(false == nwd_child->connected) continue;
if(syscalls::SyscallsInterface::cmp_data(child, &nwd_child->mac, sizeof(*child))) continue;
return nwd_child;
}
return nullptr;
}
struct node_data *NetworkData::findNeighbour(const struct net_address *neighbour)
{
struct node_data *nwd_nb = neighbours;
for(int i = 0; i < CHILDREN_SZ; ++i, ++nwd_nb) {
if(false == nwd_nb->connected) continue;
if(syscalls::SyscallsInterface::cmp_data(neighbour, &nwd_nb->mac, sizeof(*neighbour))) continue;
return nwd_nb;
}
return nullptr;
}
int NetworkData::getNewChildAddress(const struct net_address *parent,
struct net_address *child,
const int childId)
{
if(parent->master) {
// Easy one
child->nbs[0].net = childId;
return 0;
}
// here we need to find the parent, also copying the bytes from parent
for(int i = 0 ; i < NET_COUNT ; ++i) {
child->nbs[i].net = parent->nbs[i].net;
if(parent->nbs[i].net == 0) {
child->nbs[i].net = childId;
return 0;
}
}
return -1;
}
void NetworkData::generate_temporary_address(struct net_address *address) {
address->broadcast = 0;
address->master = 0;
address->gen_addr = 1;
for(int i = 0 ; i < NET_COUNT; ++i) {
address->nbs[i].net = generate_number(NUM_ADDRESSES);
}
address->host_addr = generate_number(NUM_ADDRESSES);
}
uint8_t NetworkData::generate_number(int max_number){
return syscalls->get_random() % max_number;
}
/* Should be moved to a class*/
bool NetworkData::check_timer_zero(struct node_data *node){
return node->keepalive_count == 0 ? true : false;
}
/* Should be moved to a class*/
bool NetworkData::checkConnected(struct node_data *node){
return node->connected == true ? true : false;
}
}
| 28.835714 | 98 | 0.711915 | [
"mesh"
] |
c1d24afa67e787074ce584aebf6d467586731743 | 13,866 | cpp | C++ | WaterFallView/OrientedVirtualizingPanel.cpp | Tlaster/Marduk.Controls | 111e564617403c97a2f72e64b2673cdef62e1c0e | [
"WTFPL"
] | 1 | 2019-02-19T10:24:28.000Z | 2019-02-19T10:24:28.000Z | WaterFallView/OrientedVirtualizingPanel.cpp | Tlaster/Marduk.Controls | 111e564617403c97a2f72e64b2673cdef62e1c0e | [
"WTFPL"
] | null | null | null | WaterFallView/OrientedVirtualizingPanel.cpp | Tlaster/Marduk.Controls | 111e564617403c97a2f72e64b2673cdef62e1c0e | [
"WTFPL"
] | null | null | null | #include "pch.h"
#include "OrientedVirtualizingPanel.h"
using namespace WaterFallView;
void OrientedVirtualizingPanel::ScrollIntoView(unsigned int index)
{
this->ScrollIntoView(index, false);
}
void OrientedVirtualizingPanel::ScrollIntoView(Platform::Object ^ item)
{
this->ScrollIntoView(item, false);
}
void OrientedVirtualizingPanel::ScrollIntoView(unsigned int index, bool disableAnimation)
{
auto rect = this->Layout->GetItemLayoutRect(index);
auto viewSize = Size{ (float)this->ParentScrollView->ViewportWidth, (float)this->ParentScrollView->ViewportHeight };
auto viewOffset = Point{ (float)this->ParentScrollView->HorizontalOffset, (float)this->ParentScrollView->VerticalOffset };
auto vtOffset = viewOffset.Y;
auto vbOffset = viewOffset.Y + viewSize.Height;
auto htOffset = viewOffset.X;
auto hbOffset = viewOffset.X + viewSize.Width;
double vTarget = NAN;
double hTarget = NAN;
if (rect.Top < vtOffset)
{
vTarget = rect.Top;
}
else if (rect.Bottom > vtOffset)
{
vTarget = rect.Bottom - viewSize.Height;
}
if (rect.Left < htOffset)
{
hTarget = rect.Left;
}
else if (rect.Right > hbOffset)
{
vTarget = rect.Right - viewSize.Width;
}
if (!isnan(vTarget))
{
if (vTarget < 0)
{
vTarget = 0;
}
}
if (!isnan(hTarget))
{
if (hTarget < 0)
{
hTarget = 0;
}
}
IBox<double>^ h = isnan(hTarget) ? nullptr : ref new Box<double>(hTarget);
IBox<double>^ v = isnan(vTarget) ? nullptr : ref new Box<double>(vTarget);
this->ParentScrollView->ChangeView(h, v, nullptr, disableAnimation);
}
void OrientedVirtualizingPanel::ScrollIntoView(Platform::Object ^ item, bool disableAnimation)
{
unsigned int index;
if (!Items->IndexOf(item, &index))
{
return;
}
this->ScrollIntoView(index, false);
}
OrientedVirtualizingPanel::OrientedVirtualizingPanel()
{
_timer = ref new Windows::UI::Xaml::DispatcherTimer();
_timer->Interval = TimeSpan{ 10000 };
_timer->Tick += ref new Windows::Foundation::EventHandler<Object ^>(this, &OrientedVirtualizingPanel::OnTick);
auto mc = MeasureControl;
}
void OrientedVirtualizingPanel::OnTick(Object^ sender, Object^e)
{
_timer->Stop();
_isSkip = false;
InvalidateMeasure();
InvalidateArrange();
}
Size OrientedVirtualizingPanel::MeasureOverride(Size availableSize)
{
if (_parentScrollView == nullptr)
{
_parentScrollView = dynamic_cast<WinCon::ScrollViewer^>(this->Parent);
if (_parentScrollView != nullptr)
{
_parentScrollView->ViewChanging += ref new Windows::Foundation::EventHandler<WinCon::ScrollViewerViewChangingEventArgs ^>(this, &OrientedVirtualizingPanel::OnViewChanging);
_sizeChangedToken = _parentScrollView->SizeChanged += ref new Windows::UI::Xaml::SizeChangedEventHandler(this, &OrientedVirtualizingPanel::OnSizeChanged);
}
}
if (_parentScrollView == nullptr)
{
return Size(availableSize.Width, 0);
}
if (_layout == nullptr)
{
_layout = GetLayout(availableSize);
}
if (HeaderContainer != nullptr)
{
OnHeaderMeasureOverride(availableSize);
}
if (FooterContainer != nullptr)
{
//if (_lastRealizationItemIndex + 1 == Items->Size)
//{
// FooterContainer->Visibility = Windows::UI::Xaml::Visibility::Visible;
//}
//else
//{
// FooterContainer->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
//}
OnFooterMeasureOverride(availableSize);
}
if (_parentScrollView->ViewportHeight == 0)
{
return _layout->LayoutSize;
}
_itemAvailableSize = GetItemAvailableSize(availableSize);
if (_requestRelayout || NeedRelayout(availableSize))
{
if (DelayMeasure && !_requestRelayout)
{
_isSkip = true;
}
_requestRelayout = true;
}
if (_isSkip)
{
_isSkip = true;
_timer->Stop();
_timer->Start();
return _layout->LayoutSize;
}
if (_requestRelayout)
{
_requestRelayout = false;
if (_requestShowItemIndex < 0 && (_parentScrollView->VerticalOffset >= Layout->HeaderSize.Height))
{
int requestFirstVisableItemIndex = _firstRealizationItemIndex;
int requestLastVisableItemIndex = _lastRealizationItemIndex;
auto items = (std::vector<Object^>*)(void*)(_layout->GetVisableItems(VisualWindow{ _parentScrollView->VerticalOffset,_parentScrollView->ViewportHeight }, &requestFirstVisableItemIndex, &requestLastVisableItemIndex));
delete(items);
for (int i = requestFirstVisableItemIndex; i <= requestLastVisableItemIndex; i++)
{
if (i >= 0)
{
if (Layout->GetItemLayoutRect(i).Top >= _parentScrollView->VerticalOffset)
{
_requestShowItemIndex = i;
break;
}
}
}
}
Relayout(availableSize);
}
if (_requestShowItemIndex >= 0)
{
auto requestScrollViewOffset = MakeItemVisable(_requestShowItemIndex);
if (_scrollViewOffsetCache != _scrollViewOffset)
{
_scrollViewOffsetCache = _scrollViewOffset;
if (requestScrollViewOffset.Y != _scrollViewOffset.Y)
{
_timer->Start();
return _layout->LayoutSize;
}
}
_requestShowItemIndex = -1;
}
if (_scrollViewOffset.X < 0 || _scrollViewOffset.Y < 0)
{
_scrollViewOffset = Point((float)(_parentScrollView->HorizontalOffset), (float)(_parentScrollView->VerticalOffset));
}
_requestWindow = GetVisibleWindow(_scrollViewOffset, Size((float)_parentScrollView->ViewportWidth, (float)_parentScrollView->ViewportHeight));
for (int i = _layout->UnitCount; i < (LONGLONG)Items->Size; i++)
{
if (_layout->FillWindow(_requestWindow))
{
break;
}
Size itemSize = MeasureItem(Items->GetAt(i), Size{ 0,0 });
_layout->AddItem(i, Items->GetAt(i), itemSize);
}
if (!_layout->FillWindow(_requestWindow))
{
LoadMoreItems();
}
int requestFirstRealizationItemIndex = _firstRealizationItemIndex;
int requestLastRealizationItemIndex = _lastRealizationItemIndex;
auto visableItems = (std::vector<Object^>*)(void*)(_layout->GetVisableItems(_requestWindow, &requestFirstRealizationItemIndex, &requestLastRealizationItemIndex));
std::sort(_visableItems->begin(), _visableItems->end(), CompareObject());
std::sort(visableItems->begin(), visableItems->end(), CompareObject());
std::vector<Object^>* needRecycleItems = new std::vector<Object^>();
std::set_difference(_visableItems->begin(), _visableItems->end(), visableItems->begin(), visableItems->end(), std::back_inserter(*needRecycleItems), CompareObject());
for (auto item : *visableItems)
{
auto container = RealizeItem(item);
container->Measure(_itemAvailableSize);
}
for (auto item : *needRecycleItems)
{
RecycleItem(item);
}
delete(needRecycleItems);
delete(_visableItems);
_visableItems = visableItems;
_firstRealizationItemIndex = requestFirstRealizationItemIndex;
_lastRealizationItemIndex = requestLastRealizationItemIndex;
_itemAvailableSizeCache = _itemAvailableSize;
return _layout->LayoutSize;
}
Point OrientedVirtualizingPanel::MakeItemVisable(int index)
{
auto rect = _layout->GetItemLayoutRect(index);
_parentScrollView->ChangeView((double)rect.Left, (double)rect.Top, 1.0f, true);
return Point{ rect.Left, rect.Top };
}
Size OrientedVirtualizingPanel::ArrangeOverride(Size finalSize)
{
if (_isSkip)
{
return finalSize;
}
if (_layout == nullptr)
{
return finalSize;
}
if (HeaderContainer != nullptr)
{
OnHeaderArrangeOverride(finalSize);
}
if (FooterContainer != nullptr)
{
OnFooterArrangeOverride(finalSize);
}
if (_firstRealizationItemIndex < 0 || _lastRealizationItemIndex < 0)
{
return finalSize;
}
for (int i = _firstRealizationItemIndex; i <= _lastRealizationItemIndex; i++)
{
auto rect = _layout->GetItemLayoutRect(i);
auto container = GetContainerFormIndex(i);
container->Arrange(rect);
}
return finalSize;
}
void OrientedVirtualizingPanel::OnViewChanging(Object^ sender, WinCon::ScrollViewerViewChangingEventArgs ^ e)
{
auto i = e->FinalView;
int viewIndex = (int)floor(e->NextView->VerticalOffset / (_parentScrollView->ViewportHeight / 2)) + 1;
if (viewIndex != _viewIndex)
{
_viewIndex = viewIndex;
_scrollViewOffset = Point((float)e->NextView->HorizontalOffset, (float)e->NextView->VerticalOffset);
InvalidateMeasure();
InvalidateArrange();
}
}
void OrientedVirtualizingPanel::OnSizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e)
{
_parentScrollView->SizeChanged -= _sizeChangedToken;
InvalidateMeasure();
InvalidateArrange();
}
void OrientedVirtualizingPanel::OnItemsChanged(IObservableVector<Object^>^ source, IVectorChangedEventArgs^ e)
{
if (_layout == nullptr)
{
InvalidateMeasure();
InvalidateArrange();
return;
}
switch (e->CollectionChange)
{
case CollectionChange::Reset:
_layout->RemoveAll();
InvalidateMeasure();
InvalidateArrange();
break;
case CollectionChange::ItemInserted:
if (e->Index != Items->Size - 1)
{
if ((LONGLONG)e->Index <= _layout->UnitCount)
{
_layout->AddItem(e->Index, Items->GetAt(e->Index), MeasureItem(Items->GetAt(e->Index), Size(0, 0)));
}
}
else
{
if (_layout->FillWindow(_requestWindow))
{
break;
}
}
InvalidateMeasure();
InvalidateArrange();
break;
case CollectionChange::ItemRemoved:
if ((LONGLONG)e->Index < _layout->UnitCount)
{
_layout->RemoveItem(e->Index);
InvalidateMeasure();
InvalidateArrange();
}
break;
case CollectionChange::ItemChanged:
if ((LONGLONG)e->Index < _layout->UnitCount)
{
_layout->ChangeItem(e->Index, Items->GetAt(e->Index), MeasureItem(Items->GetAt(e->Index), Size(0, 0)));
InvalidateMeasure();
InvalidateArrange();
}
break;
default:
throw Exception::CreateException(-1, "Unexpected collection operation.");
break;
}
}
Size OrientedVirtualizingPanel::MeasureItem(Object^ item, Size oldSize)
{
if (Resizer != nullptr && oldSize.Height > 0)
{
return Resizer->Resize(item, oldSize, _itemAvailableSize);
}
if (IsItemItsOwnContainerOverride(item))
{
auto measureControl = dynamic_cast<WinCon::ContentControl^>(item);
Children->Append(measureControl);
measureControl->Measure(_itemAvailableSize);
auto result = measureControl->DesiredSize;
Children->RemoveAtEnd();
return result;
}
else
{
PrepareContainerForItemOverride(MeasureControl, item);
MeasureControl->Measure(_itemAvailableSize);
ClearContainerForItemOverride(MeasureControl, item);
return MeasureControl->DesiredSize;
}
}
VisualWindow OrientedVirtualizingPanel::GetVisibleWindow(Point offset, Size viewportSize)
{
return VisualWindow{ max(offset.Y - viewportSize.Height, 0),viewportSize.Height * 3 };
}
Size OrientedVirtualizingPanel::GetItemAvailableSize(Size availableSize)
{
return availableSize;
}
bool OrientedVirtualizingPanel::NeedRelayout(Size availableSize)
{
return _layout->Width != availableSize.Width;
}
void OrientedVirtualizingPanel::Relayout(Size availableSize)
{
_layout->ChangePanelSize(availableSize.Width);
for (int i = 0; i < _layout->UnitCount; i++)
{
auto newSize = MeasureItem(Items->GetAt(i), _layout->GetItemSize(i));
_layout->ChangeItem(i, Items->GetAt(i), newSize);
}
}
ILayout^ OrientedVirtualizingPanel::GetLayout(Size availableSize)
{
return nullptr;
}
void OrientedVirtualizingPanel::OnHeaderMeasureOverride(Size availableSize)
{
if (HeaderContainer == nullptr)
return;
availableSize = Layout->GetHeaderAvailableSize();
HeaderContainer->Measure(availableSize);
Layout->SetHeaderSize(Size(availableSize.Width, HeaderContainer->DesiredSize.Height));
}
void OrientedVirtualizingPanel::OnHeaderArrangeOverride(Size finalSize)
{
if (HeaderContainer == nullptr)
return;
HeaderContainer->Arrange(Layout->GetHeaderLayoutRect());
}
void OrientedVirtualizingPanel::OnFooterMeasureOverride(Size availableSize)
{
if (FooterContainer == nullptr)
return;
availableSize = Layout->GetFooterAvailableSize();
FooterContainer->Measure(availableSize);
Layout->SetFooterSize(Size(availableSize.Width, FooterContainer->DesiredSize.Height));
}
void OrientedVirtualizingPanel::OnFooterArrangeOverride(Size finalSize)
{
if (FooterContainer == nullptr)
return;
FooterContainer->Arrange(Layout->GetFooterLayoutRect());
}
void OrientedVirtualizingPanel::OnItemContainerSizeChanged(Platform::Object^ item, VirtualizingViewItem^ itemContainer, Size newSize)
{
UINT index = 0;
if (Items->IndexOf(item, &index))
{
if (newSize != Layout->GetItemSize(index))
{
Layout->ChangeItem(index, item, newSize);
InvalidateMeasure();
InvalidateArrange();
}
}
} | 28.413934 | 228 | 0.654118 | [
"object",
"vector"
] |
c1d8164508ce2e8339c006f529712d43d0765aa9 | 4,823 | hpp | C++ | src/data/Bonus_Levels.hpp | Snackya/KH2-co-op-mix | d585c67743e7555d7aed789ed282a50024ef0e17 | [
"MIT"
] | 2 | 2021-07-03T17:38:39.000Z | 2021-09-11T21:10:55.000Z | src/data/Bonus_Levels.hpp | Snackya/KH2-Co-op-Mix | d585c67743e7555d7aed789ed282a50024ef0e17 | [
"MIT"
] | 6 | 2021-09-12T02:15:06.000Z | 2021-09-13T03:58:21.000Z | src/data/Bonus_Levels.hpp | Snackya/KH2-co-op-mix | d585c67743e7555d7aed789ed282a50024ef0e17 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <string>
// addr1: HP,MP
// addr2: armor/accessory/item slots
// addr3: item1, item2
// see https://pastebin.com/WfGrYcBK
// {bitmask address, value},
// {value , [addr1, addr2, addr3]}
static inline std::multimap<uint16_t, std::pair<uint8_t, std::vector<uint32_t>>> bonus_levels_sora =
{
{0x3704, {0x4, {0x20f81a2, 0x20f81a4, 0x20f81a8}}}, //Thresholder
{0x3704, {0x8, {0x20f81d2, 0x20f81d4, 0x20f81d8}}}, //Dark Thorn
{0x3704, {0x10, {0x20f8212, 0x20f8214, 0x20f8218}}}, //Xaldin
{0x3704, {0x20, {0x20f8252, 0x20f8254, 0x20f8258}}}, //Cerberus
{0x3704, {0x40, {0x20f8272, 0x20f8274, 0x20f8278}}}, //Pete I
{0x3704, {0x80, {0x20f82a2, 0x20f82a4, 0x20f82a8}}}, //Hydra
{0x3705, {0x1, {0x20f82d2, 0x20f82d4, 0x20f82d8}}}, //Hades
{0x3705, {0x2, {0x20f8312, 0x20f8314, 0x20f8318}}}, //Shan Yu
{0x3705, {0x4, {0x20f8352, 0x20f8354, 0x20f8358}}}, //Storm Rider
{0x3705, {0x10, {0x20f8392, 0x20f8394, 0x20f8398}}}, //Beast
{0x3705, {0x80, {0x20f83c2, 0x20f83c4, 0x20f83c8}}}, //Genie Jafar
{0x3706, {0x1, {0x20f83d2, 0x20f83d4, 0x20f83d8}}}, //Boat Pete
{0x3706, {0x2, {0x20f8402, 0x20f8404, 0x20f8408}}}, //Pete II
{0x3706, {0x4, {0x20f8432, 0x20f8434, 0x20f8438}}}, //Prison Keeper
{0x3706, {0x8, {0x20f8472, 0x20f8474, 0x20f8478}}}, //Oogie Boogie
{0x3706, {0x10, {0x20f84b2, 0x20f84b4, 0x20f84b8}}}, //The Experiment
{0x3706, {0x20, {0x20f84f2, 0x20f84f4, 0x20f84f8}}}, //Barbossa
{0x3706, {0x40, {0x20f8532, 0x20f8534, 0x20f8538}}}, //Grim Reaper II
{0x3706, {0x80, {0x20f8572, 0x20f8574, 0x20f8578}}}, //Xigbar
{0x3707, {0x1, {0x20f85a2, 0x20f85a4, 0x20f85a8}}}, //Luxord
{0x3707, {0x2, {0x20f85b2, 0x20f85b4, 0x20f85b8}}}, //Saix
{0x3707, {0x4, {0x20f85e2, 0x20f85e4, 0x20f85e8}}}, //Xemnas I
{0x3707, {0x10, {0x20f85f2, 0x20f85f4, 0x20f85f8}}}, //Demyx II
{0x3707, {0x20, {0x20f8622, 0x20f8624, 0x20f8628}}}, //Scar
{0x3707, {0x40, {0x20f8662, 0x20f8664, 0x20f8668}}}, //Groundshaker
{0x3707, {0x80, {0x20f8682, 0x20f8684, 0x20f8688}}}, //Hostile Program
{0x3708, {0x1, {0x20f86c2, 0x20f86c4, 0x20f86c8}}}, //MCP
{0x3708, {0x2, {0x20f8702, 0x20f8704, 0x20f8708}}}, //Twilight Thorn
{0x3708, {0x4, {0x20f8712, 0x20f8714, 0x20f8718}}}, //Axel II
{0x3708, {0x8, {0x20f8722, 0x20f8724, 0x20f8728}}}, //Sephiroth
{0x3708, {0x20, {0x20f8732, 0x20f8734, 0x20f8738}}}, //Volcanic Lord & Blizzard Lord
{0x3708, {0x40, {0x20f8772, 0x20f8774, 0x20f8778}}}, //Queen Minnie Escort
{0x3708, {0x80, {0x20f8782, 0x20f8784, 0x20f8788}}}, //The Interceptor Barrels
{0x3709, {0x1, {0x20f87c2, 0x20f87c4, 0x20f87c8}}}, //Lock, Shock & Barrel
{0x3709, {0x4, {0x20f8802, 0x20f8804, 0x20f8808}}}, //Abu Escort
{0x3709, {0x8, {0x20f8842, 0x20f8844, 0x20f8848}}}, //Village Cave Heartless
{0x3709, {0x20, {0x20f8862, 0x20f8864, 0x20f8868}}}, //Dataspace Monitors
{0x3709, {0x40, {0x20f88a2, 0x20f88a4, 0x20f88a8}}}, //Treasure Room Heartless
{0x3709, {0x80, {0x20f88e2, 0x20f88e4, 0x20f88e8}}}, //Bailey Nobodies
{0x370A, {0x2, {0x20f88f2, 0x20f88f4, 0x20f88f8}}}, //Hyenas I
{0x370A, {0x4, {0x20f8922, 0x20f8924, 0x20f8928}}}, //Hyenas II
{0x370A, {0x40, {0x20f89f2, 0x20f89f4, 0x20f89f8}}}, //Station of Serenity Nobodies
{0x370B, {0x1, {0x20f8a02, 0x20f8a04, 0x20f8a08}}}, //The Old Mansion Nobodies
{0x370B, {0x2, {0x20f8a32, 0x20f8a34, 0x20f8a38}}}, //Phil's Training
{0x370B, {0x4, {0x20f8a42, 0x20f8a44, 0x20f8a48}}}, //Demyx I
{0x370B, {0x8, {0x20f8a72, 0x20f8a74, 0x20f8a78}}}, //Grim Reaper I
{0x370B, {0x10, {0x20f8ab2, 0x20f8ab4, 0x20f8ab8}}}, //1000 Heartless
{0x370B, {0x20, {0x20f8ac2, 0x20f8ac4, 0x20f8ac8}}}, //Solar Sailor Heartless
{0x370B, {0x40, {0x20f8b02, 0x20f8b04, 0x20f8b08}}}, //The Interceptor Pirates
{0x370B, {0x80, {0x20f8b32, 0x20f8b34, 0x20f8b38}}}, //Betwixt and Between Nobodies
{0x370C, {0x1, {0x20f8b42, 0x20f8b44, 0x20f8b48}}}, //Vexen
{0x370C, {0x2, {0x20f8b72, 0x20f8b74, 0x20f8b78}}}, //Lexaeus
{0x370C, {0x4, {0x20f8ba2, 0x20f8ba4, 0x20f8ba8}}}, //Zexion
{0x370C, {0x8, {0x20f8bd2, 0x20f8bd4, 0x20f8bd8}}}, //Marluxia
{0x370C, {0x10, {0x20f8c02, 0x20f8c04, 0x20f8c08}}}, //Larxene
{0x370C, {0x20, {0x20f8c32, 0x20f8c34, 0x20f8c38}}}, //Roxas
{0x370C, {0x40, {0x20f8c42, 0x20f8c44, 0x20f8c48}}}, //Lingering Will
{0x370C, {0x80, {0x20f8c72, 0x20f8c74, 0x20f8c78}}}, //Xemnas II
{0x370D, {0x1, {0x20f8c92, 0x20f8c94, 0x20f8c98}}}, //Transport to Remembrance Nobodies III
{0x370D, {0x2, {0x20f8cc2, 0x20f8cc4, 0x20f8cc8}}} //Axel I
}; | 65.175676 | 100 | 0.639643 | [
"vector"
] |
c1daae43b8ec53c46ccb96760da6ab6263d66636 | 2,320 | cpp | C++ | src/util.cpp | devinus/kaolin | 260e7e16feab90ddd7a044d3bbeb2abc89ccd7c2 | [
"MIT"
] | 2 | 2016-05-08T12:31:51.000Z | 2017-07-10T13:39:33.000Z | src/util.cpp | devinus/kaolin | 260e7e16feab90ddd7a044d3bbeb2abc89ccd7c2 | [
"MIT"
] | null | null | null | src/util.cpp | devinus/kaolin | 260e7e16feab90ddd7a044d3bbeb2abc89ccd7c2 | [
"MIT"
] | null | null | null | /*
* Kaolin - Exfoliate your face
* Copyright (c) 2008 Devin Torres
* Licensed under the MIT license.
*/
#include <iostream>
#include <string>
#include <vector>
#include "config.h"
#include "main.h"
#include "server.h"
namespace util
{
/*
* Utility functions declatations.
*/
std::string center_str(const std::string& s)
{
unsigned short int len = s.length();
if (len >= 80)
return s;
std::string new_s(40 - (len / 2), ' ');
new_s += s;
return new_s;
}
std::string numberize(short int n)
{
static const std::string ones_numerals[] = {
"",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
static const std::string tens_numerals[] = {
"",
"",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
};
static const std::string special_numbers[] = {
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
};
std::string buf = "";
std::vector<short int> digits(0);
if (n == 0)
{
buf += "zero";
return buf;
}
if (n <= 9)
{
buf += ones_numerals[n];
return buf;
}
if (n <= 19)
{
buf += special_numbers[n - 10];
return buf;
}
if (n >= 10000 || n < 0)
buf += n;
digits[3] = n / 1000;
n -= digits[3] * 1000;
digits[2] = n / 100;
n -= digits[2] * 100;
digits[1] = n / 10;
n -= digits[1] * 10;
digits[0] = n;
if (digits[3] > 0)
buf += ones_numerals[digits[3]] + " thousand ";
if (digits[2] > 0)
buf += ones_numerals[digits[2]] + " hundred ";
if (digits[1] > 0)
{
buf += tens_numerals[digits[1]];
if (digits[0] >= 1)
buf += "-";
}
if (digits[0] > 0)
buf += ones_numerals[digits[0]];
if (buf[buf.length() - 1] == ' ')
buf.erase(buf.end() - 1);
return buf;
}
bool is_number(const std::string& arg)
{
for (unsigned short int i = 0; i < arg.length(); ++i)
{
if (!isdigit(arg[i]))
return false;
}
return true;
}
bool str_prefix(const std::string& s1, const std::string& s2)
{
for (unsigned short int i = 0; i < s1.length(); ++i)
{
if (tolower(s1[i]) != tolower(s2[i]))
return false;
}
return true;
}
}
| 14.409938 | 61 | 0.521983 | [
"vector"
] |
c1dd253071069050990614a40567d585f27e4e50 | 1,516 | cpp | C++ | actor_grt_rtw/rt_look2d_normal.cpp | HaiyinPiao/aca_arena | 53a307a42833898ae6fe5083124f01cfaf923e19 | [
"MIT"
] | 1 | 2020-06-06T13:26:19.000Z | 2020-06-06T13:26:19.000Z | actor_grt_rtw/rt_look2d_normal.cpp | HaiyinPiao/aca_arena | 53a307a42833898ae6fe5083124f01cfaf923e19 | [
"MIT"
] | null | null | null | actor_grt_rtw/rt_look2d_normal.cpp | HaiyinPiao/aca_arena | 53a307a42833898ae6fe5083124f01cfaf923e19 | [
"MIT"
] | null | null | null | /*
* rt_look2d_normal.cpp
*
* Code generation for model "actor".
*
* Model version : 1.1483
* Simulink Coder version : 8.11 (R2016b) 25-Aug-2016
* C++ source code generated on : Fri Jan 19 11:20:06 2018
*
* Target selection: grt.tlc
* Note: GRT includes extra infrastructure and instrumentation for prototyping
* Embedded hardware selection: Intel->x86-64 (Windows64)
* Code generation objective: Execution efficiency
* Validation result: Not run
*/
#include "rt_look2d_normal.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 2D normal lookup routine for data type of real_T. */
real_T rt_Lookup2D_Normal(const real_T *xVals, const int_T numX,
const real_T *yVals, const int_T numY,
const real_T *zVals,
const real_T x, const real_T y)
{
int_T xIdx, yIdx;
real_T ylo, yhi;
real_T Zx0yhi, Zx0ylo, xlo, xhi;
real_T corner1, corner2;
xIdx = rt_GetLookupIndex(xVals,numX,x);
xlo = xVals[xIdx];
xhi = xVals[xIdx+1];
yIdx = rt_GetLookupIndex(yVals,numY,y);
ylo = yVals[yIdx];
yhi = yVals[yIdx+1];
corner1 = *(zVals + xIdx + (numX * yIdx));
corner2 = *(zVals + (xIdx+1) + (numX * yIdx));
Zx0ylo = INTERP(x, xlo, xhi, corner1, corner2);
corner1 = *(zVals + xIdx + (numX * (yIdx+1)));
corner2 = *(zVals + (xIdx+1) + (numX*(yIdx+1)));
Zx0yhi = INTERP(x, xlo, xhi, corner1, corner2);
return (INTERP(y,ylo,yhi,Zx0ylo,Zx0yhi));
}
#ifdef __cplusplus
} /* extern "C" */
#endif
| 28.603774 | 78 | 0.631926 | [
"model"
] |
c1e521cc7b53236d96c214c3bbe7ef8f3fdb725e | 8,005 | cpp | C++ | Projects/4.Intermediate.Code.Generation/snuplc/src/symtab.cpp | hhosu107/Compiler | 3c12d5a0584a9b333af66a7eddb5960bbe537425 | [
"MIT"
] | 2 | 2016-03-22T10:56:00.000Z | 2022-03-26T15:43:46.000Z | Projects/4.Intermediate.Code.Generation/snuplc/src/symtab.cpp | hhosu107/Compiler | 3c12d5a0584a9b333af66a7eddb5960bbe537425 | [
"MIT"
] | 3 | 2016-03-22T16:18:44.000Z | 2016-03-23T01:49:58.000Z | Projects/4.Intermediate.Code.Generation/snuplc/src/symtab.cpp | hhosu107/Compiler | 3c12d5a0584a9b333af66a7eddb5960bbe537425 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
/// @brief SnuPL symbol table
/// @author Bernhard Egger <bernhard@csap.snu.ac.kr>
/// @section changelog Change Log
/// 2012/09/14 Bernhard Egger created
/// 2016/04/05 Bernhard Egger bugfix in CSymtab::print
///
/// @section license_section License
/// Copyright (c) 2012-2016, Bernhard Egger
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without modifi-
/// cation, 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.
///
/// 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 CONSE-
/// QUENTIAL 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 <cassert>
#include <iomanip>
#include "symtab.h"
using namespace std;
//------------------------------------------------------------------------------
// CSymbol
//
CSymbol::CSymbol(const string name, ESymbolType stype, const CType *dtype)
: _name(name), _symboltype(stype), _datatype(dtype), _data(NULL),
_rbase(""), _offset(0), _symtab(NULL)
{
assert(_name != "");
assert(_datatype != NULL);
}
CSymbol::~CSymbol(void)
{
}
string CSymbol::GetName(void) const
{
return _name;
}
ESymbolType CSymbol::GetSymbolType(void) const
{
return _symboltype;
}
void CSymbol::SetDataType(const CType *datatype)
{
_datatype = datatype;
}
const CType* CSymbol::GetDataType(void) const
{
return _datatype;
}
void CSymbol::SetSymbolTable(CSymtab *symtab)
{
_symtab = symtab;
}
CSymtab* CSymbol::GetSymbolTable(void) const
{
return _symtab;
}
void CSymbol::SetData(const CDataInitializer *data)
{
_data = data;
}
const CDataInitializer* CSymbol::GetData(void) const
{
return _data;
}
void CSymbol::SetBaseRegister(string rbase)
{
_rbase = rbase;
}
string CSymbol::GetBaseRegister(void) const
{
return _rbase;
}
void CSymbol::SetOffset(int offset)
{
_offset = offset;
}
int CSymbol::GetOffset(void) const
{
return _offset;
}
ostream& CSymbol::print(ostream &out, int indent) const
{
string ind(indent, ' ');
out << ind << "[ " << left << setw(8) << GetName() << right << " ";
GetDataType()->print(out);
out << ind << " ]";
return out;
}
ostream& operator<<(ostream &out, const CSymbol &t)
{
return t.print(out);
}
ostream& operator<<(ostream &out, const CSymbol *t)
{
return t->print(out);
}
//------------------------------------------------------------------------------
// CSymGlobal
//
CSymGlobal::CSymGlobal(const string name, const CType *type)
: CSymbol(name, stGlobal, type)
{
}
ostream& CSymGlobal::print(ostream &out, int indent) const
{
string ind(indent, ' ');
out << ind << "[ @" << left << setw(8) << GetName() << right << " ";
GetDataType()->print(out);
out << ind << " ]";
return out;
}
//------------------------------------------------------------------------------
// CSymLocal
//
CSymLocal::CSymLocal(const string name, const CType *type)
: CSymbol(name, stLocal, type)
{
}
CSymLocal::CSymLocal(const string name, ESymbolType stype, const CType *type)
: CSymbol(name, stype, type)
{
}
ostream& CSymLocal::print(ostream &out, int indent) const
{
string ind(indent, ' ');
out << ind << "[ $" << left << setw(8) << GetName() << right << " ";
GetDataType()->print(out);
if (GetBaseRegister() != "") {
out << " " << GetBaseRegister();
if (GetOffset() >= 0) out << "+";
out << GetOffset();
}
out << ind << " ]";
return out;
}
//------------------------------------------------------------------------------
// CSymParam
//
CSymParam::CSymParam(int index, const string name, const CType *type)
: CSymLocal(name, stParam, type), _index(index)
{
}
ostream& CSymParam::print(ostream &out, int indent) const
{
string ind(indent, ' ');
out << ind << "[ %" << left << setw(8) << GetName() << right << " ";
GetDataType()->print(out);
if (GetBaseRegister() != "") {
out << " " << GetBaseRegister();
if (GetOffset() >= 0) out << "+";
out << GetOffset();
}
out << ind << " ]";
return out;
}
int CSymParam::GetIndex(void) const
{
return _index;
}
//------------------------------------------------------------------------------
// CSymProc
//
CSymProc::CSymProc(const string name, const CType *return_type)
: CSymbol(name, stProcedure, return_type)
{
}
void CSymProc::AddParam(CSymParam *param)
{
_param.push_back(param);
}
int CSymProc::GetNParams(void) const
{
return (int)_param.size();
}
const CSymParam* CSymProc::GetParam(int index) const
{
assert((index >= 0) && (index < _param.size()));
return _param[index];
}
ostream& CSymProc::print(ostream &out, int indent) const
{
string ind(indent, ' ');
out << ind << "[ *" << GetName() << "(";
for (size_t i=0; i<_param.size(); i++) {
const CType *t = _param[i]->GetDataType();
if (i > 0) out << ",";
t->print(out);
}
out << ") --> ";
GetDataType()->print(out);
out << ind << " ]";
return out;
}
//------------------------------------------------------------------------------
// CSymtab
//
CSymtab::CSymtab(void)
{
}
CSymtab::CSymtab(CSymtab *parent)
: _parent(parent)
{
assert(parent != NULL);
}
CSymtab::~CSymtab(void)
{
map<string, CSymbol*>::const_iterator it = _symtab.begin();
while (it != _symtab.end()) delete (*it++).second;
_symtab.clear();
}
bool CSymtab::AddSymbol(CSymbol *s)
{
assert(s != NULL);
// global symbols always get pushed up to the global symbol table
if ((s->GetSymbolType() == stGlobal) && (_parent != NULL)) {
return _parent->AddSymbol(s);
}
if (!FindSymbol(s->GetName(), sLocal)) {
_symtab[s->GetName()] = s;
s->SetSymbolTable(this);
return true;
} else {
return false;
}
}
const CSymbol* CSymtab::FindSymbol(const string name, EScope scope) const
{
map<string, CSymbol*>::const_iterator it = _symtab.find(name);
if (it != _symtab.end()) return (*it).second;
else {
if ((scope == sLocal) || (_parent == NULL)) return NULL;
else return _parent->FindSymbol(name, scope);
}
}
vector<CSymbol*> CSymtab::GetSymbols(void) const
{
vector<CSymbol*> _res;
map<string, CSymbol*>::const_iterator it = _symtab.begin();
while (it != _symtab.end()) {
_res.push_back(it->second);
it++;
}
return _res;
}
ostream& CSymtab::print(ostream &out, int indent) const
{
string ind(indent, ' ');
out << ind << "[[";
map<string, CSymbol*>::const_iterator it = _symtab.begin();
while (it != _symtab.end()) {
out << endl;
const CSymbol *s = (*it++).second;
s->print(out, indent+2);
const CDataInitializer *di = s->GetData();
if (di != NULL) {
out << endl;
di->print(out, indent+4);
}
}
out << endl << ind << "]]" << endl;
return out;
}
ostream& operator<<(ostream &out, const CSymtab &s)
{
return s.print(out);
}
ostream& operator<<(ostream &out, const CSymtab *s)
{
return s->print(out);
}
| 22.871429 | 80 | 0.596877 | [
"vector"
] |
c1e7328c58e3191ae87f9e78963c2183fd489708 | 2,462 | cpp | C++ | examples/pong/ball.cpp | Miyake-Diogo/abcg | 4963eb03dec419501924ad488f36eef193dd700c | [
"MIT"
] | null | null | null | examples/pong/ball.cpp | Miyake-Diogo/abcg | 4963eb03dec419501924ad488f36eef193dd700c | [
"MIT"
] | null | null | null | examples/pong/ball.cpp | Miyake-Diogo/abcg | 4963eb03dec419501924ad488f36eef193dd700c | [
"MIT"
] | null | null | null | #include "ball.hpp"
#include <cppitertools/itertools.hpp>
#include <glm/gtx/rotate_vector.hpp>
void Ball::initializeGL(GLuint program) {
terminateGL();
m_program = program;
m_colorLoc = abcg::glGetUniformLocation(m_program, "color");
m_rotationLoc = abcg::glGetUniformLocation(m_program, "rotation");
m_scaleLoc = abcg::glGetUniformLocation(m_program, "scale");
m_translationLoc = abcg::glGetUniformLocation(m_program, "translation");
m_dead = false,
m_translation = glm::vec2{0.0f, 0.0f},
m_velocity = glm::vec2{1.0f, 0.0f} * m_ballSpeed;
// Create regular polygon
const auto sides{10};
std::vector<glm::vec2> positions(0);
positions.emplace_back(0, 0);
const auto step{M_PI * 2 / sides};
for (const auto angle : iter::range(0.0, M_PI * 2, step)) {
positions.emplace_back(std::cos(angle), std::sin(angle));
}
positions.push_back(positions.at(1));
// Generate VBO of positions
abcg::glGenBuffers(1, &m_vbo);
abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
abcg::glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec2),
positions.data(), GL_STATIC_DRAW);
abcg::glBindBuffer(GL_ARRAY_BUFFER, 0);
// Get location of attributes in the program
const GLint positionAttribute{
abcg::glGetAttribLocation(m_program, "inPosition")};
// Create VAO
abcg::glGenVertexArrays(1, &m_vao);
// Bind vertex attributes to current VAO
abcg::glBindVertexArray(m_vao);
abcg::glEnableVertexAttribArray(positionAttribute);
abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
abcg::glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, GL_FALSE, 0,
nullptr);
abcg::glBindBuffer(GL_ARRAY_BUFFER, 0);
// End of binding to current VAO
abcg::glBindVertexArray(0);
}
void Ball::paintGL() {
abcg::glUseProgram(m_program);
abcg::glBindVertexArray(m_vao);
abcg::glUniform4f(m_colorLoc, 1, 1, 1, 1);
abcg::glUniform1f(m_rotationLoc, 0);
abcg::glUniform1f(m_scaleLoc, m_scale);
abcg::glUniform2f(m_translationLoc, m_translation.x, m_translation.y);
abcg::glDrawArrays(GL_TRIANGLE_FAN, 0, 12);
abcg::glBindVertexArray(0);
abcg::glUseProgram(0);
}
void Ball::terminateGL() {
abcg::glDeleteBuffers(1, &m_vbo);
abcg::glDeleteVertexArrays(1, &m_vao);
}
void Ball::update(float deltaTime) {
// Create Ball
if (!direction) {
m_translation -= m_velocity * deltaTime;
}else{
m_translation += m_velocity * deltaTime;
}
}
| 27.977273 | 75 | 0.703899 | [
"vector"
] |
c1ed12094ac1dc1fbcaf1e4864b3e4f2953f2c24 | 8,585 | cpp | C++ | common/printfile.cpp | austinseraphin/wwiv | 9944737b0ece0e3f80656c7af08ab4dafceebdd3 | [
"Apache-2.0"
] | null | null | null | common/printfile.cpp | austinseraphin/wwiv | 9944737b0ece0e3f80656c7af08ab4dafceebdd3 | [
"Apache-2.0"
] | null | null | null | common/printfile.cpp | austinseraphin/wwiv | 9944737b0ece0e3f80656c7af08ab4dafceebdd3 | [
"Apache-2.0"
] | null | null | null | /**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2021, WWIV Software Services */
/* */
/* 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 "common/printfile.h"
#include "bbs/bbs.h"
#include "common/input.h"
#include "common/menu_data_util.h"
#include "common/pause.h"
#include "core/file.h"
#include "core/os.h"
#include "core/stl.h"
#include "core/strings.h"
#include "core/textfile.h"
#include "local_io/keycodes.h"
#include "sdk/config.h"
#include "core/scope_exit.h"
#include <chrono>
#include <memory>
#include <string>
#include <vector>
namespace wwiv::common {
using std::string;
using std::unique_ptr;
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace wwiv::core;
using namespace wwiv::sdk;
using namespace wwiv::stl;
using namespace wwiv::strings;
/**
* Creates the fully qualified filename to display adding extensions and directories as needed.
*/
std::filesystem::path CreateFullPathToPrint(const std::vector<string>& dirs, const User& user,
const string& basename) {
for (const auto& base : dirs) {
auto file{FilePath(base, basename)};
if (basename.find('.') != string::npos) {
// We have a file with extension.
if (File::Exists(file)) {
return file;
}
// Since no wwiv file names contain embedded dots skip to the next directory.
continue;
}
auto candidate{file};
if (user.HasAnsi()) {
if (user.HasColor()) {
// ANSI and color
candidate.replace_extension(".ans");
if (File::Exists(candidate)) {
return candidate;
}
}
// ANSI.
candidate.replace_extension(".b&w");
if (File::Exists(candidate)) {
return candidate;
}
}
// ANSI/Color optional
candidate.replace_extension(".msg");
if (File::Exists(candidate)) {
return candidate;
}
}
// Nothing matched, return the input.
return basename;
}
class printfile_opts {
public:
printfile_opts(SessionContext& sc, Output& out, const std::string& raw, bool abtable, bool forcep)
: sess(sc), out_(out), abortable(abtable), force_pause(forcep) {
menu_data_and_options_t t(raw);
data_ = t.data();
saved_disable_pause = sess.disable_pause();
saved_user_has_pause = out.user().HasPause();
if (!t.opts_empty()) {
for (const auto& [key, value] : t.opts()) {
if (key == "pause") {
if (value == "on") {
sess.disable_pause(false);
out.user().SetStatusFlag(User::pauseOnPage, true);
} else if (value == "off") {
sess.disable_pause(true);
out.user().SetStatusFlag(User::pauseOnPage, false);
} else if (value == "start") {
bout.pausescr();
} else if (value == "end") {
pause_at_end = true;
}
} else if (key == "bps") {
bps = to_number<int>(value);
sess.set_file_bps(bps);
}
}
}
}
~printfile_opts() {
sess.disable_pause(saved_disable_pause);
out_.user().SetStatusFlag(User::pauseOnPage, saved_user_has_pause);
if (pause_at_end) {
bout.pausescr();
}
}
[[nodiscard]] std::string data() const noexcept { return data_; }
private:
std::string data_;
SessionContext& sess;
Output& out_;
public:
bool abortable{true};
bool force_pause{true};
bool pause_at_start{false};
bool pause_at_end{false};
bool saved_disable_pause{false};
bool saved_user_has_pause{false};
int bps{0};
};
/**
* Prints the file file_name. Returns true if the file exists and is not
* zero length. Returns false if the file does not exist or is zero length
*
* @param file_path Full path to the file to display
* @param abortable If true, a keyboard input may abort the display
* @param force_pause Should pauses be used even for ANSI files - Normally
* pause on screen is disabled for ANSI files.
*
* @return true if the file exists and is not zero length
*/
// ReSharper disable once CppMemberFunctionMayBeConst
bool Output::printfile_path(const std::filesystem::path& file_path, bool abortable, bool force_pause) {
ScopeExit at_exit([this]() { sess().set_file_bps(0); });
if (!File::Exists(file_path)) {
// No need to print a file that does not exist.
return false;
}
std::error_code ec;
if (!is_regular_file(file_path, ec)) {
// Not a file, no need to print a file that is not a file.
return false;
}
TextFile tf(file_path, "rb");
const auto v = tf.ReadFileIntoVector();
const auto start_time = system_clock::now();
auto num_written = 0;
for (const auto& s : v) {
num_written += bout.bputs(s);
bout.nl();
const auto has_ansi = contains(s, ESC);
// If this is an ANSI file, then don't pause
// (since we may be moving around
// on the screen, unless the caller tells us to pause anyway)
if (has_ansi && !force_pause) {
bout.clear_lines_listed();
}
if (contains(s, CZ)) {
// We are done here on a control-Z since that's DOS EOF. Also ANSI
// files created with PabloDraw expect that anything after a Control-Z
// is fair game for metadata and includes SAUCE metadata after it which
// we do not want to render in the bbs.
break;
}
if (abortable && bin.checka()) {
break;
}
}
bout.flush();
if (sess().bps() > 0) {
const auto elapsed_ms = duration_cast<milliseconds>(system_clock::now() - start_time);
const auto actual_cps = num_written * 1000 / (elapsed_ms.count() + 1);
VLOG(1) << "Record CPS for file: " << file_path.string() << "; CPS: " << actual_cps;
}
return !v.empty();
}
bool Output::printfile(const std::string& data, bool abortable, bool force_pause) {
const printfile_opts opts(sess(), *this, data, abortable, force_pause);
const std::vector<string> dirs{sess().dirs().language_directory(),
sess().dirs().gfiles_directory()};
const auto full_path_name = CreateFullPathToPrint(dirs, context().u(), opts.data());
return printfile_path(full_path_name, abortable, force_pause);
}
/**
* Displays a help file or an error that no help is available.
*
* A help file is a normal file displayed with printfile.
*/
bool Output::print_help_file(const std::string& filename) {
if (!printfile(filename)) {
bout << "No help available. File '" << filename << "' does not exist.\r\n";
return false;
}
return true;
}
/**
* Displays a file locally.
*/
void Output::print_local_file(const string& filename) {
printfile(filename);
bout.nl(2);
bout.pausescr();
}
bool Output::printfile_random(const std::string& raw_base_fn) {
const printfile_opts opts(sess(), *this, raw_base_fn, true, true);
const auto& dir = sess().dirs().language_directory();
const auto base_fn = opts.data();
const auto dot_zero = FilePath(dir, StrCat(base_fn, ".0"));
if (!File::Exists(dot_zero)) {
return false;
}
auto screens = 0;
for (auto i = 0; i < 1000; i++) {
const auto dot_n = FilePath(dir, StrCat(base_fn, ".", i));
if (File::Exists(dot_n)) {
++screens;
} else {
break;
}
}
return printfile_path(FilePath(dir, StrCat(base_fn, ".", wwiv::os::random_number(screens))),
opts.abortable, opts.force_pause);
}
} // namespace wwiv::common
| 33.275194 | 103 | 0.591497 | [
"render",
"vector"
] |
c1f4da59d4485e81a26d34757505c3f477f02334 | 10,511 | hpp | C++ | SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/src/gatb/tools/misc/impl/Tool.hpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/src/gatb/tools/misc/impl/Tool.hpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/src/gatb/tools/misc/impl/Tool.hpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | /*****************************************************************************
* GATB : Genome Assembly Tool Box
* Copyright (C) 2014 INRIA
* Authors: R.Chikhi, G.Rizk, E.Drezen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
/** \file Tool.hpp
* \date 01/03/2013
* \author edrezen
* \brief Tool framework
*/
#ifndef _GATB_CORE_TOOLS_MISC_IMPL_TOOL_HPP_
#define _GATB_CORE_TOOLS_MISC_IMPL_TOOL_HPP_
/********************************************************************************/
#include <gatb/tools/designpattern/api/ICommand.hpp>
#include <gatb/tools/designpattern/impl/IteratorHelpers.hpp>
#include <gatb/tools/collections/api/Iterable.hpp>
#include <gatb/tools/misc/api/IProperty.hpp>
#include <gatb/tools/misc/impl/TimeInfo.hpp>
#include <gatb/tools/misc/impl/OptionsParser.hpp>
#include <gatb/tools/misc/api/StringsRepository.hpp>
#include <string>
#include <list>
/********************************************************************************/
namespace gatb {
namespace core {
namespace tools {
namespace misc {
namespace impl {
/********************************************************************************/
/** \brief Framework abstract class for implementing tools (ie. binary tools).
*
* This class provides facilities for:
* - parsing command line
* - dispatching work on several threads
* - getting execution times
* - gathering statistics information
*
* The Tool sub classes must implement the execute method; this is the place where
* the actual job of the tool has to be done.
*
* If the tool is launch with the run method and the famous [argc,argv] couple,
* the command line [argc,argv] is parsed through an options parser and the recognized
* options are available through the getInput method.
*
* The option parser should be configured (ie. adding specific options) during the constructor
* of the Tool sub class. By default, some default options are attached to the Tool options
* parser; for instance :
* - "-nb-cores" is available and enables to set the number of cores that can be used by the tool.
* - "-verbose" is available and can be used for having progress bar while iterating iterators.
*
* A dispatcher is available with the getDispatcher method. This dispatcher may have been
* configured (ie. set the number of available cores) during the constructor.
*
* Example:
* \snippet ToyTool.cpp snippet1
*
* \see Algorithm
*/
class Tool : public system::SmartPointer
{
public:
/** Constructor.
* \param[in] name: name of the tool. */
Tool (const std::string& name);
/** Destructor. */
virtual ~Tool ();
/** Get tool name
* \return the tool name. */
std::string getName () const { return _name; }
/** Run the tool with input parameters provided as a IProperties instance
* \param[in] input : input parameters
* \return the parsed options as a IProperties instance
*/
virtual IProperties* run (IProperties* input);
/** Run the tool with input parameters provided as a couple [argc,argv]
* \param[in] argc : number of arguments
* \param[in] argv : array of arguments
* \return the parsed options as a IProperties instance
*/
virtual IProperties* run (int argc, char* argv[]);
/** Subclasses must implement this method; this is where the actual job of
* the tool has to be done.
*/
virtual void execute () = 0;
/** Get the parsed options as a properties instance
* \return the parsed options.
*/
virtual IProperties* getInput () { return _input; }
/** Get output results as a properties instance
* \return the output results
*/
virtual IProperties* getOutput () { return _output; }
/** Get statistics information about the execution of the tool
* \return the statistics
*/
virtual IProperties* getInfo () { return _info; }
/** Get an option parser configured with recognized options for the tool
* \return the options parser instance
*/
virtual IOptionsParser* getParser () { return _parser; }
/** Get a dispatched that can be used for parallelization. The option "-nb-cores" can
* be used, and thus the provided number is used for configuring the dispatcher.
* \return the dispatcher for the tool
*/
virtual dp::IDispatcher* getDispatcher () { return _dispatcher; }
/** Get a TimeInfo instance for the tool. This object can be used for gathering
* execution times of some parts of the \ref execute method.
* \return the time info instance.
*/
virtual TimeInfo& getTimeInfo () { return _timeInfo; }
/** Create an iterator for the given iterable. If the verbosity is enough, progress bar information
* can be displayed.
* \param[in] iterable : object that creates the iterator.
* \param[in] message : message used if progress information has to be displayed
* \return the created iterator.
*/
template<typename Item> dp::Iterator<Item>* createIterator (collections::Iterable<Item>& iterable, const char* message=0)
{
int64_t nbItems = (iterable.getNbItems() >= 0 ? iterable.getNbItems() : iterable.estimateNbItems());
return createIterator (iterable.iterator(), nbItems, message);
}
/** Create an iterator for the given iterator. If the verbosity is enough, progress bar information
* can be displayed.
* \param[in] iter : object to be encapsulated by a potential progress information
* \param[in] nbIterations : number of iterations to be done.
* \param[in] message : message used if progress information has to be displayed
* \return the created iterator.
*/
template<typename Item> dp::Iterator<Item>* createIterator (dp::Iterator<Item>* iter, size_t nbIterations=0, const char* message=0)
{
if (nbIterations > 0 && message != 0)
{
// We create some listener to be notified every 1000 iterations and attach it to the iterator.
dp::impl::SubjectIterator<Item>* iterSubject = new dp::impl::SubjectIterator<Item> (iter, nbIterations/100);
iterSubject->addObserver (createIteratorListener (nbIterations, message));
/** We assign the used iterator to be the subject iterator. */
iter = iterSubject;
}
/** We return the result. */
return iter;
}
/** Creates an iterator listener according to the verbosity level.
* \param[in] nbIterations : number of iterations to be done
* \param[in] message : progression message
* \return an iterator listener.
*/
virtual dp::IteratorListener* createIteratorListener (size_t nbIterations, const char* message);
/** Displays information about the GATB library
* \param[in] os : output stream used for dumping library information
*/
virtual void displayVersion(std::ostream& os);
protected:
/** */
virtual void preExecute ();
virtual void postExecute ();
/** Computes the uri from an uri (ie add a prefix if any). */
std::string getUriByKey (const std::string& key) { return getUri (getInput()->getStr(key)); }
/** Computes the uri from an uri (ie add a prefix if any). */
std::string getUri (const std::string& str) { return getInput()->getStr(STR_PREFIX) + str; }
/** Setters. */
void setInput (IProperties* input) { SP_SETATTR (input); }
void setOutput (IProperties* output) { SP_SETATTR (output); }
void setInfo (IProperties* info) { SP_SETATTR (info); }
void setParser (IOptionsParser* parser) { SP_SETATTR (parser); }
void setDispatcher (dp::IDispatcher* dispatcher) { SP_SETATTR (dispatcher); }
protected:
/** Name of the tool (set at construction). */
std::string _name;
IProperties* _input;
IProperties* _output;
IProperties* _info;
IOptionsParser* _parser;
dp::IDispatcher* _dispatcher;
/** */
TimeInfo _timeInfo;
friend class ToolComposite;
};
/********************************************************************************/
/* DEPRECATED. */
class ToolComposite : public Tool
{
public:
/** Constructor.
* \param[in] name: name of the tool. */
ToolComposite (const std::string& name = "tool");
/** */
~ToolComposite ();
/** */
IProperties* run (int argc, char* argv[]);
/** */
void add (Tool* tool);
private:
std::list<Tool*> _tools;
/** */
void execute ();
void preExecute ();
void postExecute ();
};
/********************************************************************************/
/* DEPRECATED. */
class ToolProxy : public Tool
{
public:
/** */
ToolProxy (Tool* ref) : Tool("proxy"), _ref (ref) {}
/** */
virtual IOptionsParser* getParser () { return _ref->getParser(); }
/** */
virtual IProperties* getInput () { return _ref->getInput(); }
virtual IProperties* getOutput () { return _ref->getOutput(); }
virtual IProperties* getInfo () { return _ref->getInfo(); }
/** */
virtual dp::IDispatcher* getDispatcher () { return _ref->getDispatcher(); }
/** */
virtual TimeInfo& getTimeInfo () { return _ref->getTimeInfo (); }
/** */
Tool* getRef () { return _ref; }
private:
Tool* _ref;
};
/********************************************************************************/
} } } } } /* end of namespaces. */
/********************************************************************************/
#endif /* _GATB_CORE_TOOLS_MISC_IMPL_TOOL_HPP_ */
| 35.390572 | 135 | 0.606983 | [
"object"
] |
c1f6977e3cf256a32d6107a900f851b965debefe | 51 | cpp | C++ | src/comm_comp/mesh.cpp | wu1274704958/vulkan_demo | 545e00a1fae98e0ff179115887dfa7669b56ccde | [
"MIT"
] | null | null | null | src/comm_comp/mesh.cpp | wu1274704958/vulkan_demo | 545e00a1fae98e0ff179115887dfa7669b56ccde | [
"MIT"
] | null | null | null | src/comm_comp/mesh.cpp | wu1274704958/vulkan_demo | 545e00a1fae98e0ff179115887dfa7669b56ccde | [
"MIT"
] | 1 | 2021-12-27T08:40:07.000Z | 2021-12-27T08:40:07.000Z | #include <comm_comp/mesh.hpp>
namespace vkd
{
}
| 7.285714 | 29 | 0.686275 | [
"mesh"
] |
c1faf33d4db46fe99166afbc985002d7322c1624 | 4,149 | cpp | C++ | examples/threads/main.cpp | VXAPPS/modern.cpp.logger | 0120b3624f65b8c765353180c5a333244e1d3d61 | [
"BSD-3-Clause"
] | null | null | null | examples/threads/main.cpp | VXAPPS/modern.cpp.logger | 0120b3624f65b8c765353180c5a333244e1d3d61 | [
"BSD-3-Clause"
] | null | null | null | examples/threads/main.cpp | VXAPPS/modern.cpp.logger | 0120b3624f65b8c765353180c5a333244e1d3d61 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2021 Florian Becker <fb@vxapps.com> (VX APPS).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
/* stl header */
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
/* modern.cpp.logger */
#include <LoggerFactory.h>
/**
* @brief Filename of temporary log file.
*/
constexpr auto filename = "thread-example.log";
/**
* @brief Count of log messages per thread.
*/
constexpr std::size_t logMessageCount = 10000;
/**
* @brief Log message itself.
*/
constexpr auto logMessage = "This is a log message";
/**
* @brief Function per thread.
*/
static void work() {
std::ostringstream s;
s << logMessage;
std::string message = s.str();
for ( std::size_t i = 0; i < logMessageCount; ++i ) {
vx::LogFatal( message );
vx::LogError( message );
vx::LogWarning( message );
vx::LogInfo( message );
vx::LogDebug( message );
vx::LogVerbose( message );
}
}
int main() {
/* create tmp file */
std::error_code errorCode {};
std::filesystem::path tmpPath = std::filesystem::temp_directory_path( errorCode );
if ( errorCode ) {
std::cout << "Error getting temp_directory_path: " << errorCode.message() << " Code: " << errorCode.value() << std::endl;
return EXIT_FAILURE;
}
tmpPath /= filename;
std::string tmpFile = tmpPath.string();
std::cout << "Create tmp file: " << tmpFile << std::endl;
/* configure logging, if you dont it defaults to standard out logging with colors */
vx::ConfigureLogger( { { "type", "file" }, { "filename", tmpFile }, { "reopen_interval", "1" } } );
/* start up some threads */
unsigned int hardwareThreadCount = std::max<unsigned int>( 1, std::thread::hardware_concurrency() );
std::cout << "Using threads: " << hardwareThreadCount << std::endl;
#if defined __GNUC__ && __GNUC__ >= 10 || defined _MSC_VER && _MSC_VER >= 1928
std::vector<std::jthread> threads {};
threads.reserve( hardwareThreadCount );
for ( unsigned int i = 0; i < hardwareThreadCount; ++i ) {
threads.emplace_back( std::jthread( work ) );
}
#else
std::vector<std::thread> threads {};
threads.reserve( hardwareThreadCount );
for ( unsigned int i = 0; i < hardwareThreadCount; ++i ) {
threads.emplace_back( std::thread( work ) );
}
#endif
for ( auto &thread : threads ) {
thread.join();
}
threads.clear();
/* remove tmp file */
if ( !std::filesystem::remove( tmpFile ) ) {
std::cout << "Tmp file cannot be removed: " << tmpFile << std::endl;
return EXIT_FAILURE;
}
std::cout << "Tmp file was removed: " << tmpFile << std::endl;
return EXIT_SUCCESS;
}
| 32.414063 | 125 | 0.688118 | [
"vector"
] |
c1fef204995851aab7593478bce3877362a2f416 | 7,925 | cpp | C++ | plugin/AL_USDMayaTestPlugin/test_translators_CameraTranslator.cpp | AlexSchwank/AL_USDMaya | 99413e2c5d1c93e4c58a63ebc8b07e23cf072e86 | [
"Apache-2.0"
] | null | null | null | plugin/AL_USDMayaTestPlugin/test_translators_CameraTranslator.cpp | AlexSchwank/AL_USDMaya | 99413e2c5d1c93e4c58a63ebc8b07e23cf072e86 | [
"Apache-2.0"
] | null | null | null | plugin/AL_USDMayaTestPlugin/test_translators_CameraTranslator.cpp | AlexSchwank/AL_USDMaya | 99413e2c5d1c93e4c58a63ebc8b07e23cf072e86 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2017 Animal Logic
//
// 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 "test_usdmaya.h"
#include "AL/usdmaya/fileio/ExportParams.h"
#include "AL/usdmaya/fileio/ImportParams.h"
#include "AL/usdmaya/fileio/NodeFactory.h"
#include "AL/usdmaya/fileio/AnimationTranslator.h"
#include "AL/usdmaya/fileio/translators/TranslatorBase.h"
#include "AL/usdmaya/StageCache.h"
#include "maya/MFileIO.h"
#include "maya/MFnDagNode.h"
#include "maya/MDagModifier.h"
#include "pxr/usd/usd/attribute.h"
#include "pxr/usd/usdGeom/camera.h"
using AL::usdmaya::fileio::ExporterParams;
using AL::usdmaya::fileio::ImporterParams;
using AL::usdmaya::fileio::AnimationTranslator;
//----------------------------------------------------------------------------------------------------------------------
/// \brief Test some of the functionality of the CameraTranslator.
//----------------------------------------------------------------------------------------------------------------------
TEST(translators_CameraTranslator, io)
{
for(int i = 0; i < 100; ++i)
{
MDagModifier mod, mod2;
MObject xform = mod.createNode("transform");
MObject node = mod.createNode("camera", xform);
MObject xformB = mod.createNode("transform");
EXPECT_EQ(MStatus(MS::kSuccess), mod.doIt());
const char* const attributeNames[] = {
"orthographic",
"horizontalFilmAperture",
"verticalFilmAperture",
"horizontalFilmOffset",
"verticalFilmOffset",
"focalLength",
"focusDistance",
"nearClipPlane",
"farClipPlane",
"fStop",
//"lensSqueezeRatio"
};
const uint32_t numAttributes = sizeof(attributeNames) / sizeof(const char* const);
randomNode(node, attributeNames, numAttributes);
// generate a prim for testing
UsdStageRefPtr stage = UsdStage::CreateInMemory();
ExporterParams eparams;
ImporterParams iparams;
SdfPath cameraPath("/hello");
MDagPath nodeDagPath;
MDagPath::getAPathTo(node, nodeDagPath);
AL::usdmaya::fileio::translators::TranslatorManufacture manufacture(nullptr);
AL::usdmaya::fileio::translators::TranslatorRefPtr xtrans = manufacture.get(TfToken("Camera"));
UsdPrim cameraPrim = xtrans->exportObject(stage, nodeDagPath, cameraPath, eparams);
EXPECT_TRUE(cameraPrim.IsValid());
MObject nodeB;
EXPECT_EQ(MStatus(MS::kSuccess), xtrans->import(cameraPrim, xformB, nodeB));
// now make sure the imported node matches the one we started with
compareNodes(node, nodeB, attributeNames, numAttributes, true);
mod2.deleteNode(nodeB);
mod2.deleteNode(xformB);
mod2.deleteNode(node);
mod2.deleteNode(xform);
mod2.doIt();
}
}
TEST(translators_CameraTranslator, animated_io)
{
const double startFrame = 1.0;
const double endFrame = 20.0;
for(int i = 0; i < 100; ++i)
{
MDagModifier mod;
MObject xform = mod.createNode("transform");
MObject node = mod.createNode("camera", xform);
MObject xformB = mod.createNode("transform");
EXPECT_EQ(MStatus(MS::kSuccess), mod.doIt());
const char* const attributeNames[] = {
"orthographic",
"horizontalFilmAperture",
"verticalFilmAperture",
"horizontalFilmOffset",
"verticalFilmOffset",
"focalLength",
"focusDistance",
"nearClipPlane",
"farClipPlane",
"fStop",
//"lensSqueezeRatio"
};
const uint32_t numAttributes = sizeof(attributeNames) / sizeof(const char* const);
randomAnimatedNode(node, attributeNames, numAttributes, startFrame, endFrame);
// generate a prim for testing
UsdStageRefPtr stage = UsdStage::CreateInMemory();
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Export animation
//////////////////////////////////////////////////////////////////////////////////////////////////////////
ExporterParams eparams;
eparams.m_minFrame = startFrame;
eparams.m_maxFrame = endFrame;
eparams.m_animation = true;
eparams.m_animTranslator = new AnimationTranslator;
AL::usdmaya::fileio::translators::TranslatorManufacture manufacture(nullptr);
AL::usdmaya::fileio::translators::TranslatorRefPtr xtrans = manufacture.get(TfToken("Camera"));
SdfPath cameraPath("/hello");
MDagPath nodeDagPath;
MDagPath::getAPathTo(node, nodeDagPath);
UsdPrim cameraPrim = xtrans->exportObject(stage, nodeDagPath, cameraPath, eparams);
EXPECT_TRUE(cameraPrim.IsValid());
eparams.m_animTranslator->exportAnimation(eparams);
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Import animation
//////////////////////////////////////////////////////////////////////////////////////////////////////////
ImporterParams iparams;
MObject nodeB;
EXPECT_EQ(MStatus(MS::kSuccess), xtrans->import(cameraPrim, xformB, nodeB));
// now make sure the imported node matches the one we started with
for(double t = eparams.m_minFrame, e = eparams.m_maxFrame + 1e-3f; t < e; t += 1.0)
{
MGlobal::viewFrame(t);
compareNodes(node, nodeB, attributeNames, numAttributes, true);
}
EXPECT_EQ(MStatus(MS::kSuccess), mod.undoIt());
}
}
TEST(translators_CameraTranslator, cameraShapeName)
{
auto constructTestUSDFile = []() {
const std::string temp_bootstrap_path = buildTempPath("AL_USDMayaTests_camShapeName.usda");
UsdStageRefPtr stage = UsdStage::CreateInMemory();
UsdGeomXform root = UsdGeomXform::Define(stage, SdfPath("/root"));
UsdPrim geo = stage->DefinePrim(SdfPath("/root/geo"), TfToken("xform"));
UsdPrim cam = stage->DefinePrim(SdfPath("/root/geo/cam"), TfToken("Camera"));
stage->Export(temp_bootstrap_path, false);
return MString(temp_bootstrap_path.c_str());
};
auto constructCamTestCommand = [] (const MString& bootstrap_path)
{
MString cmd = "AL_usdmaya_ProxyShapeImport -file \"";
cmd += bootstrap_path;
cmd += "\"";
return cmd;
};
auto getStageFromCache = [] ()
{
auto usdStageCache = AL::usdmaya::StageCache::Get();
if(usdStageCache.IsEmpty())
{
return UsdStageRefPtr();
}
return usdStageCache.GetAllStages()[0];
};
auto assertSdfPathIsValid = [] (UsdStageRefPtr usdStage, const std::string &path)
{
EXPECT_TRUE(usdStage->GetPrimAtPath(SdfPath(path)).IsValid());
};
MString bootstrap_path = constructTestUSDFile();
MFileIO::newFile(true);
MGlobal::executeCommand(constructCamTestCommand(bootstrap_path), false, true);
auto stage = getStageFromCache();
ASSERT_TRUE(stage);
assertSdfPathIsValid(stage, "/root");
assertSdfPathIsValid(stage, "/root/geo");
assertSdfPathIsValid(stage, "/root/geo/cam");
UsdPrim camPrim = stage->GetPrimAtPath(SdfPath("/root/geo/cam"));
ASSERT_TRUE(camPrim .IsValid());
ASSERT_EQ("Camera", camPrim.GetTypeName());
MSelectionList sl;
MObject camObj;
sl.add("cam");
sl.getDependNode(0, camObj);
ASSERT_FALSE(camObj.isNull());
MFnDagNode camDag(camObj);
ASSERT_EQ(MString("AL_usdmaya_Transform"), camDag.typeName());
ASSERT_EQ(MString("cam"), camDag.name());
ASSERT_EQ(1, camDag.childCount());
MFnDagNode shapeDag(camDag.child(0));
ASSERT_EQ(MString("camera"), shapeDag.typeName());
ASSERT_EQ(MString("camShape"), shapeDag.name());
}
| 34.758772 | 120 | 0.640252 | [
"transform"
] |
de014afde8adc1f9171be640ff2c0056ffe351ef | 17,277 | cpp | C++ | Source/SprueEngine/Graph/GraphNode.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 35 | 2017-04-07T22:49:41.000Z | 2021-08-03T13:59:20.000Z | Source/SprueEngine/Graph/GraphNode.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 1 | 2017-04-13T17:43:54.000Z | 2017-04-15T04:17:37.000Z | Source/SprueEngine/Graph/GraphNode.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 7 | 2019-03-11T19:26:53.000Z | 2021-03-04T07:17:10.000Z | #include <SprueEngine/Graph/GraphNode.h>
#include <SprueEngine/Core/Context.h>
#include <SprueEngine/Graph/Graph.h>
#include <SprueEngine/Graph/GraphSocket.h>
namespace SprueEngine
{
GraphNode::~GraphNode()
{
for (GraphSocket* socket : outputFlowSockets)
delete socket;
for (GraphSocket* socket : inputSockets)
delete socket;
for (GraphSocket* socket : outputFlowSockets)
delete socket;
if (inputFlowSocket)
delete inputFlowSocket;
}
void GraphNode::Register(Context* context)
{
REGISTER_PROPERTY_MEMORY(GraphNode, float, offsetof(GraphNode, XPos), 0.0f, "XPos", "", PS_Secret);
REGISTER_PROPERTY_MEMORY(GraphNode, float, offsetof(GraphNode, YPos), 0.0f, "YPos", "", PS_Secret);
REGISTER_PROPERTY_MEMORY(GraphNode, unsigned, offsetof(GraphNode, id), 0, "ID", "", PS_Secret);
REGISTER_PROPERTY_MEMORY(GraphNode, std::string, offsetof(GraphNode, name), std::string(), "Name", "", PS_ReadOnly);
}
bool GraphNode::Deserialize(Deserializer* src, const SerializationContext& context)
{
base::Deserialize(src, context);
outputSockets.clear();
outputFlowSockets.clear();
unsigned inSocketCt = src->ReadUInt();
for (unsigned i = 0; i < inSocketCt; ++i)
{
GraphSocket* socket = new GraphSocket(this, 0, 0);
socket->Deserialize(src, context);
inputSockets.push_back(socket);
}
inSocketCt = src->ReadUInt();
for (unsigned i = 0; i < inSocketCt; ++i)
{
GraphSocket* socket = new GraphSocket(this, 0, 0);
socket->Deserialize(src, context);
outputSockets.push_back(socket);
}
inSocketCt = src->ReadUInt();
for (unsigned i = 0; i < inSocketCt; ++i)
{
GraphSocket* socket = new GraphSocket(this, 0, 0);
socket->Deserialize(src, context);
outputFlowSockets.push_back(socket);
}
if (src->ReadBool())
{
GraphSocket* socket = new GraphSocket(this, 0, 0);
socket->Deserialize(src, context);
inputFlowSocket = socket;
}
return true;
}
bool GraphNode::Serialize(Serializer* dest, const SerializationContext& context) const
{
base::Serialize(dest, context);
dest->WriteUInt((unsigned)inputSockets.size());
if (inputSockets.size() > 0)
for (GraphSocket* socket : inputSockets)
socket->Serialize(dest, context);
dest->WriteUInt((unsigned)outputSockets.size());
if (outputSockets.size() > 0)
for (GraphSocket* socket : outputSockets)
socket->Serialize(dest, context);
dest->WriteUInt((unsigned)outputFlowSockets.size());
if (outputFlowSockets.size() > 0)
for (GraphSocket* socket : outputFlowSockets)
socket->Serialize(dest, context);
dest->WriteBool(inputFlowSocket != 0x0);
if (inputFlowSocket != 0x0)
inputFlowSocket->Serialize(dest, context);
return true;
}
bool GraphNode::Deserialize(tinyxml2::XMLElement* fromElement, const SerializationContext& context)
{
base::Deserialize(fromElement, context);
#define LOAD_XML_SOCKET_LIST(LISTTAG, LIST) if (tinyxml2::XMLElement* foundList = fromElement->FirstChildElement(LISTTAG)) { \
tinyxml2::XMLElement* socketElem = foundList->FirstChildElement("socket"); \
while (socketElem) { \
GraphSocket* socket = new GraphSocket(this, 0, 0); \
socket->Deserialize(socketElem, context); \
LIST .push_back(socket); \
socketElem = socketElem->NextSiblingElement("socket"); \
} \
}
LOAD_XML_SOCKET_LIST("inputs", inputSockets);
LOAD_XML_SOCKET_LIST("outputs", outputSockets);
LOAD_XML_SOCKET_LIST("output-flows", outputFlowSockets);
if (tinyxml2::XMLElement* inputFlow = fromElement->FirstChildElement("input-flow"))
{
GraphSocket* socket = new GraphSocket(this, 0, 0);
socket->Deserialize(inputFlow, context);
inputFlowSocket = socket;
}
return true;
}
bool GraphNode::Serialize(tinyxml2::XMLElement* parentElement, const SerializationContext& context) const
{
tinyxml2::XMLElement* myElement = parentElement->GetDocument()->NewElement(GetTypeName());
parentElement->LinkEndChild(myElement);
SerializeProperties(myElement, context);
tinyxml2::XMLElement* inputSockets = parentElement->GetDocument()->NewElement("inputs");
myElement->LinkEndChild(inputSockets);
for (auto socket : this->inputSockets)
{
tinyxml2::XMLElement* socketElement = parentElement->GetDocument()->NewElement("socket");
inputSockets->LinkEndChild(socketElement);
socket->Serialize(socketElement, context);
}
tinyxml2::XMLElement* outputSockets = parentElement->GetDocument()->NewElement("outputs");
myElement->LinkEndChild(outputSockets);
for (auto socket : this->outputSockets)
{
tinyxml2::XMLElement* socketElement = parentElement->GetDocument()->NewElement("socket");
outputSockets->LinkEndChild(socketElement);
socket->Serialize(socketElement, context);
}
tinyxml2::XMLElement* outputFlowSockets = parentElement->GetDocument()->NewElement("output-flows");
myElement->LinkEndChild(outputFlowSockets);
for (auto socket : this->outputFlowSockets)
{
tinyxml2::XMLElement* socketElement = parentElement->GetDocument()->NewElement("socket");
outputFlowSockets->LinkEndChild(socketElement);
socket->Serialize(socketElement, context);
}
if (inputFlowSocket)
{
tinyxml2::XMLElement* inputFlowSocket = parentElement->GetDocument()->NewElement("input-flow");
myElement->LinkEndChild(inputFlowSocket);
this->inputFlowSocket->Serialize(inputFlowSocket, context);
}
return true;
}
GraphSocket* GraphNode::GetSocketByFlatIndex(unsigned idx)
{
if (inputFlowSocket && idx == 0)
return inputFlowSocket;
else if (inputFlowSocket)
--idx;
if (idx < inputSockets.size())
return inputSockets[idx];
else
idx -= inputSockets.size();
if (idx < outputSockets.size())
return outputSockets[idx];
else
idx -= outputSockets.size();
if (idx < outputFlowSockets.size())
return outputFlowSockets[idx];
else
idx -= outputSockets.size();
return 0x0;
}
unsigned GraphNode::GetSocketFlatIndex(GraphSocket* socket)
{
unsigned currentIndex = 0;
if (inputFlowSocket && socket == inputFlowSocket)
return currentIndex;
else if (inputFlowSocket)
++currentIndex;
for (auto is : inputSockets)
if (is == socket)
return currentIndex;
else
++currentIndex;
for (auto is : outputSockets)
if (is == socket)
return currentIndex;
else
++currentIndex;
for (auto is : outputFlowSockets)
if (is == socket)
return currentIndex;
else
++currentIndex;
return -1;
}
GraphSocket* GraphNode::GetSocketByID(unsigned id, const std::vector<GraphSocket*>& sockets) const
{
for (GraphSocket* socket : sockets)
if (socket->socketID == id)
return socket;
return 0x0;
}
GraphSocket* GraphNode::GetSocketByID(unsigned id)
{
if (inputFlowSocket != 0x0 && id == inputFlowSocket->socketID)
return inputFlowSocket;
if (GraphSocket* ret = GetSocketByID(id, inputSockets))
return ret;
if (GraphSocket* ret = GetSocketByID(id, outputSockets))
return ret;
if (GraphSocket* ret = GetSocketByID(id, outputFlowSockets))
return ret;
return 0x0;
}
GraphSocket* GraphNode::AddInput(const std::string& name, unsigned type) {
GraphSocket* socket = new GraphSocket(this, name, type);
socket->input = 1;
inputSockets.push_back(socket);
// Only signal a socket change if we're in a graph, because that means it's an real node that is likely constructed
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
GraphSocket* GraphNode::InsertInput(unsigned index, const std::string& name, unsigned type)
{
GraphSocket* socket = new GraphSocket(this, name, type);
socket->input = 1;
inputSockets.insert(inputSockets.begin() + index, socket);
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
GraphSocket* GraphNode::AddOutput(const std::string& name, unsigned type) {
GraphSocket* socket = new GraphSocket(this, name, type);
socket->output = 1;
outputSockets.push_back(socket);
// Only signal a socket change if we're in a graph, because that means it's an real node that is likely constructed
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
GraphSocket* GraphNode::InsertOutput(unsigned index, const std::string& name, unsigned type)
{
GraphSocket* socket = new GraphSocket(this, name, type);
socket->output = 1;
outputSockets.insert(outputSockets.begin() + index, socket);
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
GraphSocket* GraphNode::AddInputFlow(const std::string& name, unsigned type)
{
if (inputFlowSocket)
return 0x0;
GraphSocket* socket = new GraphSocket(this, name, type);
socket->input = 1;
socket->control = 1;
inputFlowSocket = socket;
// Only signal a socket change if we're in a graph, because that means it's an real node that is likely constructed
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
GraphSocket* GraphNode::AddOutputFlow(const std::string& name, unsigned type)
{
GraphSocket* socket = new GraphSocket(this, name, type);
socket->output = 1;
socket->control = 1;
outputFlowSockets.push_back(socket);
// Only signal a socket change if we're in a graph, because that means it's an real node that is likely constructed
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
GraphSocket* GraphNode::InsertOutputFlow(unsigned index, const std::string& name, unsigned type)
{
GraphSocket* socket = new GraphSocket(this, name, type);
socket->output = 1;
socket->control = 1;
outputFlowSockets.insert(outputFlowSockets.begin() + index, socket);
if (graph)
Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(this);
return socket;
}
void GraphNode::PropogateValues(bool down)
{
// Propogate socket values
if (down)
{
for (GraphSocket* socket : outputSockets)
{
auto edges = graph->downstreamEdges_.equal_range(socket);
for (auto edge = edges.first; edge != edges.second; ++edge)
edge->first->StoreValue(edge->second->GetValue());
}
}
else
{
for (GraphSocket* socket : inputSockets)
{
auto upstreamEdges = graph->upstreamEdges_.equal_range(socket);
for (auto edge = upstreamEdges.first; edge != upstreamEdges.second; ++edge)
edge->first->StoreValue(edge->second->GetValue());
}
}
}
void GraphNode::ExecuteUpstream(unsigned& executionContext, const Variant& parameter, unsigned ignoringNode)
{
if (executionContext != -1 && lastExecutionContext == executionContext || id == ignoringNode)
return;
Variant param = FilterParameter(parameter);
do {
if (!WillForceExecute())
{
// Evaluate upstream nodes first
for (GraphSocket* socket : inputSockets)
{
if (!(socket->typeID))
continue;
auto upstreamEdges = graph->upstreamEdges_.equal_range(socket);
for (auto edge = upstreamEdges.first; edge != upstreamEdges.second; ++edge)
edge->second->node->ExecuteUpstream(executionContext, param);
}
PropogateValues(false);
}
} while (Execute(executionContext, parameter) == GRAPH_EXECUTE_LOOP);
}
void GraphNode::VisitUpstream(GraphNodeVisitor* visitor)
{
if (!visitor)
return;
visitor->DepthPush();
for (GraphSocket* socket : inputSockets)
{
if (!(socket->typeID))
continue;
auto upstreamEdges = graph->upstreamEdges_.equal_range(socket);
for (auto edge = upstreamEdges.first; edge != upstreamEdges.second; ++edge)
edge->second->node->VisitUpstream(visitor);
}
visitor->DepthPop();
visitor->Visit(this);
}
void GraphNode::ForceExecuteUpstreamOnly(const Variant& parameter, unsigned ignoringNode)
{
// Evaluate upstream nodes first
for (GraphSocket* socket : inputSockets)
{
if (!(socket->typeID))
continue;
auto upstreamEdges = graph->upstreamEdges_.equal_range(socket);
unsigned junk = -1;
for (auto edge = upstreamEdges.first; edge != upstreamEdges.second; ++edge)
edge->second->node->ExecuteUpstream(junk, parameter);
}
PropogateValues(false);
}
void GraphNode::ExecuteDownstream(unsigned& executionContext, const Variant& parameter, unsigned ignoringNode)
{
if (lastExecutionContext == executionContext || id == ignoringNode)
return;
Variant param = FilterParameter(parameter);
int result = 0;
do {
result = Execute(parameter);
if (result == GRAPH_EXECUTE_TERMINATE)
return;
PropogateValues(true);
for (GraphSocket* socket : outputSockets)
{
if (!(socket->typeID))
continue;
auto downstreamEdges = graph->downstreamEdges_.equal_range(socket);
for (auto edge = downstreamEdges.first; edge != downstreamEdges.second; ++edge)
edge->second->node->ExecuteDownstream(executionContext, param);
}
} while (result == GRAPH_EXECUTE_LOOP);
}
void GraphNode::ExecuteHybrid(unsigned& executionContext, const Variant& parameter, unsigned ignoringNode)
{
if (lastExecutionContext == executionContext || id == ignoringNode)
return;
// Reset our selected exit
selectedExit = 0x0;
// Iterate through input variable sockets to get values
int result = 1;
do {
// Retrieve values from upstream sockets
PropogateValues(false);
result = Execute(parameter);
if (result == GRAPH_EXECUTE_TERMINATE)
return;
// Propogate into our output sockets
PropogateValues(true);
// Execute may assign our selectedExit
if (!selectedExit)
{
// Execute all output flow sockets
for (GraphSocket* socket : outputFlowSockets)
{
//TODO: deal with branching/looping execution
auto downstreamEdges = graph->downstreamEdges_.equal_range(socket);
for (auto edge = downstreamEdges.first; edge != downstreamEdges.second; ++edge)
edge->second->node->ExecuteHybrid(executionContext, parameter);
}
}
else
{
// Execute all connections downstream from the flow exit socket
auto edge = graph->downstreamEdges_.find(selectedExit);
if (edge != graph->downstreamEdges_.end())
edge->second->node->ExecuteHybrid(executionContext, parameter);
}
} while (result == GRAPH_EXECUTE_LOOP);
}
std::vector< std::pair<GraphSocket*, GraphSocket*> > GraphNode::GetConnections() const
{
std::vector< std::pair<GraphSocket*, GraphSocket*> > ret;
if (inputFlowSocket)
{
auto inputCon = inputFlowSocket->GetConnections();
ret.insert(ret.end(), inputCon.begin(), inputCon.end());
}
for (auto socket : outputSockets)
{
auto sockets = socket->GetConnections();
ret.insert(ret.end(), sockets.begin(), sockets.end());
}
for (auto socket : inputSockets)
{
auto sockets = socket->GetConnections();
ret.insert(ret.end(), sockets.begin(), sockets.end());
}
for (auto socket : outputFlowSockets)
{
auto sockets = socket->GetConnections();
ret.insert(ret.end(), sockets.begin(), sockets.end());
}
return ret;
}
void GraphNode::RestoreConnections(const std::vector< std::pair<GraphSocket*, GraphSocket*> >& connections)
{
for (auto conn : connections)
graph->Connect(conn.first, conn.second);
}
void GraphNode::NotifySocketsChange() const
{
SprueEngine::Context::GetInstance()->GetCallbacks().GraphNodeSocketsChanged(const_cast<GraphNode*>(this));
}
} | 32.721591 | 127 | 0.632112 | [
"vector"
] |
9004cff4857e4b793eec1c09b910229ac747b624 | 470 | cpp | C++ | nice/main.cpp | nikolyanikolya/some_repository | 41bdbda91f48e6df724ebaeae199c157099e59cb | [
"Apache-2.0"
] | null | null | null | nice/main.cpp | nikolyanikolya/some_repository | 41bdbda91f48e6df724ebaeae199c157099e59cb | [
"Apache-2.0"
] | null | null | null | nice/main.cpp | nikolyanikolya/some_repository | 41bdbda91f48e6df724ebaeae199c157099e59cb | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main() {
std::vector<int> long_number;
string init_str;
std::cin >> init_str;
long_number.resize(init_str.length());
for (int i = init_str.length()-1; i >=0; i--) {
char symbol = init_str[i];
long_number[long_number.size() - i - 1] = symbol - '0';
}
for (int j = 0; j < long_number.size(); j++)
std::cout << long_number[j];
return 0;
}
| 23.5 | 63 | 0.561702 | [
"vector"
] |
900a1fd86ba253af963aeff368de298b921ed549 | 5,584 | cpp | C++ | tests/tests_coordinate.cpp | BenrickSmit/Skila | 2ea5428a215448626fc7dedbb9350045e6c822d1 | [
"Apache-2.0"
] | null | null | null | tests/tests_coordinate.cpp | BenrickSmit/Skila | 2ea5428a215448626fc7dedbb9350045e6c822d1 | [
"Apache-2.0"
] | 1 | 2021-01-11T08:38:32.000Z | 2021-01-11T08:38:32.000Z | tests/tests_coordinate.cpp | BenrickSmit/Skila | 2ea5428a215448626fc7dedbb9350045e6c822d1 | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include "gtest/gtest.h"
#include "Coordinate.h"
// Coordinate Test Suite
// Coordinate Accept Cooridinates
TEST(TEST_COORDINATE_SUITE, ctor_OriginCoordinateAsIntInput_ExpectGettersAsZero) {
Coordinate coord{0,0,0};
EXPECT_EQ(0, coord.get_x());
EXPECT_EQ(0, coord.get_y());
EXPECT_EQ(0, coord.get_z());
}
TEST(TEST_COORDINATE_SUITE, ctor_OriginCoordinateAsVectorInput_ExpectGettersAsZero) {
Coordinate coord = Coordinate(std::vector<double>({0,0,0}));
EXPECT_EQ(0, coord.get_x());
EXPECT_EQ(0, coord.get_y());
EXPECT_EQ(0, coord.get_z());
}
TEST(TEST_COORDINATE_SUITE, ctor_BlackAsIntInput_ExpectGettersAsZero) {
Coordinate coord{0,0,0,255};
EXPECT_EQ(0, coord.get_r());
EXPECT_EQ(0, coord.get_g());
EXPECT_EQ(0, coord.get_b());
EXPECT_EQ(255, coord.get_a());
}
TEST(TEST_COORDINATE_SUITE, ctor_BlackAsVectorInput_ExpectGettersAsZero) {
Coordinate coord = Coordinate(std::vector<uint16_t>({0,0,0,255}));
EXPECT_EQ(0, coord.get_r());
EXPECT_EQ(0, coord.get_g());
EXPECT_EQ(0, coord.get_b());
EXPECT_EQ(255, coord.get_a());
}
TEST(TEST_COORDINATE_SUITE, ctor_OriginCoordinateAndBlackAsIntInput_ExpectGettersAsZero) {
Coordinate coord{0,0,0,0,0,0,255};
EXPECT_EQ(0.0, coord.get_x());
EXPECT_EQ(0.0, coord.get_y());
EXPECT_EQ(0.0, coord.get_z());
EXPECT_EQ(0, coord.get_r());
EXPECT_EQ(0, coord.get_g());
EXPECT_EQ(0, coord.get_b());
EXPECT_EQ(255, coord.get_a());
}
TEST(TEST_COORDINATE_SUITE, ctor_OriginCoordinateAndBlackAsVectorInput_ExpectGettersAsZero) {
Coordinate coord = Coordinate(std::vector<double>({0,0,0}), std::vector<uint16_t>({0,0,0,255}));
EXPECT_EQ(0, coord.get_x());
EXPECT_EQ(0, coord.get_y());
EXPECT_EQ(0, coord.get_z());
EXPECT_EQ(0, coord.get_r());
EXPECT_EQ(0, coord.get_g());
EXPECT_EQ(0, coord.get_b());
EXPECT_EQ(255, coord.get_a());
}
TEST(TEST_COORDINATE_SUITE, get_colour_WhiteColourInput_ExpectWhiteColourReturn) {
std::vector<uint16_t> expected_colour = std::vector<uint16_t>({255,255,255,255});
Coordinate coord = Coordinate(expected_colour);
EXPECT_EQ(coord.get_colour(), expected_colour);
}
TEST(TEST_COORDINATE_SUITE, get_coordinate_NegativeOneInput_ExpectNegativeOneReturn) {
std::vector<double> expected_point = std::vector<double>({-1.1,-1.1,-1.1});
Coordinate coord = Coordinate(expected_point);
EXPECT_EQ(coord.get_coordinate(), expected_point);
}
TEST(TEST_COORDINATE_SUITE, set_colour_HigherThan255Input_Expect255Return) {
std::vector<uint16_t> input_colour = std::vector<uint16_t>({300,300,300,300});
std::vector<uint16_t> expected_colour = std::vector<uint16_t>({255,255,255,255});
Coordinate coord = Coordinate(input_colour);
EXPECT_EQ(coord.get_colour(), expected_colour);
}
TEST(TEST_COORDINATE_SUITE, set_colour_LowerThan0Input_Expect0Return) {
// Technically Impossibel due to "unsigned int" but still testable
std::vector<uint16_t> input_colour = std::vector<uint16_t>({0,0,0,0});
std::vector<uint16_t> expected_colour = std::vector<uint16_t>({0,0,0,0});
Coordinate coord = Coordinate(input_colour);
EXPECT_EQ(coord.get_colour(), expected_colour);
}
TEST(TEST_COORDINATE_SUITE, operatorPlusOverload_AddPositiveUnitVectors_ExpectDoubleUnitVectorReturn) {
Coordinate coord1{1,1,1},coord2{1,1,1};
Coordinate expected_result{2,2,2};
EXPECT_EQ((coord1+coord2).get_coordinate(), expected_result.get_coordinate());
}
TEST(TEST_COORDINATE_SUITE, operatorPlusOverload_AddPosUnitAndNegUnitVectors_ExpectZeroReturn) {
Coordinate coord1{1,1,1},coord2{-1,-1,-1};
Coordinate expected_result{0,0,0};
EXPECT_EQ((coord1+coord2).get_coordinate(), expected_result.get_coordinate());
}
TEST(TEST_COORDINATE_SUITE, operatorMinusOverload_SubtractUnitVectors_ExpectZeroAsUnitVectorReturn) {
Coordinate coord1{1,1,1},coord2{1,1,1};
Coordinate expected_result{0,0,0};
EXPECT_EQ((coord1-coord2).get_coordinate(), expected_result.get_coordinate());
}
TEST(TEST_COORDINATE_SUITE, operatorMinusOverload_SubtractPosAndNegUnitVectors_ExpectDoubleUnitVectorReturn) {
Coordinate coord1{1,1,1},coord2{-1,-1,-1};
Coordinate expected_result{2,2,2};
EXPECT_EQ((coord1-coord2).get_coordinate(), expected_result.get_coordinate());
}
TEST(TEST_COORDINATE_SUITE, operatorEqualOverload_UnitVectors_ExpectTrueReturn) {
Coordinate coord1{1,1,1}, coord2{1,1,1};
EXPECT_EQ(true, coord1==coord2);
}
TEST(TEST_COORDINATE_SUITE, operatorEqualOverload_OriginVectorAndUnitVectorEquality_ExpectFalseReturn) {
Coordinate coord1{0,0,0}, coord2{1,1,1};
EXPECT_EQ(false, coord1==coord2);
}
TEST(TEST_COORDINATE_SUITE, OperatorInequalOverload_OriginVectorAndUnitVectorInequality_ExpectTrueReturn) {
Coordinate coord1{0,0,0}, coord2{1,1,1};
EXPECT_EQ(true, coord1!=coord2);
}
TEST(TEST_COORDINATE_SUITE, scalar_multiply_UnitVectorInput_DoubleUnitVectorReturned) {
Coordinate coord1{1,1,1}, coord2{1.1,1.1,1.1}, expected_output1{2,2,2},
expected_output2{2.2,2.2,2.2};
coord1 = coord1.scalar_multiply(2);
coord2 = coord2.scalar_multiply(2);
EXPECT_EQ(coord1.get_coordinate(), expected_output1.get_coordinate());
EXPECT_EQ(coord2.get_coordinate(), expected_output2.get_coordinate());
}
TEST(TEST_COORDINATE_SUITE, scalar_multiply_UnitVectorInput_NegativeUnitVectorReturned) {
Coordinate coord1{1,1,1}, expected_output{-1,-1,-1};
coord1 = coord1.scalar_multiply(-1);
EXPECT_EQ(coord1.get_coordinate(), expected_output.get_coordinate());
} | 36.25974 | 111 | 0.746418 | [
"vector"
] |
900b5604bdc7588f98b02c7dee1657f2cad211e1 | 1,534 | cpp | C++ | RealityCore/Source/main.cpp | Intro-Ventors/Re-Co-Desktop | 8547cca9230069a36973ec836426d4610f30f8bb | [
"MIT"
] | null | null | null | RealityCore/Source/main.cpp | Intro-Ventors/Re-Co-Desktop | 8547cca9230069a36973ec836426d4610f30f8bb | [
"MIT"
] | null | null | null | RealityCore/Source/main.cpp | Intro-Ventors/Re-Co-Desktop | 8547cca9230069a36973ec836426d4610f30f8bb | [
"MIT"
] | null | null | null | // Copyright (c) 2022 Intro-Ventors
#include "GUI/ApplicationGUI.hpp"
#ifdef RECO_SHARED
# if defined(Q_OS_WINDOWS)
# define RECO_API __declspec(dllexport)
# elif defined(Q_OS_LINUX) || defined(Q_OS_DARWIN)
# define RECO_API __attribute__((visibility("default")))
#endif
#else
# define RECO_API
#endif // RECO_SHARED
extern "C"
{
struct RECO_API RealityCoreInstance
{
/**
* Constructor.
*
* @param argc The argument count.
* @param argv The variadic arguments.
*/
RealityCoreInstance(int argc = 0, char* argv[] = nullptr)
: m_Application(argc, argv, m_Instance) {}
Scipper::Instance m_Instance;
GUI::ApplicationGUI m_Application;
};
/**
* Create a new instance object.
*
* @return The instance object pointer.
*/
RECO_API RealityCoreInstance* CreateInstance()
{
return new RealityCoreInstance();
}
/**
* Run the instance object.
*
* @param pInstance The instance pointer.
*/
RECO_API int RunInstance(const RealityCoreInstance* pInstance)
{
return pInstance->m_Application.run();
}
/**
* Destroy the instance.
*
* @param pInstance The instance pointer to delete.
*/
RECO_API void DestroyInstance(RealityCoreInstance* pInstance)
{
delete pInstance;
}
}
#ifndef RECO_SHARED
int main(int argc, char* argv[])
{
// Create the instance.
auto pInstance = CreateInstance();
// Run the instance.
const auto result = RunInstance(pInstance);
// Destroy the instance when exiting.
DestroyInstance(pInstance);
return result;
}
#endif // !RECO_SHARED | 18.261905 | 63 | 0.704042 | [
"object"
] |
900cd1a77dd3048c8da1a1c00f785a6d7ab786d5 | 26,281 | cpp | C++ | gMotifs/inc.cpp | matteocereda/RNAmotifs | dc1498e867e84ed19322920d7b0299939fa613b5 | [
"MIT"
] | 7 | 2016-03-11T13:53:34.000Z | 2021-04-11T14:58:04.000Z | gMotifs/inc.cpp | matteocereda/RNAmotifs | dc1498e867e84ed19322920d7b0299939fa613b5 | [
"MIT"
] | 1 | 2018-09-30T07:28:59.000Z | 2018-10-23T07:06:38.000Z | gMotifs/inc.cpp | matteocereda/RNAmotifs | dc1498e867e84ed19322920d7b0299939fa613b5 | [
"MIT"
] | 3 | 2016-12-16T07:49:25.000Z | 2020-04-07T05:35:01.000Z | /***************************************************************************
* Copyright (C) 2010 by Matteo Cereda *
* mcereda@tinca.bp.lnf.it *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "inc.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
void options::defaults() {
mouse = false;
search = string("");
protein = string("");
date = string("");
dIRZ = 0.1;
dIRO = 1;
regions[0] = 1000;
regions[1] = 2000;
regions[2] = 3000;
regions[3] = 4000;
inExon = 50;
inIntron = 200;
mlen = 0;
microarray_rows = 0;
path_splicing_change = string("");
tetramers = string("");
}
options::options() {
defaults();
}
void options::print(ostream & out) {
cout << "Mouse: " << mouse << endl;
cout << "Analysis folder: " << protein<< endl;
cout << "Search RSYW: " << search << endl;
cout << "dIRZ: " << dIRZ << endl;
cout << "dIRO: " << dIRO << endl;
cout << "inExon: " << inExon << endl;
cout << "inIntron: " << inIntron << endl;
cout << "Path SP: " << path_splicing_change << endl;
cout << "Path Tetra: " << tetramers << endl;
cout << "Array rows: " << microarray_rows << endl << endl;
cout << "Motif Length: " << mlen << endl;
}
options::options(int argc,char *argv[]) {
defaults();
AnyOption opt;
opt.addUsage( "tetramer " );
opt.addUsage( "Usage: " );
opt.addUsage( "" );
opt.addUsage( " -h --help Prints this help " );
opt.addUsage( " -c --config-file Read configuration file" );
opt.addUsage( "" );
opt.setOption( "config-file", 'c');
opt.setFlag( "help", 'h' );
opt.processCommandArgs( argc, argv );
if ( ! opt.hasOptions()) opt.printUsage();
if ( opt.getFlag( "help" ) || opt.getFlag( 'h' ) ) opt.printUsage();
if( opt.getValue( 'c' ) != NULL || opt.getValue( "config-file" ) != NULL ){
ifstream in(opt.getValue( 'c' ));
if(in.is_open()){
string line;
int i = 0;
while(getline(in,line)){
cout << line.c_str() << endl;
string param = line.substr(line.find("=")+1,line.length());
cout << param.c_str() << endl;
if(i==0){
if(strcmp(param.c_str(),"Mouse")==0) mouse=true;
} else if (i==1){
path_splicing_change = param;
} else if (i==2){
tetramers = param;
} else if (i==3){
protein=param;
} else if (i==4){
search=param;
}
i++;
}
if (search.compare("R")==0){
tetramers = tetramers + string("/r/");
protein = protein + string("/r/");
}else if (search.compare("N")==0) {
tetramers = tetramers + string("/nr/");
protein = protein + string("/nr/");
}
int ret = mkdir(protein.c_str(),0775);
microarray_rows = (mouse)?(32874):(53624);
}else {
cout << "invalid configuration file" << endl;
}
}
}
//------------------------------------------------------
bln::bln(){}
bln::bln(string &line){
istringstream linestream(line);
string token;
vector<string> row;
while (getline(linestream, token, '\t')) row.push_back(token);
if(row.size()>0){
strcpy(chr,row[0].c_str());
chromStart = atoi(row[1].c_str());
chromEnd = atoi(row[2].c_str());
strand_num = atoi(row[3].c_str());
forw = (strand_num>0)?(true):(false);
if(pos_map_end && cat_of_change) sprintf(mix,"CE_%d_%d",cat_of_change,pos_map_end);
cDNA = 1;
}
}
bln::bln(const bln & tocopy){
rowID = tocopy.rowID;
myRID = tocopy.myRID;
cat_of_change = tocopy.cat_of_change;
strcpy(chr,tocopy.chr);
strand_num = tocopy.strand_num;
forw = tocopy.forw;
cDNA = tocopy.cDNA;
chromStart = tocopy.chromStart;
chromEnd = tocopy.chromEnd;
pos_map_start = tocopy.pos_map_start;
pos_map_end = tocopy.pos_map_end;
strcpy(mix,tocopy.mix);
}
void bln::print(ostream &out){
out << chr << '\t'
<< chromEnd << '\t'
<< pos_map_end << '\t'
<< strand_num << '\t'
<< myRID << '\t'
<< rowID << '\t'
<< cat_of_change << endl;
};
void bln::printAll(ostream &out){
out << chr << '\t'
<< chromStart << '\t'
<< chromEnd << '\t'
<< strand_num << '\t';
if(forw)
out << pos_map_start << '\t'
<< pos_map_end << '\t';
else
out << pos_map_end << '\t'
<< pos_map_start << '\t';
out << myRID << '\t'
<< rowID << '\t'
<< cat_of_change << endl;
};
void bln::printRank(ostream &out){
out << pos_map_end << '\t'
<< cat_of_change << '\t'
<< cDNA << endl;
};
void bln::readExpandedLine(string &line){}
void bln::set_bed_on_the_map ( options opt, bool forw, int region, unsigned int region_start, unsigned int region_stop,
unsigned int geno_bound, unsigned int inIntron, unsigned int inExon ){
int delta_start = abs( (int)geno_bound - (int)chromStart ),
delta_stop = abs( (int)chromEnd - (int)geno_bound );
// [ region_start, region_stop ]
if( region_start <= chromStart && chromEnd <= region_stop ){
if(forw){
if( chromStart <= geno_bound) pos_map_start = opt.regions[ region ] - delta_start ;
else pos_map_start = opt.regions[ region ] + delta_start ;
if( chromEnd <= geno_bound) pos_map_end = opt.regions[ region ] - delta_stop ;
else pos_map_end = opt.regions[ region ] + delta_stop ;
}else{
if(chromStart <= geno_bound) pos_map_start = opt.regions[ 3-region ] + delta_start;
else pos_map_start = opt.regions[ 3-region ] - delta_start;
if(chromEnd <= geno_bound) pos_map_end = opt.regions[ 3-region ] + delta_stop;
else pos_map_end = opt.regions[ 3-region ] - delta_stop;
}
// [region_start, no]
}else if(region_start<=chromStart && chromEnd > region_stop ){
if(forw){
if(chromStart <= geno_bound) pos_map_start = opt.regions[ region ] - delta_start ;
else pos_map_start = opt.regions[ region ] + delta_start ;
if(region==0 || region==2) pos_map_end = opt.regions[ region ] + inIntron ; // end
else pos_map_end = opt.regions[ region ] + inExon ; // end
}else{
if(chromStart <= geno_bound) pos_map_start = opt.regions[ 3-region ] + delta_start;
else pos_map_start = opt.regions[ 3-region ] - delta_start;
if(region==0 || region==2) pos_map_end = opt.regions[ 3-region ] - inIntron ; // end
else pos_map_end = opt.regions[ 3-region ] - inExon ; // end
}
// [ no, firstaregion_stop]
}else if(chromStart<region_start && chromEnd<=region_stop){
if(forw){
if(region==0 || region==2) pos_map_start = opt.regions[ region ] - inExon; // start
else pos_map_start = opt.regions[ region ] - inIntron;
if(chromEnd <= geno_bound) pos_map_end = opt.regions[ region ] - delta_stop ;
else pos_map_end = opt.regions[ region ] + delta_stop ;
}else{
if(region==0 || region==2) pos_map_start = opt.regions[ 3-region ] + inExon;
else pos_map_start = opt.regions[ 3-region ] + inIntron;
if(chromEnd <= geno_bound) pos_map_end = opt.regions[ 3-region ] + delta_stop;
else pos_map_end = opt.regions[ 3-region ] - delta_stop;
}
// [ no, no ]
}else if( chromStart<region_start && chromEnd>region_stop){
if(forw){
if(region==0 || region==2){
pos_map_start = opt.regions[ region ] - inExon;
pos_map_end = opt.regions[ region ] + inIntron;
}else{
pos_map_start = opt.regions[ region ] - inIntron;
pos_map_end = opt.regions[ region ] + inExon;
}
}else{
if(region==0 || region==2){
pos_map_start = opt.regions[ 3-region ] + inExon;
pos_map_end = opt.regions[ 3-region ] - inIntron;
}else{
pos_map_start = opt.regions[ 3-region ] + inIntron;
pos_map_end = opt.regions[ 3-region ] - inExon;
}
}
}
};
void bln::set_bed_middle_on_the_map( options opt, int middle_position, bool forw, int region, unsigned int region_start, unsigned int region_stop, unsigned int geno_bound, unsigned int inIntron, unsigned int inExon ){
int delta = abs( (int)geno_bound - (middle_position) );
int pos_map;
if(forw){
if( (unsigned int) middle_position <= geno_bound) pos_map = opt.regions[ region ] - delta ;
else pos_map = opt.regions[ region ] + delta ;
}else{
if((unsigned int) middle_position <= geno_bound) pos_map = opt.regions[ 3-region ] + delta;
else pos_map = opt.regions[ 3-region ] - delta;
}
pos_map_start = pos_map;
pos_map_end = pos_map;
};
bool sortingBed(const bln & b1,const bln & b2){
return b1.rowID<b2.rowID;
}
bool sortingMyRID(const bln & b1,const bln & b2){
return b1.myRID<b2.myRID;
}
bool sortingCOC(const bln & b1,const bln & b2){
return b1.cat_of_change<b2.cat_of_change;
}
bool sortingPosMap(const bln & b1,const bln & b2){
return b1.pos_map_end<b2.pos_map_end;
}
bool sortingBedMix(const bln & b1,const bln & b2){
// return (string(b1.mix) < string(b2.mix));
int pr1=0,pr2=0;
if(b1.cat_of_change==1) pr1=10;
else if(b1.cat_of_change==0) pr1=1;
else if(b1.cat_of_change==(-1)) pr1=(-10);
if(b2.cat_of_change==1) pr2=10;
else if(b2.cat_of_change==0) pr2=1;
else if(b2.cat_of_change==(-1)) pr2=(-10);
int a = pr1*b1.pos_map_end;
int b = pr2*b2.pos_map_end;
if(a<0 && b<0) return a>b;
else return a<b; //quasi ok
}
//------------------------------------------------------
windows::windows(){};
windows::windows(const bln &tocopy):bln(tocopy){
sum1=0;
sum2=0;
sum3=0;
sum4=0;
}
void windows::setSums(bln mybln,options opt){
unsigned int reg1_start = opt.regions[0]-opt.inExon, reg1_stop = opt.regions[0]+opt.inIntron,
reg2_start = opt.regions[1]-opt.inIntron, reg2_stop = opt.regions[1]+opt.inExon,
reg3_start = opt.regions[2]-opt.inExon, reg3_stop = opt.regions[2]+opt.inIntron,
reg4_start = opt.regions[3]-opt.inIntron, reg4_stop = opt.regions[3]+opt.inExon;
if(reg1_start<=mybln.pos_map_end && mybln.pos_map_end<=reg1_stop) sum1+=mybln.cDNA;
else if(reg2_start<=mybln.pos_map_end && mybln.pos_map_end<=reg2_stop) sum2+=mybln.cDNA;
else if(reg3_start<=mybln.pos_map_end && mybln.pos_map_end<=reg3_stop) sum3+=mybln.cDNA;
else if(reg4_start<=mybln.pos_map_end && mybln.pos_map_end<=reg4_stop) sum4+=mybln.cDNA;
}
void windows::print_myRID(ofstream &out){
out << myRID << "\t" << chromStart << "\t" << sum1 << "\t" << sum2 << "\t" << sum3 << "\t" << sum4 << endl;
}
void windows::print_rowID(ofstream &out){
out << rowID << "\t" << chromStart << "\t" << sum1 << "\t" << sum2 << "\t" << sum3 << "\t" << sum4 << endl;
}
//------------------------------------------------------
void expand(vector<bln> bedres, vector<bln> &bedexp){
if(bedres.size()>0){
unsigned int gen_end,rna_end;
for(unsigned int g=0; g<bedres.size();g++){
gen_end = bedres[g].chromEnd;
rna_end = bedres[g].pos_map_end;
if(bedres[g].strand_num>0){
for(int i=0; i<bedres[g].strand_num; i++){
bln bb(bedres[g]);
bb.chromEnd = gen_end - i;
bb.pos_map_end = rna_end - i;
sprintf(bb.mix,"CE_%d_%d",bb.pos_map_end,bb.cat_of_change);
bedexp.push_back(bb);
}
} else {
for( int i=0; i<(-bedres[g].strand_num); i++){
bln bb(bedres[g]);
bb.chromEnd = gen_end - i;
bb.pos_map_end = rna_end + i;
sprintf(bb.mix,"CE_%d_%d",bb.pos_map_end,bb.cat_of_change);
bedexp.push_back(bb);
}
}
}
}else{
cout << "no size" << endl;
throw ("Expand: no results");
}
}
void dIrank( vector<bln> bedexp, options opt, vector <windows> &wins){
unsigned int c=0,a=0;
wins.push_back( windows(bedexp[a]) );
wins[c].setSums( bedexp[a], opt );
for( a=1; a<bedexp.size(); a++ ){
if( bedexp[a].myRID == bedexp[a-1].myRID ){
wins[c].setSums(bedexp[a],opt);
}else{
c++;
wins.push_back( windows( bedexp[a] ) );
wins[c].setSums( bedexp[a],opt );
}
}
}
//------------------------------------------------------
int EM_clip_microarray_CE(options &opt,const char *sp_fname,const char *bed_fname, const char *output_fname, const char * tet_name,ofstream & stats){
try{
ifstream in(sp_fname), fbed(bed_fname);
ofstream fout(output_fname),fstats(),fres1("/tmp/out.txt");
string line,f;
vector<bln> bedlines, bedres;
unsigned int CEone = 0, rCEone = 0,
CEminone = 0, rCEminone = 0,
CEzero = 0, rCEzero = 0,
offset = 0;
if(in.is_open() && fbed.is_open()){
while(getline(fbed,line)) bedlines.push_back(bln(line)); // Read BED file
fbed.close();
while(getline(in,f)){ // read splicing change lines and evaluate bed positions
gString spline=f;
vector<gString> pars;
spline.split(';',pars);
string chr = string(pars[2]);
bool forw = (string(pars[3]).compare("+")==0)?(true):(false);
unsigned int myRID = atoi(string(pars[0]).c_str()),
rowID = atoi(string(pars[1]).c_str()),
skip_start = atoi(string(pars[4]).c_str()) - offset, // posizioni genomiche
in_start = atoi(string(pars[5]).c_str()),
in_stop = atoi(string(pars[6]).c_str()),
skip_stop = atoi(string(pars[7]).c_str()) + offset;
double dIRank = atof(string(pars[8]).c_str());
int cofc = 2;
unsigned int firstaregion_start = skip_start - opt.inExon,
firstaregion_stop = skip_start + opt.inIntron,
secondaregion_start = in_start - opt.inIntron,
secondaregion_stop = in_start + opt.inExon,
thirdaregion_start = in_stop - opt.inExon,
thirdaregion_stop = in_stop + opt.inIntron,
fourtharegion_start = skip_stop - opt.inIntron,
fourtharegion_stop = skip_stop + opt.inExon,
left_intron_middle = skip_start + round((in_start-skip_start)/2),
exon_middle = in_start + round((in_stop-in_start)/2),
right_intron_middle = in_stop + round((skip_stop-in_stop)/2);
if((-opt.dIRZ)<=dIRank && dIRank<=opt.dIRZ){
CEzero++;
cofc = 0;
}else if(dIRank>=opt.dIRO){
CEone++;
cofc = 1;
}else if(dIRank<=(-opt.dIRO)){
CEminone++;
cofc= -1;
}
/*----------------------------
updating regions boundaries
-----------------------------*/
if( left_intron_middle < firstaregion_stop ) firstaregion_stop = left_intron_middle;
if( left_intron_middle > secondaregion_start ) secondaregion_start = left_intron_middle;
if( exon_middle < secondaregion_stop ) secondaregion_stop = exon_middle;
if( exon_middle > thirdaregion_start ) thirdaregion_start = exon_middle;
if( right_intron_middle < thirdaregion_stop ) thirdaregion_stop = right_intron_middle;
if( right_intron_middle > fourtharegion_start ) fourtharegion_start = right_intron_middle;
unsigned int inIntronLeft = firstaregion_stop - skip_start,
inExon = secondaregion_stop - in_start,
inIntronRight = thirdaregion_stop - in_stop;
bool spara=false;
for(unsigned int g=0; g<bedlines.size();g++){
if(strcmp(chr.c_str(),bedlines[g].chr)==0 &&
(forw==bedlines[g].forw) &&
(bedlines[g].chromStart<=fourtharegion_stop) && (bedlines[g].chromEnd>=firstaregion_start) ){
bln bed(bedlines[g]);
bed.rowID = rowID;
bed.myRID = myRID;
bed.cat_of_change = cofc;
/*--------------------
FIRST REGION
--------------------*/
if( bedlines[g].chromStart <= firstaregion_stop && bedlines[g].chromEnd >= firstaregion_start ){
bed.set_bed_on_the_map(opt, forw, 0, firstaregion_start, firstaregion_stop, skip_start, inIntronLeft, opt.inExon);
bedres.push_back(bed);
//spara=true;
}
/*--------------------
SECOND REGION
--------------------*/
else if( bedlines[g].chromStart <= secondaregion_stop && bedlines[g].chromEnd >= secondaregion_start ){
bed.set_bed_on_the_map(opt, forw, 1, secondaregion_start, secondaregion_stop, in_start, inIntronLeft, inExon);
bedres.push_back(bed);
if(bedlines[g].chromEnd >= (secondaregion_start+100) && bedlines[g].chromStart <= (secondaregion_stop-15)) spara=true;
}
/*--------------------
THIRD REGION
--------------------*/
else if( bedlines[g].chromStart <= thirdaregion_stop && bedlines[g].chromEnd >= thirdaregion_start ){
bed.set_bed_on_the_map(opt, forw, 2, thirdaregion_start, thirdaregion_stop, in_stop, inIntronRight, inExon);
bedres.push_back(bed);
if(bedlines[g].chromEnd >= (thirdaregion_start+15) && bedlines[g].chromStart <= (thirdaregion_stop-130)) spara=true;
}
/*--------------------
FOURTH REGION
--------------------*/
else if( bedlines[g].chromStart <= fourtharegion_stop && bedlines[g].chromEnd >= fourtharegion_start ){
bed.set_bed_on_the_map(opt, forw, 3, fourtharegion_start, fourtharegion_stop, skip_stop, inIntronRight, opt.inExon);
bedres.push_back(bed);
//spara=true;
}
}
}
if(spara==true){
if(cofc==0){ rCEzero++;
}else if(cofc==1){ rCEone++;
}else if(cofc==(-1)){ rCEminone++;
}
}
} // end splicing change file
fout << "CE1 = " << CEone << ", CE-1 = " << CEminone <<", CE0 = " << CEzero << endl;
stats << tet_name << "\t" << rCEone << "\t" << rCEminone << "\t" << rCEzero << endl;
if(bedres.size()>0){
// Expand
// -------
vector<bln> bedexp;
expand( bedres, bedexp );
sort(bedexp.begin(),bedexp.end(),sortingBedMix); // for(unsigned int g=0; g<bedexp.size();g++) bedexp[g].print(fres1);
// dIrank
//-------
vector <bln> bedrank;
unsigned int c=0, a=0;
while( a<bedexp.size() ){
bln bb(bedexp[a]);
if(a==0){
bb.cDNA=1;
bedrank.push_back( bb );
}else{
if(bedexp[a].pos_map_end==bedexp[a-1].pos_map_end && bedexp[a].cat_of_change==bedexp[a-1].cat_of_change){
bedrank[c].cDNA++;
}else{
c++;
bb.cDNA=1;
bedrank.push_back( bb );
}
}
a++;
}
for(unsigned int g=0; g<bedrank.size();g++) bedrank[g].printRank(fout);
}else cout << "no results!" << endl;
}else cout << "Impossible open data file: "<< sp_fname << endl;
}catch(gException &e){
cout << e.what() << endl;
}catch(...){
cout <<"\tException";
}
return 0;
}
int count_per_regions(options &opt,const char *sp_fname,const char *bed_fname, const char *output_fname){
try{
ifstream in(sp_fname), fbed(bed_fname);
ofstream fout(output_fname);
string line,f;
vector<bln> bedlines, bedres;
unsigned int CEone = 0,
CEminone = 0,
CEzero = 0;
fout << "myRID\trowID\ttype\thits_region1\thits_region2\thits_region3\n";
if(in.is_open() && fbed.is_open()){
while(getline(fbed,line)) bedlines.push_back(bln(line)); // Read BED file
fbed.close();
while(getline(in,f)){ // read splicing change lines and evaluate bed positions
/*----------------------------
LOADING EXON
-----------------------------*/
gString spline=f;
vector<gString> pars;
spline.split(';',pars);
string chr = string(pars[2]);
bool forw = (string(pars[3]).compare("+")==0)?(true):(false);
unsigned int myRID = atoi(string(pars[0]).c_str()),
rowID = atoi(string(pars[1]).c_str()),
in_start = atoi(string(pars[5]).c_str()),
in_stop = atoi(string(pars[6]).c_str());
double dIRank = atof(string(pars[8]).c_str());
unsigned int exon_region1_stop = in_start + 30,
exon_region2_start = in_stop - 30,
exon_middle = in_start + round((in_stop-in_start)/2),
r1_start = in_start - 35,
r1_stop = in_start - 5,
r3_start = in_stop + 10,
r3_stop = in_stop + 40;
int cofc = 2;
if((-opt.dIRZ)<=dIRank && dIRank<=opt.dIRZ){
CEzero++;
cofc = 0;
}else if(dIRank>=opt.dIRO){
CEone++;
cofc = 1;
}else if(dIRank<=(-opt.dIRO)){
CEminone++;
cofc= -1;
}
/*----------------------------
updating regions boundaries
-----------------------------*/
if( exon_middle < exon_region1_stop ) exon_region1_stop = exon_middle;
if( exon_middle > exon_region2_start ) exon_region2_start = exon_middle;
bool hits_region1 = false,
hits_region2 = false,
hits_region3 = false;
/*----------------------------
load teramer hits
-----------------------------*/
for(unsigned int g=0; g<bedlines.size();g++){
if(strcmp(chr.c_str(),bedlines[g].chr)==0 &&
(forw==bedlines[g].forw)){
if (!forw){
r1_start = in_stop + 5,
r1_stop = in_stop + 35, // piu alta
r3_start = in_start - 40, // piu bassa
r3_stop = in_start - 10;
}
// REGION 1
if( bedlines[g].chromStart <= r1_stop && bedlines[g].chromEnd >= r1_start ) { hits_region1 = true; }
// REGION 2
else if( bedlines[g].chromStart <= exon_region1_stop && bedlines[g].chromEnd >= in_start ){ hits_region2 = true; }
else if( bedlines[g].chromStart <= in_stop && bedlines[g].chromEnd >=exon_region2_start ){ hits_region2 = true; }
// REGION 3
else if( bedlines[g].chromStart <= r3_stop && bedlines[g].chromEnd >= r3_start ){ hits_region3 = true; }
}
}
fout << myRID << "\t" << rowID << "\t" << cofc << "\t" << hits_region1 << "\t" << hits_region2 << "\t" << hits_region3 << "\n";
}
}else cout << "Impossible open data file: "<< sp_fname << endl;
}catch(gException &e){
cout << e.what() << endl;
}catch(...){
cout <<"\tException";
}
return 0;
}
int counting_per_region(options &opt){
string folder = opt.protein,
command = string("wc -l ") + opt.tetramers + string("*.bed > ") + opt.tetramers + string("tetramers_files.txt");
system(command.c_str());
string fin = opt.tetramers + string("tetramers_files.txt");
cout << fin.c_str() << endl;
ifstream in(fin.c_str());
if(in.is_open()){ // load tetramers bed file in the folder
unsigned int rows_bed;
string bed_fname, output_fname,
splicing_fname = opt.path_splicing_change,
filelist_name = folder + string("filelist_count.tsv");
ofstream filelist(filelist_name.c_str());
while(!in.eof()){ // load single tet bed file
in >> rows_bed >> bed_fname;
if(bed_fname.compare("total")!=0){
size_t p1 = bed_fname.find_last_of('/');
string tet_name = bed_fname.substr(p1+1).substr(0,4);
if(bed_fname.substr(p1+1).compare("totale")!=0){
string fout = opt.protein + tet_name.c_str() + string("_region_count.tsv");
count_per_regions(opt,splicing_fname.c_str(),bed_fname.c_str(),fout.c_str());
filelist << tet_name.c_str() << string("_region_count.tsv") << endl;
}
}
}
}else cout << "impossible opening file" << endl;
in.close();
//loop on splicing change human files
return 0;
}
int tetramer(options &opt){
/*-------------------------------
RUN ANALISYS
-------------------------------*/
int ret = 0;
string folder = opt.protein ,
command = string("wc -l ") + opt.tetramers + string("*.bed > ") + opt.tetramers + string("tetramers_files.txt");
system(command.c_str());
string fin = opt.tetramers + string("tetramers_files.txt");
ifstream in(fin.c_str());
if(in.is_open()){
string bed_fname, output_fname,
splicing_fname = opt.path_splicing_change ,
stats_name = folder + string("STATS.txt"),
filelist_name = folder + string("filelist.txt");
unsigned int rows_bed;
cout << stats_name << endl;
ofstream stats(stats_name.c_str()),
filelist(filelist_name.c_str());
while(!in.eof()){
in >> rows_bed >> bed_fname;
if(bed_fname.compare("total")!=0){
size_t p1 = bed_fname.find_last_of('/');
string tet_name = bed_fname.substr(p1+1).substr(0,4);
if(bed_fname.substr(p1+1).compare("totale")!=0){
string fout = opt.protein + bed_fname.substr(p1+1).c_str();
ret = EM_clip_microarray_CE(opt,splicing_fname.c_str(),bed_fname.c_str(),fout.c_str(),tet_name.c_str(),stats);
filelist << bed_fname.substr(p1+1).c_str() << endl;
}
}
}
}else cout << "impossible opening file" << endl;
in.close();
return ret;
}
| 34.354248 | 217 | 0.564743 | [
"vector"
] |
900f61878aacee3fbf7ce6f4905eabbb37f48284 | 23,271 | cpp | C++ | frontend/typer.cpp | NicolaiLS/becarre | cf23e80041f856f50b9f96c087819780dfe1792c | [
"MIT"
] | null | null | null | frontend/typer.cpp | NicolaiLS/becarre | cf23e80041f856f50b9f96c087819780dfe1792c | [
"MIT"
] | null | null | null | frontend/typer.cpp | NicolaiLS/becarre | cf23e80041f856f50b9f96c087819780dfe1792c | [
"MIT"
] | null | null | null | #include <becarre/frontend/typer.hpp>
#include <becarre/frontend/typing/equality_checker.hpp>
#include <becarre/frontend/typing/normalisation.hpp>
#include <becarre/frontend/typing/printer.hpp>
#include <becarre/frontend/typing/specialisation.hpp>
#include <becarre/frontend/typing/substitution.hpp>
#include <becarre/frontend/typing/type_variables_lowering.hpp>
#include <becarre/utility/algorithm.hpp>
#include <algorithm>
#include <functional>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <type_traits>
#include <variant>
#include <vector>
namespace becarre::frontend
{
//
// Helper visitors
//
namespace visitors
{
static std::optional<std::string> get_optional_label_from_left_value(ast::Left_value const & left_value)
{
struct Visitor : public ast::Visitor<Visitor>
{
using Super = ast::Visitor<Visitor>;
using Super::traverse;
using Super::visit;
using Super::leave;
std::optional<std::string> label = std::nullopt;
bool traverse(ast::Identifier<ast::Left_value> const & identifier)
{
this->label = identifier.token.value;
return true;
}
};
Visitor visitor;
visitor.traverse(left_value);
return visitor.label;
}
struct Annotation : public ast::Visitor<Annotation>
{
using Super = ast::Visitor<Annotation>;
using Super::traverse;
using Super::visit;
using Super::leave;
Annotation(Typer & typer, typing::Type & fresh_type)
: typer(typer)
, fresh_type(&fresh_type)
{ }
Typer & typer;
typing::Type * fresh_type;
//
// Traverse / Visit / Leave
//
bool traverse(ast::Function const & function)
{
// Save current fresh type:
decltype(auto) saved_fresh_type = this->fresh_type;
std::vector<typing::Type> parameters;
typing::Type return_type = this->typer.environment.fresh_type();
// Retrieve parameters:
std::transform(
function.parameters.elements.begin(), function.parameters.elements.end(),
std::back_inserter(parameters),
[this](auto const & parameter)
{
auto fresh_type = this->typer.environment.fresh_type();
this->fresh_type = &fresh_type;
this->traverse(parameter);
typing::normalisation::apply(*this->fresh_type);
return *this->fresh_type;
}
);
// Retrieve return type:
this->fresh_type = &return_type;
this->traverse(function.return_type);
typing::normalisation::apply(*this->fresh_type);
// Reload saved fresh type:
this->fresh_type = saved_fresh_type;
auto function_type = typing::types::function(parameters, return_type);
typing::substitution::apply(*this->fresh_type, function_type);
return true;
}
bool visit(ast::Identifier<ast::Type> const & identifier)
{
auto & found = this->typer.environment.lookup(identifier.token.value);
auto & type = shallow_cast_to<typing::types::Meta>(found)->value.value();
typing::substitution::apply(*this->fresh_type, type);
return true;
}
bool traverse(ast::Tuple<ast::Type> const & tuple)
{
if (tuple.elements.empty())
{
auto nothing_type = typing::types::nothing();
typing::substitution::apply(*this->fresh_type, nothing_type);
return true;
}
std::vector<typing::types::Tuple::Element> elements;
std::transform(
tuple.elements.begin(), tuple.elements.end(),
std::back_inserter(elements),
[this](auto const & element)
{
auto element_type = this->typer.environment.fresh_type();
auto * saved_fresh_type = this->fresh_type;
this->fresh_type = &element_type;
this->traverse(element.type);
this->fresh_type = saved_fresh_type;
if (element.label.has_value())
{
return typing::types::tuple_element(element.label->token.value, element_type);
}
return typing::types::tuple_element(element_type);
}
);
if (elements.size() == 1 && !elements[0].label.has_value())
{
typing::substitution::apply(*this->fresh_type, elements[0].type.value());
return true;
}
auto tuple_type = typing::types::tuple(elements);
typing::substitution::apply(*this->fresh_type, tuple_type);
return true;
}
};
struct Pattern : public ast::Visitor<Pattern>
{
using Super = ast::Visitor<Pattern>;
using Super::traverse;
using Super::visit;
using Super::leave;
Pattern(Typer & typer, typing::Type & fresh_type)
: typer(typer)
, fresh_type(&fresh_type)
, bound_types()
{ }
Typer & typer;
typing::Type * fresh_type;
std::vector<std::reference_wrapper<typing::Type>> bound_types;
//
// Traverse / Visit / Leave
//
bool visit(ast::Wildcard const & wildcard)
{
auto & id_type = this->typer.environment.bind(
wildcard.internal_identifier,
*this->fresh_type
);
this->bound_types.emplace_back(id_type);
typing::substitution::apply(*this->fresh_type, id_type);
return true;
}
bool visit(ast::Identifier<ast::Left_value> const & identifier)
{
auto & id_type = this->typer.environment.bind(
identifier.token.value,
*this->fresh_type
);
this->bound_types.emplace_back(id_type);
typing::substitution::apply(*this->fresh_type, id_type);
return true;
}
bool traverse(ast::Tuple<ast::Left_value> const & tuple)
{
if (tuple.elements.empty())
{
auto nothing_type = typing::types::nothing();
typing::substitution::apply(*this->fresh_type, nothing_type);
return true;
}
std::vector<typing::types::Tuple::Element> elements;
std::transform(
tuple.elements.begin(), tuple.elements.end(),
std::back_inserter(elements),
[this](auto const & element)
{
auto element_type = this->typer.environment.fresh_type();
auto * saved_fresh_type = this->fresh_type;
this->fresh_type = &element_type;
this->traverse(element.left_value);
this->fresh_type = saved_fresh_type;
if (element.type)
{
auto type_variable = this->typer.environment.fresh_type();
Annotation annotation_visitor(this->typer, type_variable);
annotation_visitor.traverse(element.type);
typing::substitution::apply(*this->fresh_type, type_variable);
}
typing::normalisation::apply(*this->fresh_type);
return typing::types::Tuple::Element{
.label = get_optional_label_from_left_value(element.left_value.value()),
.type = element_type
};
}
);
if (elements.size() == 1 && !elements[0].label.has_value())
{
typing::substitution::apply(*this->fresh_type, elements[0].type.value());
return true;
}
auto tuple_type = typing::types::tuple(elements);
typing::substitution::apply(*this->fresh_type, tuple_type);
return true;
}
};
struct Infer : public ast::Visitor<Infer>
{
using Super = ast::Visitor<Infer>;
using Super::traverse;
using Super::visit;
using Super::leave;
Infer(Typer & typer, typing::Type & fresh_type)
: typer(typer)
, fresh_type(&fresh_type)
{ }
Typer & typer;
typing::Type * fresh_type;
//
// Traverse / Visit / Leave
//
bool traverse(ast::Binary const & binary)
{
auto call = ast::Call{
.callable = ast::Expression{binary.operator_},
.arguments = ast::Tuple<ast::Expression>{{
ast::Tuple_element<ast::Expression>{
.label = std::nullopt,
.expression = binary.left
},
ast::Tuple_element<ast::Expression>{
.label = std::nullopt,
.expression = binary.right
}
}}
};
return this->traverse(call);
}
bool visit(ast::Boolean const &)
{
auto boolean_type = typing::types::boolean();
typing::substitution::apply(*this->fresh_type, boolean_type);
return true;
}
bool traverse(ast::Call const & call)
{
typing::Type * saved_fresh_type = nullptr;
// Retrieve called expression type:
auto retrieved_type = this->typer.environment.fresh_type();
saved_fresh_type = this->fresh_type;
this->fresh_type = &retrieved_type;
this->traverse(call.callable);
this->fresh_type = saved_fresh_type;
auto function_type = is_of_type<typing::types::Function>(retrieved_type)
? typing::specialisation::apply(retrieved_type, this->typer.environment)
: retrieved_type;
// Retrieve given arguments:
std::vector<typing::Type> arguments;
std::transform(
call.arguments.elements.begin(), call.arguments.elements.end(),
std::back_inserter(arguments),
[this, &saved_fresh_type](auto const & argument)
{
auto type = this->typer.environment.fresh_type();
saved_fresh_type = this->fresh_type;
this->fresh_type = &type;
this->traverse(argument.expression);
this->fresh_type = saved_fresh_type;
return type;
}
);
// Fresh return type:
auto return_type = this->typer.environment.fresh_type();
// Build function type:
auto built_called_type = typing::types::function(arguments, return_type);
// Apply substitution on both called and built types:
if (auto error = typing::substitution::apply(function_type, built_called_type); error.has_value())
{
std::ostringstream message;
message << "Typing error: Incompatible types with function call:\n"
<< "- called type : `" << function_type << "`\n"
<< "- applied type : `" << typing::Type(built_called_type) << "`";
throw std::runtime_error(message.str());
}
// Resulting type of call is return type of function:
if (auto error = typing::substitution::apply(*this->fresh_type, return_type); error.has_value())
{
std::ostringstream message;
message << "Typing error: Incompatibility between returned type and expected type with function call:\n"
<< "- expected : `" << *this->fresh_type << "`\n"
<< "- actual : `" << return_type << "`";
throw std::runtime_error(message.str());
}
return true;
}
bool visit(ast::Character const &)
{
auto character_type = typing::types::character();
typing::substitution::apply(*this->fresh_type, character_type);
return true;
}
bool traverse(ast::Closure const & closure)
{
auto body_fresh_type = this->typer.environment.fresh_type();
this->typer.environment.new_namespace();
// Bind parameters to local namespace:
std::vector<typing::Type> parameters;
if (closure.header.has_value())
{
std::transform(
closure.header->parameters.elements.begin(), closure.header->parameters.elements.end(),
std::back_inserter(parameters),
[this](auto const & parameter)
{
auto pattern_type_variable = this->typer.environment.fresh_type();
Pattern pattern_visitor(this->typer, pattern_type_variable);
pattern_visitor.traverse(parameter.left_value);
if (parameter.type.has_value())
{
auto type_variable = this->typer.environment.fresh_type();
Annotation annotation_visitor(this->typer, type_variable);
annotation_visitor.traverse(parameter.type);
typing::substitution::apply(pattern_type_variable, type_variable);
}
typing::normalisation::apply(pattern_type_variable);
return pattern_type_variable;
}
);
}
// Bind "$$" in local namespace:
{
auto function_type = typing::types::function(parameters, body_fresh_type);
this->typer.environment.bind("$$", function_type);
}
auto & function_type = this->typer.environment.lookup("$$");
// Return type:
auto * saved_fresh_type = this->fresh_type;
this->fresh_type = &body_fresh_type;
this->typer.environment.current_namespace().expect_implicit_parameters = !closure.header.has_value();
this->traverse(closure.body);
this->typer.environment.current_namespace().expect_implicit_parameters = false;
this->fresh_type = saved_fresh_type;
if (closure.header.has_value() && closure.header->return_type.has_value())
{
auto return_type_variable = this->typer.environment.fresh_type();
Annotation annotation_visitor(this->typer, return_type_variable);
annotation_visitor.traverse(closure.header->return_type.value());
typing::substitution::apply(body_fresh_type, return_type_variable);
}
typing::substitution::apply(*this->fresh_type, function_type);
this->typer.environment.exit_namespace();
return true;
}
bool visit(ast::Identifier<ast::Expression> const & identifier)
{
auto id_type = this->typer.environment.lookup(identifier.token.value);
typing::substitution::apply(*this->fresh_type, id_type);
return true;
}
bool traverse(ast::Implicit_parameter const & implicit_parameter)
{
if (auto * integer = std::get_if<ast::Integer>(&implicit_parameter.value); integer != nullptr)
{
auto & type = this->manage_implicit_parameter(std::stoi(integer->token.value));
typing::substitution::apply(*this->fresh_type, type);
return true;
}
return this->traverse(ast::Identifier<ast::Expression>{Token::identifier("$$")});
}
bool visit(ast::Integer const &)
{
auto integer_type = typing::types::integer();
typing::substitution::apply(*this->fresh_type, integer_type);
return true;
}
bool traverse(ast::Member_access const & member_access)
{
auto expression_type = this->typer.environment.fresh_type();
// Expression type:
auto * saved_fresh_type = this->fresh_type;
this->fresh_type = &expression_type;
this->traverse(member_access.expression);
this->fresh_type = saved_fresh_type;
typing::normalisation::apply(expression_type);
auto * tuple_type = typing::cast_to<typing::types::Tuple>(expression_type);
if (tuple_type == nullptr)
{
throw std::runtime_error("Typing error: Member access for something else than a tuple is not managed yet.");
}
// TODO: Later, manage member access in it's own class/file/whatever as it will be more
// complex and a full functionality on its own.
auto found_element = tuple_type->elements.end();
if (auto * identifier = std::get_if<ast::Identifier<ast::Expression>>(&member_access.index); identifier != nullptr)
{
found_element = std::find_if(
tuple_type->elements.begin(), tuple_type->elements.end(),
[&identifier](auto const & element)
{
return element.label == identifier->token.value;
}
);
if (found_element == tuple_type->elements.end())
{
std::ostringstream message;
message << "Typing error: Cannot find element by label in tuple:\n"
<< "- label : \"" << identifier->token.value << "\"\n"
<< "- tuple : `" << expression_type << "`";
throw std::runtime_error(message.str());
}
}
if (auto * integer = std::get_if<ast::Integer>(&member_access.index); integer != nullptr)
{
auto index_value = std::stoi(integer->token.value);
if (index_value < 0 || index_value >= tuple_type->elements.size())
{
std::ostringstream message;
message << "Typing error: Tuple element access cannot use an out of bounds index:"
<< "- index : " << index_value << " (tuple size = " << tuple_type->elements.size() << ")\n"
<< "- tuple : `" << expression_type << "`";
throw std::runtime_error(message.str());
}
found_element = std::next(tuple_type->elements.begin(), index_value);
}
// Shouldn't fail here by parsing:
assert(found_element != tuple_type->elements.end());
typing::substitution::apply(*this->fresh_type, found_element->type.value());
return false;
}
bool visit(ast::Operator const & operator_)
{
auto op_type = this->typer.environment.lookup(operator_.token.value);
typing::substitution::apply(*this->fresh_type, op_type);
return true;
}
bool visit(ast::Real const &)
{
auto real_type = typing::types::real();
typing::substitution::apply(*this->fresh_type, real_type);
return true;
}
bool visit(ast::String const &)
{
auto string_type = typing::types::string();
typing::substitution::apply(*this->fresh_type, string_type);
return true;
}
bool traverse(ast::Tuple<ast::Expression> const & tuple)
{
if (tuple.elements.empty())
{
auto nothing_type = typing::types::nothing();
typing::substitution::apply(*this->fresh_type, nothing_type);
return true;
}
std::vector<typing::types::Tuple::Element> elements;
std::transform(
tuple.elements.begin(), tuple.elements.end(),
std::back_inserter(elements),
[this](auto const & element)
{
auto element_type = this->typer.environment.fresh_type();
auto * saved_fresh_type = this->fresh_type;
this->fresh_type = &element_type;
this->traverse(element.expression);
this->fresh_type = saved_fresh_type;
if (element.label)
{
return typing::types::tuple_element(element.label->token.value, element_type);
}
return typing::types::tuple_element(element_type);
}
);
if (elements.size() == 1 && !elements[0].label.has_value())
{
typing::substitution::apply(*this->fresh_type, elements[0].type.value());
return true;
}
if (std::find_if(elements.begin(), elements.end(),
[](auto const & element) { return !typing::is_of_type<typing::types::Meta>(element.type.value()); })
== elements.end())
{
// If all "expressions" of tuple are types, then the tuple is a type:
auto tuple_type = turn_tuple_of_types_into_meta(typing::types::Tuple{elements});
typing::substitution::apply(*this->fresh_type, tuple_type);
return true;
}
auto tuple_type = typing::types::tuple(elements);
typing::substitution::apply(*this->fresh_type, tuple_type);
return true;
}
bool traverse(ast::Unary const & unary)
{
auto call = ast::Call{
.callable = ast::Expression{unary.operator_},
.arguments = ast::Tuple<ast::Expression>{{
ast::Tuple_element<ast::Expression>{
.label = std::nullopt,
.expression = unary.expression
}
}}
};
return this->traverse(call);
}
private:
//
// Helpers
//
bool is_builtin_type(typing::Type const & type) noexcept
{
return typing::is_of_type<typing::types::Boolean>(type)
|| typing::is_of_type<typing::types::Character>(type)
|| typing::is_of_type<typing::types::Integer>(type)
|| typing::is_of_type<typing::types::Nothing>(type)
|| typing::is_of_type<typing::types::Real>(type)
|| typing::is_of_type<typing::types::String>(type);
}
typing::Type turn_tuple_of_types_into_meta(typing::types::Tuple const & tuple) noexcept
{
std::vector<typing::types::Tuple::Element> elements;
std::transform(
tuple.elements.begin(), tuple.elements.end(),
std::back_inserter(elements),
[](auto const & element)
{
return typing::types::Tuple::Element{
.label = element.label,
.type = typing::cast_to<typing::types::Meta>(element.type.value())->value.value()
};
}
);
return typing::types::meta(typing::types::tuple(elements));
}
typing::Type & manage_implicit_parameter(int number)
{
if (!this->typer.environment.current_namespace().expect_implicit_parameters)
{
throw std::runtime_error("Typing error: Implicit parameter used in a closure which header has been provided.");
}
// Retrieve function type:
auto function_type = typing::cast_to<typing::types::Function>(this->typer.environment.lookup("$$"));
// If need be, add missing parameters:
for (int i = function_type->parameters.size(); i <= number; ++i)
{
function_type->parameters.push_back(this->typer.environment.fresh_type());
}
// Return type of specified parameter:
return function_type->parameters[number];
}
};
struct Define : public ast::Visitor<Define>
{
using Super = ast::Visitor<Define>;
using Super::traverse;
using Super::visit;
using Super::leave;
Define(Typer & typer)
: typer(typer)
{ }
Typer & typer;
//
// Traverse / Visit / Leave
//
bool traverse(ast::Binding const & binding)
{
auto pattern_type_variable = this->typer.environment.fresh_type();
auto annotated_type_variable = this->typer.environment.fresh_type();
auto inferred_type_variable = this->typer.environment.fresh_type();
Pattern pattern_visitor(this->typer, pattern_type_variable);
Annotation annotation_visitor(this->typer, annotated_type_variable);
Infer infer_visitor(this->typer, inferred_type_variable);
pattern_visitor.traverse(binding.left_value);
annotation_visitor.traverse(binding.type);
infer_visitor.traverse(binding.expression);
if (auto error = typing::substitution::apply(pattern_type_variable, annotated_type_variable); error)
{
std::ostringstream message;
message << "Typing error: Incompatibility between pattern and annotated type:\n"
<< "- pattern : `" << error->left << "`\n"
<< "- annotated : `" << error->right << "`\n";
throw std::runtime_error(message.str());
}
if (auto error = typing::substitution::check(inferred_type_variable, annotated_type_variable); error)
{
std::ostringstream message;
message << "Typing error: Incompatibility between inferred type and annotated type:\n"
<< "- inferred : `" << error->left << "`\n"
<< "- annotated : `" << error->right << "`\n";
throw std::runtime_error(message.str());
}
if (auto error = typing::substitution::apply(pattern_type_variable, inferred_type_variable); error)
{
std::ostringstream message;
message << "Typing error: Incompatibility between inferred type and pattern type:\n"
<< "- inferred : `" << error->left << "`\n"
<< "- pattern : `" << error->right << "`\n";
throw std::runtime_error(message.str());
}
std::for_each(
pattern_visitor.bound_types.begin(), pattern_visitor.bound_types.end(),
[](auto bound_type) { typing::normalisation::apply(bound_type); }
);
this->typer.environment.clear_type_variables();
typing::type_variables_lowering::apply(pattern_type_variable);
return true;
}
};
} // namespace visitors
//
// Typer :: Public methods
//
Typer::Typer(parsing::Operators & operators) noexcept
: environment(typing::Environment::default_())
, operators(operators)
{ }
typing::Environment Typer::type_ast(Ast const & ast)
{
visitors::Define define(*this);
std::for_each(
ast.begin(), ast.end(),
[&define](auto const & binding)
{
define.traverse(binding);
}
);
return this->environment;
}
//
// Typer :: Static methods
//
typing::Environment Typer::type_all(Ast const & ast)
{
parsing::Operators operators;
Typer typer(operators);
return typer.type_ast(ast);
}
} // namespace becarre::frontend
| 30.660079 | 119 | 0.649693 | [
"vector",
"transform"
] |
9011c23011bcdf9acfae3992bb5ab78fcda3a392 | 6,281 | cc | C++ | third_party/blink/renderer/modules/background_sync/sync_manager.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/modules/background_sync/sync_manager.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/modules/background_sync/sync_manager.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/background_sync/sync_manager.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
SyncManager::SyncManager(ServiceWorkerRegistration* registration,
scoped_refptr<base::SequencedTaskRunner> task_runner)
: registration_(registration),
background_sync_service_(registration->GetExecutionContext()) {
DCHECK(registration);
Platform::Current()->GetBrowserInterfaceBroker()->GetInterface(
background_sync_service_.BindNewPipeAndPassReceiver(task_runner));
}
ScriptPromise SyncManager::registerFunction(ScriptState* script_state,
const String& tag,
ExceptionState& exception_state) {
if (!registration_->active()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Registration failed - no active Service Worker");
return ScriptPromise();
}
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
mojom::blink::SyncRegistrationOptionsPtr sync_registration =
mojom::blink::SyncRegistrationOptions::New();
sync_registration->tag = tag;
background_sync_service_->Register(
std::move(sync_registration), registration_->RegistrationId(),
WTF::Bind(&SyncManager::RegisterCallback, WrapPersistent(this),
WrapPersistent(resolver)));
return promise;
}
ScriptPromise SyncManager::getTags(ScriptState* script_state) {
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
background_sync_service_->GetRegistrations(
registration_->RegistrationId(),
WTF::Bind(&SyncManager::GetRegistrationsCallback,
WrapPersistent(resolver)));
return promise;
}
void SyncManager::RegisterCallback(
ScriptPromiseResolver* resolver,
mojom::blink::BackgroundSyncError error,
mojom::blink::SyncRegistrationOptionsPtr options) {
// TODO(iclelland): Determine the correct error message to return in each case
switch (error) {
case mojom::blink::BackgroundSyncError::NONE:
if (!options) {
resolver->Resolve(v8::Null(resolver->GetScriptState()->GetIsolate()));
return;
}
resolver->Resolve();
// Let the service know that the registration promise is resolved so that
// it can fire the event.
background_sync_service_->DidResolveRegistration(
mojom::blink::BackgroundSyncRegistrationInfo::New(
registration_->RegistrationId(), options->tag,
mojom::blink::BackgroundSyncType::ONE_SHOT));
break;
case mojom::blink::BackgroundSyncError::NOT_FOUND:
NOTREACHED();
break;
case mojom::blink::BackgroundSyncError::STORAGE:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kUnknownError, "Background Sync is disabled."));
break;
case mojom::blink::BackgroundSyncError::NOT_ALLOWED:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidAccessError,
"Attempted to register a sync event without a "
"window or registration tag too long."));
break;
case mojom::blink::BackgroundSyncError::PERMISSION_DENIED:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotAllowedError, "Permission denied."));
break;
case mojom::blink::BackgroundSyncError::NO_SERVICE_WORKER:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"Registration failed - no active Service Worker"));
break;
}
}
// static
void SyncManager::GetRegistrationsCallback(
ScriptPromiseResolver* resolver,
mojom::blink::BackgroundSyncError error,
WTF::Vector<mojom::blink::SyncRegistrationOptionsPtr> registrations) {
// TODO(iclelland): Determine the correct error message to return in each case
switch (error) {
case mojom::blink::BackgroundSyncError::NONE: {
Vector<String> tags;
for (const auto& r : registrations) {
tags.push_back(r->tag);
}
resolver->Resolve(tags);
break;
}
case mojom::blink::BackgroundSyncError::NOT_FOUND:
case mojom::blink::BackgroundSyncError::NOT_ALLOWED:
case mojom::blink::BackgroundSyncError::PERMISSION_DENIED:
// These errors should never be returned from
// BackgroundSyncManager::GetRegistrations
NOTREACHED();
break;
case mojom::blink::BackgroundSyncError::STORAGE:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kUnknownError, "Background Sync is disabled."));
break;
case mojom::blink::BackgroundSyncError::NO_SERVICE_WORKER:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kUnknownError, "No service worker is active."));
break;
}
}
void SyncManager::Trace(Visitor* visitor) const {
visitor->Trace(registration_);
visitor->Trace(background_sync_service_);
ScriptWrappable::Trace(visitor);
}
} // namespace blink
| 40.785714 | 90 | 0.72775 | [
"vector"
] |
9012251eb0d9ed0362662ac4a7732ce8dd0ff780 | 28,538 | cpp | C++ | ds/security/gina/snapins/fde/scope.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/gina/snapins/fde/scope.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/gina/snapins/fde/scope.cpp | 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, 1994 - 1998.
//
// File: scope.cpp
//
// Contents: implementation of the scope pane
//
// Classes: CScopePane
//
// History: 03-14-1998 stevebl Created
// 07-16-1998 rahulth Added calls to IGPEInformation::PolicyChanged
//
//---------------------------------------------------------------------------
#include "precomp.hxx"
#include <shlobj.h>
#include <winnetwk.h>
// Comment this line to stop trying to set the main snapin icon in the
// scope pane.
#define SET_SCOPE_ICONS 1
// Un-comment the next line to persist snap-in related data. (This really
// shouldn't be necessary since I get all my info from my parent anyway.)
// #define PERSIST_DATA 1
///////////////////////////////////////////////////////////////////////////////
// IComponentData implementation
DEBUG_DECLARE_INSTANCE_COUNTER(CScopePane);
CScopePane::CScopePane()
{
HKEY hKey;
DWORD dwDisp;
DEBUG_INCREMENT_INSTANCE_COUNTER(CScopePane);
m_bIsDirty = FALSE;
m_fRSOP = FALSE;
m_pScope = NULL;
m_pConsole = NULL;
m_pIPropertySheetProvider = NULL;
m_fLoaded = FALSE;
m_fExtension = FALSE;
m_pIGPEInformation = NULL;
m_pIRSOPInformation = NULL;
}
CScopePane::~CScopePane()
{
DEBUG_DECREMENT_INSTANCE_COUNTER(CScopePane);
ASSERT(m_pScope == NULL);
ASSERT(CResultPane::lDataObjectRefCount == 0);
}
#include <msi.h>
//+--------------------------------------------------------------------------
//
// Member: CScopePane::CreateNestedDirectory
//
// Synopsis: Ensures the existance of a path. If any directory along the
// path doesn't exist, this routine will create it.
//
// Arguments: [lpDirectory] - path to the leaf directory
// [lpSecurityAttributes] - security attributes
//
// Returns: 1 on success
// 0 on failure
//
// History: 3-17-1998 stevebl Copied from ADE
//
// Notes: Originally written by EricFlo
//
//---------------------------------------------------------------------------
UINT CScopePane::CreateNestedDirectory (LPTSTR lpDirectory, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
TCHAR szDirectory[MAX_PATH];
LPTSTR lpEnd;
//
// Check for NULL pointer
//
if (!lpDirectory || !(*lpDirectory)) {
SetLastError(ERROR_INVALID_DATA);
return 0;
}
//
// First, see if we can create the directory without having
// to build parent directories.
//
if (CreateDirectory (lpDirectory, lpSecurityAttributes)) {
return 1;
}
//
// If this directory exists already, this is OK too.
//
if (GetLastError() == ERROR_ALREADY_EXISTS) {
return ERROR_ALREADY_EXISTS;
}
//
// No luck, copy the string to a buffer we can munge
//
HRESULT hr;
hr = StringCchCopy(szDirectory, sizeof(szDirectory)/sizeof(szDirectory[0]), lpDirectory);
if (FAILED(hr))
{
SetLastError(HRESULT_CODE(hr));
return 0;
}
//
// Find the first subdirectory name
//
lpEnd = szDirectory;
if (szDirectory[1] == TEXT(':')) {
lpEnd += 3;
} else if (szDirectory[1] == TEXT('\\')) {
//
// Skip the first two slashes
//
lpEnd += 2;
//
// Find the slash between the server name and
// the share name.
//
while (*lpEnd && *lpEnd != TEXT('\\')) {
lpEnd++;
}
if (!(*lpEnd)) {
return 0;
}
//
// Skip the slash, and find the slash between
// the share name and the directory name.
//
lpEnd++;
while (*lpEnd && *lpEnd != TEXT('\\')) {
lpEnd++;
}
if (!(*lpEnd)) {
return 0;
}
//
// Leave pointer at the beginning of the directory.
//
lpEnd++;
} else if (szDirectory[0] == TEXT('\\')) {
lpEnd++;
}
while (*lpEnd) {
while (*lpEnd && *lpEnd != TEXT('\\')) {
lpEnd++;
}
if (*lpEnd == TEXT('\\')) {
*lpEnd = TEXT('\0');
if (!CreateDirectory (szDirectory, NULL)) {
if (GetLastError() != ERROR_ALREADY_EXISTS) {
return 0;
}
}
*lpEnd = TEXT('\\');
lpEnd++;
}
}
//
// Create the final directory
//
if (CreateDirectory (szDirectory, lpSecurityAttributes)) {
return 1;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
return ERROR_ALREADY_EXISTS;
}
//
// Failed
//
return 0;
}
STDMETHODIMP CScopePane::Initialize(LPUNKNOWN pUnknown)
{
ASSERT(pUnknown != NULL);
HRESULT hr;
AFX_MANAGE_STATE(AfxGetStaticModuleState());
// MMC should only call ::Initialize once!
ASSERT(m_pScope == NULL);
pUnknown->QueryInterface(IID_IConsoleNameSpace,
reinterpret_cast<void**>(&m_pScope));
ASSERT(hr == S_OK);
hr = pUnknown->QueryInterface(IID_IPropertySheetProvider,
(void **)&m_pIPropertySheetProvider);
hr = pUnknown->QueryInterface(IID_IConsole, reinterpret_cast<void**>(&m_pConsole));
ASSERT(hr == S_OK);
hr = m_pConsole->QueryInterface (IID_IDisplayHelp, reinterpret_cast<void**>(&m_pDisplayHelp));
ASSERT(hr == S_OK);
#ifdef SET_SCOPE_ICONS
LPIMAGELIST lpScopeImage;
hr = m_pConsole->QueryScopeImageList(&lpScopeImage);
ASSERT(hr == S_OK);
// Load the bitmaps from the dll
CBitmap bmp16x16;
CBitmap bmp32x32;
bmp16x16.LoadBitmap(IDB_16x16);
bmp32x32.LoadBitmap(IDB_32x32);
// Set the images
lpScopeImage->ImageListSetStrip(reinterpret_cast<LONG_PTR *>(static_cast<HBITMAP>(bmp16x16)),
reinterpret_cast<LONG_PTR *>(static_cast<HBITMAP>(bmp32x32)),
0, RGB(255,0,255));
lpScopeImage->Release();
#endif
return S_OK;
}
STDMETHODIMP CScopePane::CreateComponent(LPCOMPONENT* ppComponent)
{
ASSERT(ppComponent != NULL);
CComObject<CResultPane>* pObject;
HRESULT hr = CComObject<CResultPane>::CreateInstance(&pObject);
if ( FAILED(hr) )
{
return hr;
}
ASSERT(pObject != NULL);
m_pResultPane = pObject;
// Store IComponentData
pObject->SetIComponentData(this);
return pObject->QueryInterface(IID_IComponent,
reinterpret_cast<void**>(ppComponent));
}
STDMETHODIMP CScopePane::Notify(LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM param)
{
ASSERT(m_pScope != NULL);
HRESULT hr = S_OK;
UINT i;
// Since it's my folder it has an internal format.
// Design Note: for extension. I can use the fact, that the data object doesn't have
// my internal format and I should look at the node type and see how to extend it.
if (event == MMCN_PROPERTY_CHANGE)
{
// perform any action needed as a result of result property changes
hr = OnProperties(param);
}
else if ( event == MMCN_REMOVE_CHILDREN )
{
//
// In RSoP, we may get called to refresh the scope pane when the query
// is re-executed -- if this happens, current nodes will be removed and
// we must reset all of our cached information. We reset the relevant
// information below
//
if ( ((HSCOPEITEM)arg != NULL) && m_fRSOP && (m_pIRSOPInformation != NULL) )
{
m_pIRSOPInformation->Release();
m_pIRSOPInformation = NULL;
}
}
else
{
INTERNAL* pInternal = ExtractInternalFormat(lpDataObject);
MMC_COOKIE cookie = 0;
if (pInternal != NULL)
{
cookie = pInternal->m_cookie;
FREE_INTERNAL(pInternal);
}
else
{
// only way we could not be able to extract our own format is if we're operating as an extension
m_fExtension = TRUE;
}
if (m_fRSOP)
{
WCHAR szBuffer[MAX_DS_PATH];
if (m_pIRSOPInformation == NULL)
{
IRSOPInformation * pIRSOPInformation;
hr = lpDataObject->QueryInterface(IID_IRSOPInformation,
reinterpret_cast<void**>(&pIRSOPInformation));
if (SUCCEEDED(hr))
{
m_pIRSOPInformation = pIRSOPInformation;
m_pIRSOPInformation->AddRef();
/* extract the namespace here */
hr = m_pIRSOPInformation->GetNamespace(GPO_SECTION_USER, szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]));
if (SUCCEEDED(hr))
{
m_szRSOPNamespace = szBuffer;
}
pIRSOPInformation->Release();
}
}
}
else
{
if (m_pIGPEInformation == NULL)
{
IGPEInformation * pIGPEInformation;
hr = lpDataObject->QueryInterface(IID_IGPEInformation,
reinterpret_cast<void**>(&pIGPEInformation));
if (SUCCEEDED(hr))
{
GROUP_POLICY_OBJECT_TYPE gpoType;
hr = pIGPEInformation->GetType(&gpoType);
if (SUCCEEDED(hr))
{
if (gpoType == GPOTypeDS)
{
WCHAR szBuffer[MAX_PATH];
do
{
AFX_MANAGE_STATE (AfxGetStaticModuleState());
hr = pIGPEInformation->GetFileSysPath(GPO_SECTION_USER, szBuffer, MAX_PATH);
if (FAILED(hr))
break;
m_pIGPEInformation = pIGPEInformation;
m_pIGPEInformation->AddRef();
m_szFileRoot = szBuffer;
m_szFileRoot += L"\\Documents & Settings";
CreateNestedDirectory (((LPOLESTR)(LPCOLESTR)(m_szFileRoot)), NULL);
//initialize the folder data.
for (i = IDS_DIRS_START; i < IDS_DIRS_END; i++)
{
m_FolderData[GETINDEX(i)].Initialize (i,
(LPCTSTR) m_szFileRoot);
}
ConvertOldStyleSection (m_szFileRoot);
} while (0);
}
else
{
// force this to fail
hr = E_FAIL;
}
}
pIGPEInformation->Release();
}
}
}
if (SUCCEEDED(hr))
{
switch(event)
{
case MMCN_EXPAND:
{
hr = OnExpand(cookie, arg, param);
}
break;
case MMCN_SELECT:
hr = OnSelect(cookie, arg, param);
break;
case MMCN_CONTEXTMENU:
hr = OnContextMenu(cookie, arg, param);
break;
default:
//perform the default action
hr = S_FALSE;
break;
}
}
}
return hr;
}
STDMETHODIMP CScopePane::Destroy()
{
SAFE_RELEASE(m_pScope);
SAFE_RELEASE(m_pDisplayHelp);
SAFE_RELEASE(m_pConsole);
SAFE_RELEASE(m_pIPropertySheetProvider);
SAFE_RELEASE(m_pIGPEInformation);
SAFE_RELEASE(m_pIRSOPInformation);
return S_OK;
}
STDMETHODIMP CScopePane::QueryDataObject(MMC_COOKIE cookie, DATA_OBJECT_TYPES type, LPDATAOBJECT* ppDataObject)
{
ASSERT(ppDataObject != NULL);
CComObject<CDataObject>* pObject = NULL;
CComObject<CDataObject>::CreateInstance(&pObject);
ASSERT(pObject != NULL);
if (!pObject)
return E_UNEXPECTED;
// Save cookie and type for delayed rendering
pObject->SetID (m_FolderData[GETINDEX(cookie)].m_scopeID);
pObject->SetType(type);
pObject->SetCookie(cookie);
return pObject->QueryInterface(IID_IDataObject,
reinterpret_cast<void**>(ppDataObject));
}
///////////////////////////////////////////////////////////////////////////////
//// IPersistStreamInit interface members
STDMETHODIMP CScopePane::GetClassID(CLSID *pClassID)
{
ASSERT(pClassID != NULL);
// Copy the CLSID for this snapin
*pClassID = CLSID_Snapin;
return S_OK;
}
STDMETHODIMP CScopePane::IsDirty()
{
return ThisIsDirty() ? S_OK : S_FALSE;
}
STDMETHODIMP CScopePane::Load(IStream *pStm)
{
#ifdef PERSIST_DATA
ASSERT(pStm);
// UNDONE - Read data from the stream here.
return SUCCEEDED(hr) ? S_OK : E_FAIL;
#else
return S_OK;
#endif
}
STDMETHODIMP CScopePane::Save(IStream *pStm, BOOL fClearDirty)
{
#ifdef PERSIST_DATA
ASSERT(pStm);
// UNDONE - Write data to the stream here.
// on error, return STG_E_CANTSAVE;
#endif
if (fClearDirty)
ClearDirty();
return S_OK;
}
STDMETHODIMP CScopePane::GetSizeMax(ULARGE_INTEGER *pcbSize)
{
ASSERT(pcbSize);
// UNDONE - set the size of the string to be saved
ULONG cb = 0;
// Set the size of the string to be saved
ULISet32(*pcbSize, cb);
return S_OK;
}
STDMETHODIMP CScopePane::InitNew(void)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
//// Notify handlers for IComponentData
HRESULT CScopePane::OnAdd(MMC_COOKIE cookie, LPARAM arg, LPARAM param)
{
return E_UNEXPECTED;
}
HRESULT CScopePane::OnExpand(MMC_COOKIE cookie, LPARAM arg, LPARAM param)
{
if (arg == TRUE) //MMC never sends arg = FALSE (for collapse)
{
// Did Initialize get called?
ASSERT(m_pScope != NULL);
EnumerateScopePane(cookie,
param);
}
return S_OK;
}
HRESULT CScopePane::OnSelect(MMC_COOKIE cookie, LPARAM arg, LPARAM param)
{
return E_UNEXPECTED;
}
HRESULT CScopePane::OnContextMenu(MMC_COOKIE cookie, LPARAM arg, LPARAM param)
{
return S_OK;
}
HRESULT CScopePane::OnProperties(LPARAM param)
{
if (param == NULL)
{
return S_OK;
}
ASSERT(param != NULL);
return S_OK;
}
void CScopePane::EnumerateScopePane(MMC_COOKIE cookie, HSCOPEITEM pParent)
{
AFX_MANAGE_STATE (AfxGetStaticModuleState());
CString szFullPathname;
CString szParent;
SCOPEDATAITEM scopeItem;
FILETIME ftCurr;
LONG i;
int cChildren = 0;
DWORD myDocsFlags = REDIR_DONT_CARE;
DWORD myPicsFlags = REDIR_DONT_CARE;
memset(&scopeItem, 0, sizeof(SCOPEDATAITEM));
CHourglass hourglass; //this may take some time, so put up an hourglass
GetSystemTimeAsFileTime (&ftCurr);
//set the common members for the scope pane items
scopeItem.mask = SDI_STR | SDI_PARAM | SDI_CHILDREN;
#ifdef SET_SCOPE_ICONS
scopeItem.mask |= SDI_IMAGE | SDI_OPENIMAGE;
scopeItem.nImage = IMG_CLOSEDBOX;
scopeItem.nOpenImage = IMG_OPENBOX;
#endif
scopeItem.relativeID = pParent;
scopeItem.displayname = MMC_CALLBACK;
if (m_fExtension)
{
switch(cookie)
{
case NULL: //getting the folder
// if we're an extension then add a root folder to hang everything off of
if (m_fRSOP)
{
// make sure that nodes don't get enumerated if they contain no data
if (FAILED(m_pResultPane->TestForRSOPData(cookie)))
{
if (m_pIRSOPInformation)
{
m_pIRSOPInformation->Release();
m_pIRSOPInformation = NULL;
}
return;
}
}
scopeItem.lParam = IDS_FOLDER_TITLE; //use resource id's as cookies
scopeItem.cChildren = 1;
m_pScope->InsertItem(&scopeItem);
break;
case IDS_FOLDER_TITLE:
for (i = IDS_LEVEL1_DIRS_START; i < IDS_LEVEL1_DIRS_END; i++)
{
BOOL fInsert = TRUE;
if (m_fRSOP)
{
if (FAILED(m_pResultPane->TestForRSOPData(i)))
{
fInsert = FALSE;
}
}
if (fInsert)
{
scopeItem.lParam = i;
m_FolderData[GETINDEX(i)].Initialize(i,
(LPCTSTR) m_szFileRoot
);
if (i == IDS_MYDOCS && !m_fRSOP)
{
//
// Show the My Pictures folder only if it does not follow MyDocs.
// and only if there is no registry setting overriding the hiding behavior
// for My Pics
//
if (AlwaysShowMyPicsNode())
{
cChildren = 1;
m_FolderData[GETINDEX(i)].m_bHideChildren = FALSE;
}
else
{
m_FolderData[GETINDEX(IDS_MYPICS)].Initialize(IDS_MYPICS,
(LPCTSTR) m_szFileRoot
);
m_FolderData[GETINDEX(i)].LoadSection();
m_FolderData[GETINDEX(IDS_MYPICS)].LoadSection();
myDocsFlags = m_FolderData[GETINDEX(i)].m_dwFlags;
myPicsFlags = m_FolderData[GETINDEX(IDS_MYPICS)].m_dwFlags;
if (((REDIR_DONT_CARE & myDocsFlags) && (REDIR_DONT_CARE & myPicsFlags)) ||
((REDIR_FOLLOW_PARENT & myPicsFlags) && (!(REDIR_DONT_CARE & myDocsFlags)))
)
{
cChildren = 0;
m_FolderData[GETINDEX(i)].m_bHideChildren = TRUE;
}
else
{
cChildren = 1;
m_FolderData[GETINDEX(i)].m_bHideChildren = FALSE;
}
}
}
scopeItem.cChildren = cChildren; //only My Docs will possibly have children
m_pScope->InsertItem(&scopeItem);
m_FolderData[GETINDEX(i)].SetScopeItemID(scopeItem.ID);
}
if (IDS_MYDOCS == i && m_fRSOP && SUCCEEDED(m_pResultPane->TestForRSOPData(IDS_MYPICS)))
{
// In RSOP mode we put My Pictures after My Documents
// instead of under it. Otherwise the results pane
// for My Documents would contain a folder along with
// the data and it would look very odd.
scopeItem.lParam = IDS_MYPICS;
scopeItem.cChildren = 0;
m_pScope->InsertItem(&scopeItem);
m_FolderData[GETINDEX(IDS_MYPICS)].Initialize (IDS_MYPICS,
(LPCTSTR) m_szFileRoot
);
m_FolderData[GETINDEX(IDS_MYPICS)].SetScopeItemID(scopeItem.ID);
}
}
break;
case IDS_MYDOCS: //of all levels 1 folder, only MyDocs has children
if (!m_fRSOP && !(m_FolderData[GETINDEX(IDS_MYDOCS)].m_bHideChildren))
{
scopeItem.lParam = IDS_MYPICS;
scopeItem.cChildren = 0;
m_pScope->InsertItem(&scopeItem);
m_FolderData[GETINDEX(IDS_MYPICS)].Initialize (IDS_MYPICS,
(LPCTSTR) m_szFileRoot
);
m_FolderData[GETINDEX(IDS_MYPICS)].SetScopeItemID(scopeItem.ID);
}
break;
}
}
}
STDMETHODIMP CScopePane::GetSnapinDescription(LPOLESTR * lpDescription)
{
// UNDONE
OLESAFE_COPYSTRING(*lpDescription, L"description");
return S_OK;
}
STDMETHODIMP CScopePane::GetProvider(LPOLESTR * lpName)
{
// UNDONE
OLESAFE_COPYSTRING(*lpName, L"provider");
return S_OK;
}
STDMETHODIMP CScopePane::GetSnapinVersion(LPOLESTR * lpVersion)
{
// UNDONE
OLESAFE_COPYSTRING(*lpVersion, L"version");
return S_OK;
}
STDMETHODIMP CScopePane::GetSnapinImage(HICON * hAppIcon)
{
// UNDONE
return E_NOTIMPL;
}
STDMETHODIMP CScopePane::GetStaticFolderImage(HBITMAP * hSmallImage,
HBITMAP * hSmallImageOpen,
HBITMAP * hLargeImage,
COLORREF * cMask)
{
// UNDONE
return E_NOTIMPL;
}
STDMETHODIMP CScopePane::GetHelpTopic(LPOLESTR *lpCompiledHelpFile)
{
LPOLESTR lpHelpFile;
lpHelpFile = (LPOLESTR) CoTaskMemAlloc (MAX_PATH * sizeof(WCHAR));
if (!lpHelpFile)
{
DbgMsg((TEXT("CScopePane::GetHelpTopic: Failed to allocate memory.")));
return E_OUTOFMEMORY;
}
ExpandEnvironmentStringsW (L"%SystemRoot%\\Help\\gpedit.chm",
lpHelpFile, MAX_PATH);
*lpCompiledHelpFile = lpHelpFile;
return S_OK;
}
STDMETHODIMP CScopePane::GetDisplayInfo(SCOPEDATAITEM* pScopeDataItem)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
LONG i;
ASSERT(pScopeDataItem != NULL);
if (pScopeDataItem == NULL)
return E_POINTER;
if (IDS_FOLDER_TITLE == pScopeDataItem->lParam)
{
m_szFolderTitle.LoadString(IDS_FOLDER_TITLE);
pScopeDataItem->displayname = (unsigned short *)((LPCOLESTR)m_szFolderTitle);
}
else
{
pScopeDataItem->displayname = L"???";
if (-1 != (i = GETINDEX(pScopeDataItem->lParam)))
pScopeDataItem->displayname = (unsigned short*)((LPCOLESTR)(m_FolderData[i].m_szDisplayname));
}
ASSERT(pScopeDataItem->displayname != NULL);
return S_OK;
}
STDMETHODIMP CScopePane::CompareObjects(LPDATAOBJECT lpDataObjectA, LPDATAOBJECT lpDataObjectB)
{
if (lpDataObjectA == NULL || lpDataObjectB == NULL)
return E_POINTER;
// Make sure both data object are mine
INTERNAL* pA;
INTERNAL* pB;
HRESULT hr = S_FALSE;
pA = ExtractInternalFormat(lpDataObjectA);
pB = ExtractInternalFormat(lpDataObjectB);
if (pA != NULL && pB != NULL)
hr = ((pA->m_type == pB->m_type) && (pA->m_cookie == pB->m_cookie)) ? S_OK : S_FALSE;
FREE_INTERNAL(pA);
FREE_INTERNAL(pB);
return hr;
}
// Scope item property pages:
STDMETHODIMP CScopePane::CreatePropertyPages(LPPROPERTYSHEETCALLBACK lpProvider,
LONG_PTR handle,
LPDATAOBJECT lpIDataObject)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
HRESULT hr = S_FALSE;
INTERNAL* pInternal = ExtractInternalFormat(lpIDataObject);
if (! pInternal)
return S_FALSE;
DWORD cookie = pInternal->m_cookie;
LONG i;
BOOL fShowPage = FALSE;
AFX_OLDPROPSHEETPAGE * pPsp;
AFX_OLDPROPSHEETPAGE * pPspSettings;
CFileInfo* pFileInfo;
//it is one of the folders
i = GETINDEX (cookie);
pFileInfo = &(m_FolderData[i]);
if (!pFileInfo->m_pRedirPage) //make sure that the property page is not already up.
{
pFileInfo->m_pRedirPage = new CRedirect(cookie);
pFileInfo->m_pRedirPage->m_ppThis = &(pFileInfo->m_pRedirPage);
pFileInfo->m_pRedirPage->m_pScope = this;
pFileInfo->m_pRedirPage->m_pFileInfo = pFileInfo;
fShowPage = TRUE;
pPsp = (AFX_OLDPROPSHEETPAGE *)&(pFileInfo->m_pRedirPage->m_psp);
//create the settings page;
pFileInfo->m_pSettingsPage = new CRedirPref();
pFileInfo->m_pSettingsPage->m_ppThis = &(pFileInfo->m_pSettingsPage);
pFileInfo->m_pSettingsPage->m_pFileInfo = pFileInfo;
pPspSettings = (AFX_OLDPROPSHEETPAGE *)&(pFileInfo->m_pSettingsPage->m_psp);
}
if (fShowPage) //show page if it is not already up.
{
hr = SetPropPageToDeleteOnClose (pPsp);
if (SUCCEEDED (hr))
hr = SetPropPageToDeleteOnClose (pPspSettings);
if (SUCCEEDED(hr))
{
HPROPSHEETPAGE hProp = CreateThemedPropertySheetPage(pPsp);
HPROPSHEETPAGE hPropSettings = CreateThemedPropertySheetPage(pPspSettings);
if (NULL == hProp || NULL == hPropSettings )
hr = E_UNEXPECTED;
else
{
lpProvider->AddPage(hProp);
lpProvider->AddPage (hPropSettings);
hr = S_OK;
}
}
}
FREE_INTERNAL(pInternal);
return hr;
}
// Scope item property pages:
STDMETHODIMP CScopePane::QueryPagesFor(LPDATAOBJECT lpDataObject)
{
// scope panes don't have property pages in RSOP mode
if (m_fRSOP)
{
return S_FALSE;
}
//the only property sheets we are presenting right now are those
//for built-in folder redirection
INTERNAL* pInternal = ExtractInternalFormat(lpDataObject);
if (! pInternal)
return S_FALSE;
MMC_COOKIE cookie = pInternal->m_cookie;
HRESULT hr = S_FALSE;
CError error;
if (CCT_SCOPE == pInternal->m_type)
{
if (SUCCEEDED(m_FolderData[GETINDEX(cookie)].LoadSection()))
hr = S_OK;
else
{
error.ShowConsoleMessage (m_pConsole, IDS_SECTIONLOAD_ERROR,
m_FolderData[GETINDEX(cookie)].m_szDisplayname);
hr = S_FALSE;
}
}
FREE_INTERNAL(pInternal);
return hr;
}
BOOL CScopePane::IsScopePaneNode(LPDATAOBJECT lpDataObject)
{
BOOL bResult = FALSE;
INTERNAL* pInternal = ExtractInternalFormat(lpDataObject);
if (! pInternal)
return bResult;
if (pInternal->m_type == CCT_SCOPE)
bResult = TRUE;
FREE_INTERNAL(pInternal);
return bResult;
}
///////////////////////////////////////////////////////////////////////////////
// IExtendContextMenu implementation
//
STDMETHODIMP CScopePane::AddMenuItems(LPDATAOBJECT pDataObject,
LPCONTEXTMENUCALLBACK pContextMenuCallback,
LONG * pInsertionAllowed)
{
//we do not have any commands on the menu.
return S_OK;
}
STDMETHODIMP CScopePane::Command(long nCommandID, LPDATAOBJECT pDataObject)
{
//we do not have any commands on the menu
return S_OK;
}
| 29.882723 | 128 | 0.518747 | [
"object"
] |
901611ee1df576cfd2c11590c0639564d2f3c146 | 931 | cpp | C++ | contest/1397/c/c.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | contest/1397/c/c.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | contest/1397/c/c.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define watch(x) std::cout << (#x) << " is " << (x) << std::endl
#define print(x) std::cout << (x) << std::endl
using LL = long long;
int main() {
//freopen("in", "r", stdin);
std::cin.tie(nullptr)->sync_with_stdio(false);
int n;
std::cin >> n;
std::vector<LL> a(n);
for (auto &x : a) std::cin >> x;
if (n == 1) {
std::cout << "1 1" << std::endl;
std::cout << -a[0] << std::endl;
std::cout << "1 1" << std::endl;
std::cout << 0 << std::endl;
std::cout << "1 1" << std::endl;
std::cout << 0 << std::endl;
return 0;
}
std::cout << "1 " << n << std::endl;
std::cout << "0 ";
for (int i = 1; i < n; ++i) {
LL tmp = -a[i] * n % (n - 1) * n;
std::cout << tmp << " \n"[i == n - 1];
a[i] += tmp;
}
std::cout << "1 1\n";
std::cout << -a[0] << std::endl;
std::cout << "2 " << n << std::endl;
for (int i = 1; i < n; ++i) {
std::cout << -a[i] << " \n"[i == n - 1];
}
return 0;
} | 26.6 | 64 | 0.460795 | [
"vector"
] |
902186c89ca8c391b68ee799615d9e4f6f9708a4 | 584 | cpp | C++ | cpp/group_anagrams.cpp | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | 1 | 2020-10-06T01:20:07.000Z | 2020-10-06T01:20:07.000Z | cpp/group_anagrams.cpp | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | null | null | null | cpp/group_anagrams.cpp | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | null | null | null | /*
Input:
2
5
act cat tac god dog
3
act cat tac
Output:
2 3
3
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
map<string,int> m;
vector<int> v;
cin>>n;
string s[n];
for(int i=0;i<n;i++){
cin>>s[i];
// cin.ignore();
sort(s[i].begin(),s[i].end());
m[s[i]]++;
}
map<string,int>::iterator it;
for(it=m.begin();it!=m.end();it++){
v.push_back(it->second);
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
cout<<endl;
}
}
| 13.581395 | 38 | 0.479452 | [
"vector"
] |
9026be14155fa1f437902c7ac9b47743aa150951 | 6,939 | cpp | C++ | source/Server/tlc-server/socket/ltfsTask.cpp | BDT-GER/SWIFT-TLC | 1474a36c67b03797b37ff40ea2df78a582c8147b | [
"Apache-2.0"
] | 22 | 2015-04-23T20:02:18.000Z | 2018-06-02T03:30:39.000Z | source/Server/tlc-server/socket/ltfsTask.cpp | BDT-GER/SWIFT-TLC | 1474a36c67b03797b37ff40ea2df78a582c8147b | [
"Apache-2.0"
] | null | null | null | source/Server/tlc-server/socket/ltfsTask.cpp | BDT-GER/SWIFT-TLC | 1474a36c67b03797b37ff40ea2df78a582c8147b | [
"Apache-2.0"
] | 8 | 2015-05-24T18:13:48.000Z | 2022-03-26T16:36:58.000Z | /*
* ltfsTask.cpp
*
* Created on: 2012-8-22
* Author: chento
*/
#include "ltfsTaskManagement.h"
#include "ltfsTask.h"
namespace ltfs_soapserver
{
string
Task::Status2String(StatusForTask status)
{
switch(status)
{
case Status_Loading:
return "loading";
case Status_Formatting:
return "formatting";
case Status_Creating:
return "creating";
case status_Deleting:
return "deleting";
case Status_Waiting:
return "waiting";
case Status_Running:
return "running";
case Status_Failed:
return "failed";
case Status_Finish:
return "finish";
case Status_Canceled:
return "cancel";
case Status_Ready:
return "ready";
default:
return "";
}
}
int
Task::String2Status(string& status)
{
if(status == "loading")
return Status_Loading;
if(status == "formatting")
return Status_Formatting;
if(status == "creating")
return Status_Creating;
if(status == "deleting")
return status_Deleting;
if(status == "waiting")
return Status_Waiting;
if(status == "running")
return Status_Running;
if(status == "failed")
return Status_Failed;
if(status == "finish")
return Status_Finish;
if(status == "cancel")
return Status_Canceled;
if(status == "ready")
return Status_Ready;
return -1;
}
int
Task::String2Type(string& type)
{
if(type == "Inventory")
return Type_LoadTape;
if(type == "DeleteShare")
return Type_DelShare;
if(type == "Revoke")
return Type_Revoke;
if(type == "Recycle")
return Type_Recycle;
if(type == "Import")
return Type_Import;
if(type == "Export")
return Type_Export;
if(type == "CleanDrive")
return Type_CleanDrive;
if(type == "DiagnoseTape")
return Type_CheckTape;
if(type == "Eject")
return Type_Eject;
if(type == "DirectAccess")
return Type_DirectAccess;
if(type == "MannulFormat")
return Type_MannulFormat;
if(type == "DeleteTape")
return Type_DeleteTape;
if(type == "AuditTape")
return Type_AuditTape;
if(type == "DeleteTapeFile")
return Type_DeleteTapeFile;
return -1;
}
Task::Task(TaskType type):
type_(type)
{
statusForQueue_ = Status_New;
timeStart_ = boost::posix_time::second_clock::local_time();
timeEnd_ = timeStart_;
cancel_ = false;
status_ = Status_Waiting;
excludeByQuery_ = false;
manager_ = NULL;
taskProgress_ = "";
}
Task::Task(TaskType type, const string& groupID, const vector<string> &barcodes):
type_(type), groupID_(groupID)
{
statusForQueue_ = Status_New;
timeStart_ = boost::posix_time::second_clock::local_time();
timeEnd_ = timeStart_;
cancel_ = false;
status_ = Status_Waiting;
excludeByQuery_ = false;
manager_ = NULL;
taskProgress_ = "";
InitStatus(barcodes);
}
Task::~Task()
{
}
void
Task::InitStatus(const vector<std::string> &barcodes)
{
for(vector<std::string>::const_iterator iter = barcodes.begin();
iter!=barcodes.end(); ++iter)
{
TapeStatusPair pair;
pair.mBarcode = *iter;
pair.mStatus = Status_Waiting;
barcodeList_.insert(barcodeList_.end(), pair);
}
}
bool
Task::Start(void* manager)
{
threadPtr_.reset(new boost::thread(boost::bind(&Task::Execute, this)));
if(manager != NULL){
manager_ = manager;
}
return true;
}
bool
Task::Cancel()
{
cancel_ = true;
return true;
}
void
Task::MarkEnd()
{
statusForQueue_ = Status_Finished;
timeEnd_ = boost::posix_time::second_clock::local_time();
}
bool Task::GetExcludeByQueryFlag() const
{
return excludeByQuery_;
}
string
Task::GetTypeStr() const
{
switch(type_)
{
case Type_LoadTape:
return "Inventory";
case Type_DelShare:
return "DeleteShare";
case Type_Revoke:
return "Revoke";
case Type_Recycle:
return "Recycle";
case Type_Import:
return "Import";
case Type_Export:
return "Export";
case Type_CleanDrive:
return "CleanDrive";
case Type_CheckTape:
return "DiagnoseTape";
case Type_Eject:
return "Eject";
case Type_DirectAccess:
return "DirectAccess";
case Type_MannulFormat:
return "MannulFormat";
case Type_DeleteTape:
return "DeleteTape";
case Type_AuditTape:
return "AuditTape";
case Type_DeleteTapeFile:
return "DeleteTapeFile";
}
return "";
}
string
Task::GetStatusStr() const
{
return Status2String(status_);
}
string
Task::GetStartTimeStr() const
{
string strTime = boost::posix_time::to_iso_string(timeStart_);
int pos = strTime.find('T');
strTime.replace(pos,1,std::string(" "));
strTime.replace(pos + 3,0,std::string(":"));
strTime.replace(pos + 6,0,std::string(":"));
strTime.replace(4,0,std::string("-"));
strTime.replace(7,0,std::string("-"));
return strTime;
}
string
Task::GetEndTimeStr() const
{
string strTime = boost::posix_time::to_iso_string(timeEnd_);
int pos = strTime.find('T');
strTime.replace(pos,1,std::string(" "));
strTime.replace(pos + 3,0,std::string(":"));
strTime.replace(pos + 6,0,std::string(":"));
strTime.replace(4,0,std::string("-"));
strTime.replace(7,0,std::string("-"));
return strTime;
}
string
Task::GetGroupID() const
{
return groupID_;
}
TaskType
Task::GetType() const
{
return type_;
}
StatusForTask
Task::GetStatus() const
{
return status_;
}
boost::posix_time::ptime
Task::GetStartTime() const
{
return timeStart_;
}
boost::posix_time::ptime
Task::GetEndTime() const
{
return timeEnd_;
}
void
Task::GetTapeList(vector<TapeStatusPair>& tapeList)
{
tapeList = barcodeList_;
}
StatusForQueue
Task::GetStatusForQueue() const
{
return statusForQueue_;
}
void
Task::SaveStateToFile()
{
if(NULL != manager_)
{
((TaskManagement*)manager_)->SaveTaskQueue();
}
}
string Task::GetTaskProgressStr()
{
return taskProgress_;
}
bool
Task::RequestResource(string& barcode, int priority,bool mount)
{
SocketDebug("RequestResource, barcode :" << barcode << " type:"<< GetTypeStr())
while(!ltfs_management::TapeLibraryMgr::Instance()->RequestTape(barcode,mount,priority,1))
{
if(cancel_)
{
SocketDebug("RequestResource, barcode :" << barcode << " type:"<< GetTypeStr() << " return false")
return false;
}
}
SocketDebug("RequestResource, barcode :" << barcode << " type:"<< GetTypeStr() << " return true")
return true;
}
bool
Task::FreeResource(string& barcode)
{
ltfs_management::TapeLibraryMgr::Instance()->ReleaseTape(barcode);
SocketDebug("FreeResource, barcode :" << barcode);
return true;
}
void
Task::ForceDetachTask()
{
//threadPtr_->interrupt();
}
}
| 19.939655 | 109 | 0.636835 | [
"vector"
] |
9028e7fa578599221f8f3c70ff3a762704caa0c7 | 6,972 | cpp | C++ | Systems/Physics/CoreActions.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | Systems/Physics/CoreActions.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | Systems/Physics/CoreActions.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Davis
/// Copyright 2011-2017, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
namespace Physics
{
TransformAction::TransformAction()
{
EmptyState();
}
void TransformAction::QueueState(byte state)
{
mState |= state;
}
void TransformAction::CommitState(PhysicsNode* node)
{
Collider* collider = node->mCollider;
RigidBody* body = node->mBody;
if(collider == nullptr && body == nullptr)
return;
WorldTransformation* transform = node->GetTransform();
Vec3 oldTranslation = transform->GetOldTranslation();
Mat3 oldRotation = transform->GetOldRotation();
if(mState & ReadTransform)
node->ReadTransform();
if(mState & WorldTransform)
node->RecomputeWorldTransform();
//this happens when a collider is first made, we need to update the old
//values to be where it currently is so that the kinematic velocity
//calculation for the first frame will be correct
if(mState & OverrideOldTransform)
{
oldTranslation = transform->GetWorldTranslation();
oldRotation = transform->GetWorldRotation();
transform->mOldTranslation = oldTranslation;
transform->mOldRotation = oldRotation;
}
//Update the kinematic velocity if requested. The partial velocity still needs to be
//updated here even though it's updated in UpdateKinematicVelocities so that the user
//can update positions mid-frame and get a new velocity on their kinematic objects.
//However, don't update the old position and rotation as that should only be updated
//once per frame. If the old position is updated multiple times then velocity calculation
//will get partial values. To avoid that the positions are only updated once a
//frame (see UpdateKinematicVelocities).
if(body != nullptr && mState & KinematicVelocity)
body->ComputeVelocities(oldTranslation, oldRotation, body->mSpace->mIterationDt);
}
void TransformAction::EmptyState()
{
mState = Empty;
}
void TransformAction::Validate()
{
}
MassAction::MassAction()
{
EmptyState();
}
void MassAction::QueueState(byte state)
{
mState |= state;
}
void MassAction::CommitState(RigidBody* owner)
{
if(mState & RecomputeCenterMass)
owner->RecomputeCenterMass();
if(mState & CenterMassUpdate)
owner->UpdateCenterMassFromWorldPosition();
if(mState & RecomputeInertiaTensor)
owner->RecomputeInertiaTensor();
if(mState & WorldInertiaTensor)
owner->UpdateWorldInertiaTensor();
//we've now committed all state, mark ourself as empty now
EmptyState();
}
void MassAction::EmptyState()
{
mState = Empty;
}
void MassAction::Validate()
{
}
BroadPhaseAction::BroadPhaseAction()
{
mState = Empty;
}
void BroadPhaseAction::PushAction(byte state)
{
QueueState(state);
}
void BroadPhaseAction::InsertAction(Collider* collider)
{
if(collider->InDynamicBroadPhase())
PushAction(DynamicInsert);
else
PushAction(StaticInsert);
}
void BroadPhaseAction::RemoveAction(Collider* collider)
{
if(collider->InDynamicBroadPhase())
PushAction(DynamicRemoval);
else
PushAction(StaticRemoval);
}
void BroadPhaseAction::UpdateAction(Collider* collider)
{
PushAction(Update);
}
void BroadPhaseAction::QueueState(byte state)
{
//deal with dynamic states
if(state & DynamicInsert)
{
if(IsSet(DynamicRemoval))
ClearState(Dynamic);
else
{
ClearState(Dynamic);
SetState(state & Dynamic);
}
}
else if(state & DynamicRemoval)
{
if(IsSet(DynamicInsert))
ClearState(Dynamic);
else
{
ClearState(Dynamic);
SetState(state & Dynamic);
}
}
//deal with static states
if(state & StaticInsert)
{
if(IsSet(StaticRemoval))
ClearState(Static);
else
{
ClearState(Static);
SetState(state & Static);
}
}
else if(state & StaticRemoval)
{
if(IsSet(StaticInsert))
ClearState(Static);
else
{
ClearState(Static);
SetState(state & Static);
}
}
//combine the old state (with update stripped out) with the new update state.
mState = (mState & ~Update) | (state & Update);
}
void BroadPhaseAction::EmptyState()
{
//determine if we are in a static or dynamic state
if(mState & DynamicInsert)
mState = CurrStateDynamic;
else if(mState & StaticInsert)
mState = CurrStateStatic;
else if(mState & (DynamicRemoval | StaticRemoval))
mState = mState & ~(CurrStateDynamic | CurrStateStatic);
ClearState(CurrStateQueued | Update | Static | Dynamic);
Validate();
}
void BroadPhaseAction::ClearAction()
{
mState = Empty;
}
bool BroadPhaseAction::IsSet(byte state) const
{
return (mState & state) != 0;
}
void BroadPhaseAction::SetState(byte state)
{
mState |= state;
}
void BroadPhaseAction::ClearState(byte state)
{
mState = mState & ~state;
}
bool BroadPhaseAction::IsActionQueued() const
{
return (mState & (Update | Dynamic | Static)) != 0;
}
bool BroadPhaseAction::IsInBroadPhase() const
{
return (mState & (CurrStateStatic | CurrStateDynamic)) != 0;
}
bool BroadPhaseAction::IsInDynamicBroadPhase() const
{
return (mState & CurrStateDynamic) != 0;
}
uint BroadPhaseAction::BroadPhaseToRemoveFrom() const
{
//we cannot just check the current broadphase state. We may be currently in static,
//but with a static remove and a dynamic Insert queued. That would mean we'd
//want to queue a dynamic remove. Therefore, if we have an Insert queued, queue
//the corresponding remove. If we don't have an Insert, just use the current state.
if(mState & StaticInsert)
return StaticRemoval;
if(mState & DynamicInsert)
return DynamicRemoval;
if(mState & CurrStateStatic)
return StaticRemoval;
if(mState & CurrStateDynamic)
return DynamicRemoval;
return 0;
}
void BroadPhaseAction::Validate()
{
ErrorIf(IsSet(DynamicRemoval) && !IsSet(CurrStateDynamic),
"Removing Dynamic when this object was never dynamic.");
ErrorIf(IsSet(StaticRemoval) && !IsSet(CurrStateStatic),
"Removing Static when this object was never static.");
ErrorIf(IsSet(DynamicRemoval) && IsSet(StaticRemoval),
"Removing from static and dynamic in same action.");
ErrorIf(IsSet(DynamicInsert) && IsSet(StaticInsert),
"Inserting to static and dynamic in same action.");
ErrorIf(IsSet(DynamicRemoval) && IsSet(DynamicInsert),
"Cannot remove and Insert an object simultaneously.");
ErrorIf(IsSet(StaticRemoval) && IsSet(StaticInsert),
"Cannot remove and Insert an object simultaneously.");
}
}//namespace Physics
}//namespace Zero
| 24.9 | 92 | 0.670683 | [
"object",
"transform"
] |
902c04c0dda80b51c8262b6057fe62d73969fa2a | 1,756 | hpp | C++ | tests/libs/fakeParticle/api/fakeParticleDevice.hpp | charleskorn/weather-thingy-particle | 0f64d4bcd8145899cac73e4b678202552702aa82 | [
"MIT"
] | null | null | null | tests/libs/fakeParticle/api/fakeParticleDevice.hpp | charleskorn/weather-thingy-particle | 0f64d4bcd8145899cac73e4b678202552702aa82 | [
"MIT"
] | null | null | null | tests/libs/fakeParticle/api/fakeParticleDevice.hpp | charleskorn/weather-thingy-particle | 0f64d4bcd8145899cac73e4b678202552702aa82 | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <vector>
#include <unordered_map>
#include <memory>
#include "pinmap_hal.h"
#include "spark_wiring_constants.h"
#include "eventChain.hpp"
#include "timeUnit.hpp"
#include "expectations/expectations.hpp"
#include "particleEvent.hpp"
namespace FakeParticle {
class FakeParticleDevice {
public:
FakeParticleDevice();
void reset();
void assertFinished();
void setPinMode(uint16_t pin, PinMode mode);
PinMode getPinMode(uint16_t pin);
void setPinDigitalState(uint16_t pin, PinState state);
PinState getPinDigitalState(uint16_t pin);
void setPinAnalogValue(uint16_t pin, int32_t value);
int32_t getPinAnalogValue(uint16_t pin);
void setEEPROMValue(int slot, uint8_t value);
uint8_t getEEPROMValue(int slot);
void advanceClock(uint32_t microseconds);
uint32_t getCurrentTimeInMicroseconds();
EventChain& after(uint32_t time, TimeUnit timeUnit, Action action);
EventChain& when(Condition* const condition, Action action);
EventChain& expect(Expectation* const expectation);
EventChain& immediately(Action action);
void publishEvent(const ParticleEvent event);
std::vector<ParticleEvent>& getPublishedEvents();
private:
std::vector<std::unique_ptr<EventChain>> eventChains;
uint32_t currentTime;
std::unordered_map<uint16_t, PinMode> pinModes;
std::unordered_map<uint16_t, PinState> pinDigitalStates;
std::unordered_map<uint16_t, int32_t> pinAnalogValues;
std::unordered_map<int, uint8_t> eepromValues;
std::vector<ParticleEvent> publishedEvents;
bool alreadyProcessingStateChange;
bool needToReprocessStateChange;
void onStateChange();
};
extern FakeParticleDevice fakeParticle;
}
| 27.873016 | 71 | 0.752847 | [
"vector"
] |
902ff302fe66f83b98482cb721a764229f8eff4c | 45,532 | cpp | C++ | dpcpp/cfd/euler3d_double.dp.cpp | CR-G/rodinia-dpct-dpcpp | a0e80bd715c3cc7c3356e1e00245b91e15927d2c | [
"MIT"
] | 1 | 2022-03-28T18:13:13.000Z | 2022-03-28T18:13:13.000Z | dpcpp/cfd/euler3d_double.dp.cpp | artecs-group/rodinia-dpct-dpcpp | a0e80bd715c3cc7c3356e1e00245b91e15927d2c | [
"MIT"
] | 7 | 2021-04-15T11:53:20.000Z | 2021-05-15T08:58:30.000Z | dpcpp/cfd/euler3d_double.dp.cpp | artecs-group/rodinia-dpct-dpcpp | a0e80bd715c3cc7c3356e1e00245b91e15927d2c | [
"MIT"
] | null | null | null | // Copyright 2009, Andrew Corrigan, acorriga@gmu.edu
// This code is from the AIAA-2009-4001 paper
// #include <cutil.h>
#include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include "helper_cuda.h"
#include "helper_timer.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include "../common.hpp"
#if CUDART_VERSION < 3000
struct double3
{
double x, y, z;
};
#endif
/*
* Options
*
*/
#define GAMMA 1.4
#define iterations 2000
#ifndef block_length
#define block_length 128
#endif
#define NDIM 3
#define NNB 4
#define RK 3 // 3rd order RK
#define ff_mach 1.2
#define deg_angle_of_attack 0.0
/*
* not options
*/
#if block_length > 128
#warning "the kernels may fail too launch on some systems if the block length is too large"
#endif
#define VAR_DENSITY 0
#define VAR_MOMENTUM 1
#define VAR_DENSITY_ENERGY (VAR_MOMENTUM+NDIM)
#define NVAR (VAR_DENSITY_ENERGY+1)
/*
* Generic functions
*/
#ifdef TIME_IT
long long get_time() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000000) + tv.tv_usec;
}
#endif
template <typename T>
#ifdef TIME_IT
T* alloc(int N, long long &time)
#else
T* alloc(int N)
#endif
{
T* t;
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1003:17: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors((t = (T *)sycl::malloc_device(
sizeof(T) * N, dpct::get_default_queue()),
0));
#ifdef TIME_IT
dpct::get_current_device().queues_wait_and_throw();
time1 = get_time();
time = time1-time0;
#endif
return t;
}
template <typename T>
#ifdef TIME_IT
long long dealloc(T* array)
#else
void dealloc(T* array)
#endif
{
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1003:18: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors((sycl::free((void *)array, dpct::get_default_queue()), 0));
#ifdef TIME_IT
dpct::get_current_device().queues_wait_and_throw();
time1 = get_time();
return time1-time0;
#endif
}
template <typename T>
#ifdef TIME_IT
long long copy(T* dst, T* src, int N)
#else
void copy(T* dst, T* src, int N)
#endif
{
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1003:19: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors((dpct::get_default_queue()
.memcpy((void *)dst, (void *)src, N * sizeof(T))
.wait(),
0));
#ifdef TIME_IT
time1 = get_time();
return time1-time0;
#endif
}
template <typename T>
#ifdef TIME_IT
long long upload(T* dst, T* src, int N)
#else
void upload(T* dst, T* src, int N)
#endif
{
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1003:20: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors((dpct::get_default_queue()
.memcpy((void *)dst, (void *)src, N * sizeof(T))
.wait(),
0));
#ifdef TIME_IT
time1 = get_time();
return time1-time0;
#endif
}
template <typename T>
#ifdef TIME_IT
long long download(T* dst, T* src, int N)
#else
void download(T* dst, T* src, int N)
#endif
{
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1003:21: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors((dpct::get_default_queue()
.memcpy((void *)dst, (void *)src, N * sizeof(T))
.wait(),
0));
#ifdef TIME_IT
time1 = get_time();
return time1-time0;
#endif
}
#ifdef TIME_IT
long long dump(double* variables, int nel, int nelr)
#else
void dump(double* variables, int nel, int nelr)
#endif
{
double* h_variables = new double[nelr*NVAR];
#ifdef TIME_IT
long long time =
#endif
download(h_variables, variables, nelr*NVAR);
{
std::ofstream file("density");
file << nel << " " << nelr << std::endl;
for(int i = 0; i < nel; i++) file << h_variables[i + VAR_DENSITY*nelr] << std::endl;
}
{
std::ofstream file("momentum");
file << nel << " " << nelr << std::endl;
for(int i = 0; i < nel; i++)
{
for(int j = 0; j != NDIM; j++)
file << h_variables[i + (VAR_MOMENTUM+j)*nelr] << " ";
file << std::endl;
}
}
{
std::ofstream file("density_energy");
file << nel << " " << nelr << std::endl;
for(int i = 0; i < nel; i++) file << h_variables[i + VAR_DENSITY_ENERGY*nelr] << std::endl;
}
delete[] h_variables;
#ifdef TIME_IT
return time;
#endif
}
/*
* Element-based Cell-centered FVM solver functions
*/
dpct::constant_memory<double, 1> ff_variable(NVAR);
dpct::constant_memory<sycl::double3, 1> ff_flux_contribution_momentum_x(1);
dpct::constant_memory<sycl::double3, 1> ff_flux_contribution_momentum_y(1);
dpct::constant_memory<sycl::double3, 1> ff_flux_contribution_momentum_z(1);
dpct::constant_memory<sycl::double3, 1> ff_flux_contribution_density_energy(1);
SYCL_EXTERNAL void cuda_initialize_variables(int nelr, double *variables,
sycl::nd_item<3> item_ct1,
double *ff_variable)
{
const int i =
(item_ct1.get_local_range().get(2) * item_ct1.get_group(2) +
item_ct1.get_local_id(2));
for(int j = 0; j < NVAR; j++)
variables[i + j*nelr] = ff_variable[j];
}
#ifdef TIME_IT
long long initialize_variables(int nelr, double* variables)
#else
void initialize_variables(int nelr, double* variables)
#endif
{
sycl::range<3> Dg(1, 1, nelr / block_length), Db(1, 1, block_length);
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1049:22: The workgroup size passed to the SYCL kernel may exceed the
limit. To get the device limit, query info::device::max_work_group_size.
Adjust the workgroup size if needed.
*/
dpct::get_default_queue().submit([&](sycl::handler &cgh) {
extern dpct::constant_memory<double, 1> ff_variable;
ff_variable.init();
auto ff_variable_ptr_ct1 = ff_variable.get_ptr();
cgh.parallel_for(sycl::nd_range<3>(Dg * Db, Db),
[=](sycl::nd_item<3> item_ct1) {
cuda_initialize_variables(
nelr, variables, item_ct1,
ff_variable_ptr_ct1);
});
});
/*
DPCT1010:23: SYCL uses exceptions to report errors and does not use the
error codes. The call was replaced with 0. You need to rewrite this
code.
*/
int error = 0;
#ifdef TIME_IT
dpct::get_current_device().queues_wait_and_throw();
time1 = get_time();
return time1-time0;
#endif
}
SYCL_EXTERNAL inline void compute_flux_contribution(
double &density, sycl::double3 &momentum, double &density_energy,
double &pressure, sycl::double3 &velocity, sycl::double3 &fc_momentum_x,
sycl::double3 &fc_momentum_y, sycl::double3 &fc_momentum_z,
sycl::double3 &fc_density_energy)
{
fc_momentum_x.x() = velocity.x() * momentum.x() + pressure;
fc_momentum_x.y() = velocity.x() * momentum.y();
fc_momentum_x.z() = velocity.x() * momentum.z();
fc_momentum_y.x() = fc_momentum_x.y();
fc_momentum_y.y() = velocity.y() * momentum.y() + pressure;
fc_momentum_y.z() = velocity.y() * momentum.z();
fc_momentum_z.x() = fc_momentum_x.z();
fc_momentum_z.y() = fc_momentum_y.z();
fc_momentum_z.z() = velocity.z() * momentum.z() + pressure;
double de_p = density_energy+pressure;
fc_density_energy.x() = velocity.x() * de_p;
fc_density_energy.y() = velocity.y() * de_p;
fc_density_energy.z() = velocity.z() * de_p;
}
SYCL_EXTERNAL inline void compute_velocity(double &density,
sycl::double3 &momentum,
sycl::double3 &velocity)
{
velocity.x() = momentum.x() / density;
velocity.y() = momentum.y() / density;
velocity.z() = momentum.z() / density;
}
SYCL_EXTERNAL inline double compute_speed_sqd(sycl::double3 &velocity)
{
return velocity.x() * velocity.x() + velocity.y() * velocity.y() +
velocity.z() * velocity.z();
}
SYCL_EXTERNAL inline double
compute_pressure(double &density, double &density_energy, double &speed_sqd)
{
return (double(GAMMA)-double(1.0))*(density_energy - double(0.5)*density*speed_sqd);
}
SYCL_EXTERNAL inline double compute_speed_of_sound(double &density,
double &pressure)
{
return sycl::sqrt(double(GAMMA) * pressure / density);
}
SYCL_EXTERNAL void cuda_compute_step_factor(int nelr, double *variables,
double *areas, double *step_factors,
sycl::nd_item<3> item_ct1)
{
const int i =
(item_ct1.get_local_range().get(2) * item_ct1.get_group(2) +
item_ct1.get_local_id(2));
double density = variables[i + VAR_DENSITY*nelr];
sycl::double3 momentum;
momentum.x() = variables[i + (VAR_MOMENTUM + 0) * nelr];
momentum.y() = variables[i + (VAR_MOMENTUM + 1) * nelr];
momentum.z() = variables[i + (VAR_MOMENTUM + 2) * nelr];
double density_energy = variables[i + VAR_DENSITY_ENERGY*nelr];
sycl::double3 velocity; compute_velocity(density, momentum, velocity);
double speed_sqd = compute_speed_sqd(velocity);
double pressure = compute_pressure(density, density_energy, speed_sqd);
double speed_of_sound = compute_speed_of_sound(density, pressure);
// dt = double(0.5) * sqrt(areas[i]) / (||v|| + c).... but when we do time stepping, this later would need to be divided by the area, so we just do it all at once
step_factors[i] =
double(0.5) /
(sycl::sqrt(areas[i]) * (sycl::sqrt(speed_sqd) + speed_of_sound));
}
#ifdef TIME_IT
long long compute_step_factor(int nelr, double* variables, double* areas, double* step_factors)
#else
void compute_step_factor(int nelr, double* variables, double* areas, double* step_factors)
#endif
{
sycl::range<3> Dg(1, 1, nelr / block_length), Db(1, 1, block_length);
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1049:25: The workgroup size passed to the SYCL kernel may exceed the
limit. To get the device limit, query info::device::max_work_group_size.
Adjust the workgroup size if needed.
*/
dpct::get_default_queue().submit([&](sycl::handler &cgh) {
cgh.parallel_for(sycl::nd_range<3>(Dg * Db, Db),
[=](sycl::nd_item<3> item_ct1) {
cuda_compute_step_factor(
nelr, variables, areas,
step_factors, item_ct1);
});
});
/*
DPCT1010:26: SYCL uses exceptions to report errors and does not use the
error codes. The call was replaced with 0. You need to rewrite this
code.
*/
int error = 0;
#ifdef TIME_IT
dpct::get_current_device().queues_wait_and_throw();
time1 = get_time();
return time1-time0;
#endif
}
/*
*
*
*/
void cuda_compute_flux(int nelr, int* elements_surrounding_elements, double* normals, double* variables, double* fluxes,
sycl::nd_item<3> item_ct1, double *ff_variable,
sycl::double3 *ff_flux_contribution_momentum_x,
sycl::double3 *ff_flux_contribution_momentum_y,
sycl::double3 *ff_flux_contribution_momentum_z,
sycl::double3 *ff_flux_contribution_density_energy)
{
const double smoothing_coefficient = double(0.2f);
const int i =
(item_ct1.get_local_range().get(2) * item_ct1.get_group(2) +
item_ct1.get_local_id(2));
int j, nb;
sycl::double3 normal; double normal_len;
double factor;
double density_i = variables[i + VAR_DENSITY*nelr];
sycl::double3 momentum_i;
momentum_i.x() = variables[i + (VAR_MOMENTUM + 0) * nelr];
momentum_i.y() = variables[i + (VAR_MOMENTUM + 1) * nelr];
momentum_i.z() = variables[i + (VAR_MOMENTUM + 2) * nelr];
double density_energy_i = variables[i + VAR_DENSITY_ENERGY*nelr];
sycl::double3 velocity_i; compute_velocity(density_i, momentum_i, velocity_i);
double speed_sqd_i = compute_speed_sqd(velocity_i);
double speed_i = sycl::sqrt(speed_sqd_i);
double pressure_i = compute_pressure(density_i, density_energy_i, speed_sqd_i);
double speed_of_sound_i = compute_speed_of_sound(density_i, pressure_i);
sycl::double3 flux_contribution_i_momentum_x,
flux_contribution_i_momentum_y, flux_contribution_i_momentum_z;
sycl::double3 flux_contribution_i_density_energy;
compute_flux_contribution(density_i, momentum_i, density_energy_i, pressure_i, velocity_i, flux_contribution_i_momentum_x, flux_contribution_i_momentum_y, flux_contribution_i_momentum_z, flux_contribution_i_density_energy);
double flux_i_density = double(0.0);
sycl::double3 flux_i_momentum;
flux_i_momentum.x() = double(0.0);
flux_i_momentum.y() = double(0.0);
flux_i_momentum.z() = double(0.0);
double flux_i_density_energy = double(0.0);
sycl::double3 velocity_nb;
double density_nb, density_energy_nb;
sycl::double3 momentum_nb;
sycl::double3 flux_contribution_nb_momentum_x,
flux_contribution_nb_momentum_y, flux_contribution_nb_momentum_z;
sycl::double3 flux_contribution_nb_density_energy;
double speed_sqd_nb, speed_of_sound_nb, pressure_nb;
#pragma unroll
for(j = 0; j < NNB; j++)
{
nb = elements_surrounding_elements[i + j*nelr];
normal.x() = normals[i + (j + 0 * NNB) * nelr];
normal.y() = normals[i + (j + 1 * NNB) * nelr];
normal.z() = normals[i + (j + 2 * NNB) * nelr];
normal_len = sycl::sqrt(normal.x() * normal.x() +
normal.y() * normal.y() +
normal.z() * normal.z());
if(nb >= 0) // a legitimate neighbor
{
density_nb = variables[nb + VAR_DENSITY*nelr];
momentum_nb.x() = variables[nb + (VAR_MOMENTUM + 0) * nelr];
momentum_nb.y() = variables[nb + (VAR_MOMENTUM + 1) * nelr];
momentum_nb.z() = variables[nb + (VAR_MOMENTUM + 2) * nelr];
density_energy_nb = variables[nb + VAR_DENSITY_ENERGY*nelr];
compute_velocity(density_nb, momentum_nb, velocity_nb);
speed_sqd_nb = compute_speed_sqd(velocity_nb);
pressure_nb = compute_pressure(density_nb, density_energy_nb, speed_sqd_nb);
speed_of_sound_nb = compute_speed_of_sound(density_nb, pressure_nb);
compute_flux_contribution(density_nb, momentum_nb, density_energy_nb, pressure_nb, velocity_nb, flux_contribution_nb_momentum_x, flux_contribution_nb_momentum_y, flux_contribution_nb_momentum_z, flux_contribution_nb_density_energy);
// artificial viscosity
factor = -normal_len * smoothing_coefficient *
double(0.5) *
(speed_i + sycl::sqrt(speed_sqd_nb) +
speed_of_sound_i + speed_of_sound_nb);
flux_i_density += factor*(density_i-density_nb);
flux_i_density_energy += factor*(density_energy_i-density_energy_nb);
flux_i_momentum.x() += factor * (momentum_i.x() - momentum_nb.x());
flux_i_momentum.y() += factor * (momentum_i.y() - momentum_nb.y());
flux_i_momentum.z() += factor * (momentum_i.z() - momentum_nb.z());
// accumulate cell-centered fluxes
factor = double(0.5) * normal.x();
flux_i_density += factor * (momentum_nb.x() + momentum_i.x());
flux_i_density_energy +=
factor * (flux_contribution_nb_density_energy.x() +
flux_contribution_i_density_energy.x());
flux_i_momentum.x() +=
factor * (flux_contribution_nb_momentum_x.x() +
flux_contribution_i_momentum_x.x());
flux_i_momentum.y() +=
factor * (flux_contribution_nb_momentum_y.x() +
flux_contribution_i_momentum_y.x());
flux_i_momentum.z() +=
factor * (flux_contribution_nb_momentum_z.x() +
flux_contribution_i_momentum_z.x());
factor = double(0.5) * normal.y();
flux_i_density += factor * (momentum_nb.y() + momentum_i.y());
flux_i_density_energy +=
factor * (flux_contribution_nb_density_energy.y() +
flux_contribution_i_density_energy.y());
flux_i_momentum.x() +=
factor * (flux_contribution_nb_momentum_x.y() +
flux_contribution_i_momentum_x.y());
flux_i_momentum.y() +=
factor * (flux_contribution_nb_momentum_y.y() +
flux_contribution_i_momentum_y.y());
flux_i_momentum.z() +=
factor * (flux_contribution_nb_momentum_z.y() +
flux_contribution_i_momentum_z.y());
factor = double(0.5) * normal.z();
flux_i_density += factor * (momentum_nb.z() + momentum_i.z());
flux_i_density_energy +=
factor * (flux_contribution_nb_density_energy.z() +
flux_contribution_i_density_energy.z());
flux_i_momentum.x() +=
factor * (flux_contribution_nb_momentum_x.z() +
flux_contribution_i_momentum_x.z());
flux_i_momentum.y() +=
factor * (flux_contribution_nb_momentum_y.z() +
flux_contribution_i_momentum_y.z());
flux_i_momentum.z() +=
factor * (flux_contribution_nb_momentum_z.z() +
flux_contribution_i_momentum_z.z());
}
else if(nb == -1) // a wing boundary
{
flux_i_momentum.x() += normal.x() * pressure_i;
flux_i_momentum.y() += normal.y() * pressure_i;
flux_i_momentum.z() += normal.z() * pressure_i;
}
else if(nb == -2) // a far field boundary
{
factor = double(0.5) * normal.x();
flux_i_density +=
factor *
(ff_variable[VAR_MOMENTUM + 0] + momentum_i.x());
flux_i_density_energy +=
factor *
(ff_flux_contribution_density_energy[0].x() +
flux_contribution_i_density_energy.x());
flux_i_momentum.x() +=
factor * (ff_flux_contribution_momentum_x[0].x() +
flux_contribution_i_momentum_x.x());
flux_i_momentum.y() +=
factor * (ff_flux_contribution_momentum_y[0].x() +
flux_contribution_i_momentum_y.x());
flux_i_momentum.z() +=
factor * (ff_flux_contribution_momentum_z[0].x() +
flux_contribution_i_momentum_z.x());
factor = double(0.5) * normal.y();
flux_i_density +=
factor *
(ff_variable[VAR_MOMENTUM + 1] + momentum_i.y());
flux_i_density_energy +=
factor *
(ff_flux_contribution_density_energy[0].y() +
flux_contribution_i_density_energy.y());
flux_i_momentum.x() +=
factor * (ff_flux_contribution_momentum_x[0].y() +
flux_contribution_i_momentum_x.y());
flux_i_momentum.y() +=
factor * (ff_flux_contribution_momentum_y[0].y() +
flux_contribution_i_momentum_y.y());
flux_i_momentum.z() +=
factor * (ff_flux_contribution_momentum_z[0].y() +
flux_contribution_i_momentum_z.y());
factor = double(0.5) * normal.z();
flux_i_density +=
factor *
(ff_variable[VAR_MOMENTUM + 2] + momentum_i.z());
flux_i_density_energy +=
factor *
(ff_flux_contribution_density_energy[0].z() +
flux_contribution_i_density_energy.z());
flux_i_momentum.x() +=
factor * (ff_flux_contribution_momentum_x[0].z() +
flux_contribution_i_momentum_x.z());
flux_i_momentum.y() +=
factor * (ff_flux_contribution_momentum_y[0].z() +
flux_contribution_i_momentum_y.z());
flux_i_momentum.z() +=
factor * (ff_flux_contribution_momentum_z[0].z() +
flux_contribution_i_momentum_z.z());
}
}
fluxes[i + VAR_DENSITY*nelr] = flux_i_density;
fluxes[i + (VAR_MOMENTUM + 0) * nelr] = flux_i_momentum.x();
fluxes[i + (VAR_MOMENTUM + 1) * nelr] = flux_i_momentum.y();
fluxes[i + (VAR_MOMENTUM + 2) * nelr] = flux_i_momentum.z();
fluxes[i + VAR_DENSITY_ENERGY*nelr] = flux_i_density_energy;
}
#ifdef TIME_IT
long long compute_flux(int nelr, int* elements_surrounding_elements, double* normals, double* variables, double* fluxes)
#else
void compute_flux(int nelr, int* elements_surrounding_elements, double* normals, double* variables, double* fluxes)
#endif
{
sycl::range<3> Dg(1, 1, nelr / block_length), Db(1, 1, block_length);
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1049:28: The workgroup size passed to the SYCL kernel may exceed the
limit. To get the device limit, query info::device::max_work_group_size.
Adjust the workgroup size if needed.
*/
dpct::get_default_queue().submit([&](sycl::handler &cgh) {
ff_variable.init();
ff_flux_contribution_momentum_x.init();
ff_flux_contribution_momentum_y.init();
ff_flux_contribution_momentum_z.init();
ff_flux_contribution_density_energy.init();
auto ff_variable_ptr_ct1 = ff_variable.get_ptr();
auto ff_flux_contribution_momentum_x_ptr_ct1 =
ff_flux_contribution_momentum_x.get_ptr();
auto ff_flux_contribution_momentum_y_ptr_ct1 =
ff_flux_contribution_momentum_y.get_ptr();
auto ff_flux_contribution_momentum_z_ptr_ct1 =
ff_flux_contribution_momentum_z.get_ptr();
auto ff_flux_contribution_density_energy_ptr_ct1 =
ff_flux_contribution_density_energy.get_ptr();
cgh.parallel_for(
sycl::nd_range<3>(Dg * Db, Db),
[=](sycl::nd_item<3> item_ct1) {
cuda_compute_flux(
nelr, elements_surrounding_elements, normals,
variables, fluxes, item_ct1,
ff_variable_ptr_ct1,
ff_flux_contribution_momentum_x_ptr_ct1,
ff_flux_contribution_momentum_y_ptr_ct1,
ff_flux_contribution_momentum_z_ptr_ct1,
ff_flux_contribution_density_energy_ptr_ct1);
});
});
/*
DPCT1010:29: SYCL uses exceptions to report errors and does not use the
error codes. The call was replaced with 0. You need to rewrite this
code.
*/
int error = 0;
#ifdef TIME_IT
dpct::get_current_device().queues_wait_and_throw();
time1 = get_time();
return time1-time0;
#endif
}
SYCL_EXTERNAL void cuda_time_step(int j, int nelr, double *old_variables,
double *variables, double *step_factors,
double *fluxes, sycl::nd_item<3> item_ct1)
{
const int i =
(item_ct1.get_local_range().get(2) * item_ct1.get_group(2) +
item_ct1.get_local_id(2));
double factor = step_factors[i]/double(RK+1-j);
variables[i + VAR_DENSITY*nelr] = old_variables[i + VAR_DENSITY*nelr] + factor*fluxes[i + VAR_DENSITY*nelr];
variables[i + VAR_DENSITY_ENERGY*nelr] = old_variables[i + VAR_DENSITY_ENERGY*nelr] + factor*fluxes[i + VAR_DENSITY_ENERGY*nelr];
variables[i + (VAR_MOMENTUM+0)*nelr] = old_variables[i + (VAR_MOMENTUM+0)*nelr] + factor*fluxes[i + (VAR_MOMENTUM+0)*nelr];
variables[i + (VAR_MOMENTUM+1)*nelr] = old_variables[i + (VAR_MOMENTUM+1)*nelr] + factor*fluxes[i + (VAR_MOMENTUM+1)*nelr];
variables[i + (VAR_MOMENTUM+2)*nelr] = old_variables[i + (VAR_MOMENTUM+2)*nelr] + factor*fluxes[i + (VAR_MOMENTUM+2)*nelr];
}
#ifdef TIME_IT
long long time_step(int j, int nelr, double* old_variables, double* variables, double* step_factors, double* fluxes)
#else
void time_step(int j, int nelr, double* old_variables, double* variables, double* step_factors, double* fluxes)
#endif
{
sycl::range<3> Dg(1, 1, nelr / block_length), Db(1, 1, block_length);
#ifdef TIME_IT
long long time1;
long long time0 = get_time();
#endif
/*
DPCT1049:31: The workgroup size passed to the SYCL kernel may exceed the
limit. To get the device limit, query info::device::max_work_group_size.
Adjust the workgroup size if needed.
*/
dpct::get_default_queue().submit([&](sycl::handler &cgh) {
cgh.parallel_for(sycl::nd_range<3>(Dg * Db, Db),
[=](sycl::nd_item<3> item_ct1) {
cuda_time_step(j, nelr, old_variables,
variables, step_factors,
fluxes, item_ct1);
});
});
/*
DPCT1010:32: SYCL uses exceptions to report errors and does not use the
error codes. The call was replaced with 0. You need to rewrite this
code.
*/
int error = 0;
#ifdef TIME_IT
dpct::get_current_device().queues_wait_and_throw();
time1 = get_time();
return time1-time0;
#endif
}
/*
* Main function
*/
int main(int argc, char** argv)
{
#ifdef TIME_IT
long long initTime = 0;
long long alocTime = 0;
long long cpInTime = 0;
long long kernTime = 0;
long long cpOtTime = 0;
long long freeTime = 0;
long long auxTime1 = 0;
long long auxTime2 = 0;
#endif
if (argc < 2)
{
std::cout << "specify data file name" << std::endl;
return 0;
}
const char* data_file_name = argv[1];
// CUDA_SAFE_CALL(cudaSetDevice(0));
// CUDA_SAFE_CALL(cudaGetDevice(&dev));
// CUDA_SAFE_CALL(cudaGetDeviceProperties(&prop, dev));
/*
DPCT1003:34: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
#ifdef TIME_IT
auxTime1 = get_time();
select_custom_device();
auxTime2 = get_time();
initTime = auxTime2-auxTime1;
#else
select_custom_device();
//checkCudaErrors(dev = dpct::dev_mgr::instance().current_device_id());
#endif
/*
DPCT1003:35: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
// set far field conditions and load them into constant memory on the gpu
{
double h_ff_variable[NVAR];
const double angle_of_attack = double(3.1415926535897931 / 180.0) * double(deg_angle_of_attack);
h_ff_variable[VAR_DENSITY] = double(1.4);
double ff_pressure = double(1.0);
double ff_speed_of_sound = sqrt(GAMMA*ff_pressure / h_ff_variable[VAR_DENSITY]);
double ff_speed = double(ff_mach)*ff_speed_of_sound;
sycl::double3 ff_velocity;
ff_velocity.x() = ff_speed * double(cos((double)angle_of_attack));
ff_velocity.y() = ff_speed * double(sin((double)angle_of_attack));
ff_velocity.z() = 0.0;
h_ff_variable[VAR_MOMENTUM + 0] =
h_ff_variable[VAR_DENSITY] * ff_velocity.x();
h_ff_variable[VAR_MOMENTUM + 1] =
h_ff_variable[VAR_DENSITY] * ff_velocity.y();
h_ff_variable[VAR_MOMENTUM + 2] =
h_ff_variable[VAR_DENSITY] * ff_velocity.z();
h_ff_variable[VAR_DENSITY_ENERGY] = h_ff_variable[VAR_DENSITY]*(double(0.5)*(ff_speed*ff_speed)) + (ff_pressure / double(GAMMA-1.0));
sycl::double3 h_ff_momentum;
h_ff_momentum.x() = *(h_ff_variable + VAR_MOMENTUM + 0);
h_ff_momentum.y() = *(h_ff_variable + VAR_MOMENTUM + 1);
h_ff_momentum.z() = *(h_ff_variable + VAR_MOMENTUM + 2);
sycl::double3 h_ff_flux_contribution_momentum_x;
sycl::double3 h_ff_flux_contribution_momentum_y;
sycl::double3 h_ff_flux_contribution_momentum_z;
sycl::double3 h_ff_flux_contribution_density_energy;
compute_flux_contribution(h_ff_variable[VAR_DENSITY], h_ff_momentum, h_ff_variable[VAR_DENSITY_ENERGY], ff_pressure, ff_velocity, h_ff_flux_contribution_momentum_x, h_ff_flux_contribution_momentum_y, h_ff_flux_contribution_momentum_z, h_ff_flux_contribution_density_energy);
// copy far field conditions to the gpu
/*
DPCT1003:36: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
#ifdef TIME_IT
auxTime1 = get_time();
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_variable.get_ptr(), h_ff_variable,
NVAR * sizeof(double))
.wait(),
0));
auxTime2 = get_time();
cpInTime += auxTime2-auxTime1;
auxTime1 = get_time();
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_momentum_x.get_ptr(),
&h_ff_flux_contribution_momentum_x,
sizeof(sycl::double3))
.wait(),
0));
auxTime2 = get_time();
cpInTime += auxTime2-auxTime1;
auxTime1 = get_time();
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_momentum_y.get_ptr(),
&h_ff_flux_contribution_momentum_y,
sizeof(sycl::double3))
.wait(),
0));
auxTime2 = get_time();
cpInTime += auxTime2-auxTime1;
auxTime1 = get_time();
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_momentum_z.get_ptr(),
&h_ff_flux_contribution_momentum_z,
sizeof(sycl::double3))
.wait(),
0));
auxTime2 = get_time();
cpInTime += auxTime2-auxTime1;
auxTime1 = get_time();
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_density_energy.get_ptr(),
&h_ff_flux_contribution_density_energy,
sizeof(sycl::double3))
.wait(),
0));
auxTime2 = get_time();
cpInTime += auxTime2-auxTime1;
#else
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_variable.get_ptr(), h_ff_variable,
NVAR * sizeof(double))
.wait(),
0));
/*
DPCT1003:37: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_momentum_x.get_ptr(),
&h_ff_flux_contribution_momentum_x,
sizeof(sycl::double3))
.wait(),
0));
/*
DPCT1003:38: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_momentum_y.get_ptr(),
&h_ff_flux_contribution_momentum_y,
sizeof(sycl::double3))
.wait(),
0));
/*
DPCT1003:39: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_momentum_z.get_ptr(),
&h_ff_flux_contribution_momentum_z,
sizeof(sycl::double3))
.wait(),
0));
/*
DPCT1003:40: Migrated API does not return error code. (*, 0) is
inserted. You may need to rewrite this code.
*/
checkCudaErrors(
(dpct::get_default_queue()
.memcpy(ff_flux_contribution_density_energy.get_ptr(),
&h_ff_flux_contribution_density_energy,
sizeof(sycl::double3))
.wait(),
0));
#endif
}
int nel;
int nelr;
// read in domain geometry
double* areas;
int* elements_surrounding_elements;
double* normals;
{
std::ifstream file(data_file_name);
file >> nel;
nelr = block_length *
((nel / block_length) + std::min(1, nel % block_length));
double* h_areas = new double[nelr];
int* h_elements_surrounding_elements = new int[nelr*NNB];
double* h_normals = new double[nelr*NDIM*NNB];
// read in data
for(int i = 0; i < nel; i++)
{
file >> h_areas[i];
for(int j = 0; j < NNB; j++)
{
file >> h_elements_surrounding_elements[i + j*nelr];
if(h_elements_surrounding_elements[i+j*nelr] < 0) h_elements_surrounding_elements[i+j*nelr] = -1;
h_elements_surrounding_elements[i + j*nelr]--; //it's coming in with Fortran numbering
for(int k = 0; k < NDIM; k++)
{
file >> h_normals[i + (j + k*NNB)*nelr];
h_normals[i + (j + k*NNB)*nelr] = -h_normals[i + (j + k*NNB)*nelr];
}
}
}
// fill in remaining data
int last = nel-1;
for(int i = nel; i < nelr; i++)
{
h_areas[i] = h_areas[last];
for(int j = 0; j < NNB; j++)
{
// duplicate the last element
h_elements_surrounding_elements[i + j*nelr] = h_elements_surrounding_elements[last + j*nelr];
for(int k = 0; k < NDIM; k++) h_normals[last + (j + k*NNB)*nelr] = h_normals[last + (j + k*NNB)*nelr];
}
}
#ifdef TIME_IT
areas = alloc<double>(nelr, auxTime1);
alocTime += auxTime1;
cpInTime += upload<double>(areas, h_areas, nelr);
elements_surrounding_elements = alloc<int>(nelr*NNB, auxTime1);
alocTime += auxTime1;
cpInTime += upload<int>(elements_surrounding_elements, h_elements_surrounding_elements, nelr*NNB);
normals = alloc<double>(nelr*NDIM*NNB, auxTime1);
alocTime += auxTime1;
cpInTime += upload<double>(normals, h_normals, nelr*NDIM*NNB);
#else
areas = alloc<double>(nelr);
upload<double>(areas, h_areas, nelr);
elements_surrounding_elements = alloc<int>(nelr*NNB);
upload<int>(elements_surrounding_elements, h_elements_surrounding_elements, nelr*NNB);
normals = alloc<double>(nelr*NDIM*NNB);
upload<double>(normals, h_normals, nelr*NDIM*NNB);
#endif
delete[] h_areas;
delete[] h_elements_surrounding_elements;
delete[] h_normals;
}
#ifdef TIME_IT
double* variables = alloc<double>(nelr*NVAR, auxTime1);
alocTime += auxTime1;
kernTime += initialize_variables(nelr, variables);
double* old_variables = alloc<double>(nelr*NVAR, auxTime1);
alocTime += auxTime1;
double* fluxes = alloc<double>(nelr*NVAR, auxTime1);
alocTime += auxTime1;
double* step_factors = alloc<double>(nelr, auxTime1);
alocTime += auxTime1;
kernTime += initialize_variables(nelr, old_variables);
kernTime += initialize_variables(nelr, fluxes);
dpct::get_default_queue()
.memset((void *)step_factors, 0, sizeof(double) * nelr)
.wait();
// make sure CUDA isn't still doing something before we start timing
dpct::get_current_device().queues_wait_and_throw();
#else
// Create arrays and set initial conditions
double* variables = alloc<double>(nelr*NVAR);
initialize_variables(nelr, variables);
double* old_variables = alloc<double>(nelr*NVAR);
double* fluxes = alloc<double>(nelr*NVAR);
double* step_factors = alloc<double>(nelr);
// make sure all memory is doublely allocated before we start timing
initialize_variables(nelr, old_variables);
initialize_variables(nelr, fluxes);
dpct::get_default_queue()
.memset((void *)step_factors, 0, sizeof(double) * nelr)
.wait();
// make sure CUDA isn't still doing something before we start timing
dpct::get_current_device().queues_wait_and_throw();
#endif
// these need to be computed the first time in order to compute time step
std::cout << "Starting..." << std::endl;
int error;
StopWatchInterface *timer = NULL;
sdkCreateTimer( &timer);
sdkStartTimer( &timer);
// Begin iterations
for(int i = 0; i < iterations; i++)
{
#ifdef TIME_IT
copy<double>(old_variables, variables, nelr*NVAR);
kernTime += compute_step_factor(nelr, variables, areas, step_factors);
for(int j = 0; j < RK; j++)
{
kernTime += compute_flux(nelr, elements_surrounding_elements, normals, variables, fluxes);
kernTime += time_step(j, nelr, old_variables, variables, step_factors, fluxes);
}
#else
copy<double>(old_variables, variables, nelr*NVAR);
// for the first iteration we compute the time step
compute_step_factor(nelr, variables, areas, step_factors);
/*
DPCT1010:41: SYCL uses exceptions to report errors and does not
use the error codes. The call was replaced with 0. You need to
rewrite this code.
*/
error = 0;
for(int j = 0; j < RK; j++)
{
compute_flux(nelr, elements_surrounding_elements, normals, variables, fluxes);
/*
DPCT1010:43: SYCL uses exceptions to report errors and does
not use the error codes. The call was replaced with 0. You
need to rewrite this code.
*/
error = 0;
time_step(j, nelr, old_variables, variables, step_factors, fluxes);
/*
DPCT1010:45: SYCL uses exceptions to report errors and does
not use the error codes. The call was replaced with 0. You
need to rewrite this code.
*/
error = 0;
}
#endif
}
dpct::get_current_device().queues_wait_and_throw();
sdkStopTimer(&timer);
std::cout << (sdkGetAverageTimerValue(&timer)/1000.0) / iterations << " seconds per iteration" << std::endl;
std::cout << "Saving solution..." << std::endl;
#ifdef TIME_IT
cpOtTime +=
#endif
dump(variables, nel, nelr);
std::cout << "Saved solution..." << std::endl;
std::cout << "Cleaning up..." << std::endl;
#ifdef TIME_IT
freeTime +=
#endif
dealloc<double>(areas);
#ifdef TIME_IT
freeTime +=
#endif
dealloc<int>(elements_surrounding_elements);
#ifdef TIME_IT
freeTime +=
#endif
dealloc<double>(normals);
#ifdef TIME_IT
freeTime +=
#endif
dealloc<double>(variables);
#ifdef TIME_IT
freeTime +=
#endif
dealloc<double>(old_variables);
#ifdef TIME_IT
freeTime +=
#endif
dealloc<double>(fluxes);
#ifdef TIME_IT
freeTime +=
#endif
dealloc<double>(step_factors);
std::cout << "Done..." << std::endl;
#ifdef TIME_IT
long long totalTime = initTime + alocTime + cpInTime + kernTime + cpOtTime + freeTime;
printf("Time spent in different stages of GPU_CUDA KERNEL:\n");
printf("%15.12f s, %15.12f % : GPU: SET DEVICE / DRIVER INIT\n", (float) initTime / 1000000, (float) initTime / (float) totalTime * 100);
printf("%15.12f s, %15.12f % : GPU MEM: ALO\n", (float) alocTime / 1000000, (float) alocTime / (float) totalTime * 100);
printf("%15.12f s, %15.12f % : GPU MEM: COPY IN\n", (float) cpInTime / 1000000, (float) cpInTime / (float) totalTime * 100);
printf("%15.12f s, %15.12f % : GPU: KERNEL\n", (float) kernTime / 1000000, (float) kernTime / (float) totalTime * 100);
printf("%15.12f s, %15.12f % : GPU MEM: COPY OUT\n", (float) cpOtTime / 1000000, (float) cpOtTime / (float) totalTime * 100);
printf("%15.12f s, %15.12f % : GPU MEM: FRE\n", (float) freeTime / 1000000, (float) freeTime / (float) totalTime * 100);
printf("Total time:\n");
printf("%.12f s\n", (float) totalTime / 1000000);
#endif
return 0;
}
| 39.083262 | 290 | 0.550668 | [
"geometry"
] |
90341e4d4f8fee2f0960c21cfd5db2822b343e58 | 3,727 | cpp | C++ | src/Library/Physics/Data/Direction.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | src/Library/Physics/Data/Direction.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | src/Library/Physics/Data/Direction.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Physics
/// @file Library/Physics/Data/Direction.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Physics/Data/Direction.hpp>
#include <Library/Physics/Unit.hpp>
#include <Library/Core/Types/Real.hpp>
#include <Library/Core/Error.hpp>
#include <Library/Core/Utilities.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace library
{
namespace physics
{
namespace data
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using library::core::types::Real ;
using library::physics::Unit ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Direction::Direction ( const Vector3d& aValue,
const Shared<const Frame>& aFrameSPtr )
: Vector(aValue.normalized(), Unit::None(), aFrameSPtr)
{
if (std::abs(aValue.norm() - 1.0) > Real::Epsilon())
{
throw library::core::error::RuntimeError("Direction vector is not unitary [{}].", aValue.norm()) ;
}
}
bool Direction::operator == ( const Direction& aDirection ) const
{
if ((!this->isDefined()) || (!aDirection.isDefined()))
{
return false ;
}
return Vector::operator == (aDirection) ;
}
bool Direction::operator != ( const Direction& aDirection ) const
{
return !((*this) == aDirection) ;
}
std::ostream& operator << ( std::ostream& anOutputStream,
const Direction& aDirection )
{
library::core::utils::Print::Header(anOutputStream, "Direction") ;
library::core::utils::Print::Line(anOutputStream) << "Value:" << (aDirection.getValue().isDefined() ? aDirection.getValue().toString() : "Undefined") ;
library::core::utils::Print::Line(anOutputStream) << "Frame:" << (((aDirection.getFrame() != nullptr) && (aDirection.getFrame()->isDefined())) ? aDirection.getFrame()->getName() : "Undefined") ;
library::core::utils::Print::Footer(anOutputStream) ;
return anOutputStream ;
}
Direction Direction::Undefined ( )
{
return { Vector3d::Undefined(), Frame::Undefined() } ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 41.411111 | 213 | 0.332439 | [
"vector"
] |
903cd33b5cd00f8c7b777a49a275a470feeb65ae | 1,338 | cpp | C++ | microcode/addr_alu_test.cpp | mortenjc/fpgacode | 28849d243f76fad71e0df720e2afe142fcc06ef9 | [
"BSD-2-Clause"
] | null | null | null | microcode/addr_alu_test.cpp | mortenjc/fpgacode | 28849d243f76fad71e0df720e2afe142fcc06ef9 | [
"BSD-2-Clause"
] | null | null | null | microcode/addr_alu_test.cpp | mortenjc/fpgacode | 28849d243f76fad71e0df720e2afe142fcc06ef9 | [
"BSD-2-Clause"
] | null | null | null |
#include <addr_alu_alu_types.h>
#include <addr_alu.h>
#include <verilated.h>
#include <gtest/gtest.h>
#include <string>
#include <vector>
class TestCase {
public:
std::string name;
uint32_t x;
uint32_t y; // unused
uint8_t cmd;
uint32_t expected_z;
uint8_t expected_zflag;
};
using cmd_t = addr_alu_alu_types::cmd_t;
std::vector<TestCase> tests {
{"inc1", 0, 0, cmd_t::INC, 1, 0},
{"inc2", 1, 0, cmd_t::INC, 2, 0},
{"inc3", 0x1FFFE, 0, cmd_t::INC, 0x1FFFF, 0},
{"inc4", 0x1FFFF, 0, cmd_t::INC, 0, 1},
};
class ADDRALUTest: public ::testing::Test {
protected:
addr_alu * alu1;
void SetUp( ) {
alu1 = new addr_alu;
alu1->x = 0;
alu1->y = 0;
alu1->cmd = cmd_t::NONE;
alu1->eval();
}
void TearDown( ) {
alu1->final();
delete alu1;
}
};
TEST_F(ADDRALUTest, BasicCommands) {
for (auto & test : tests) {
alu1->x = test.x;
alu1->y = test.y;
alu1->cmd = test.cmd;
alu1->eval();
printf("subtest: %s\n", test.name.c_str());
ASSERT_EQ(alu1->z, test.expected_z);
ASSERT_EQ(alu1->zflag, test.expected_zflag);
}
}
int main(int argc, char **argv) {
Verilated::commandArgs(argc, argv);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 19.676471 | 63 | 0.573991 | [
"vector"
] |
9041484817ac99f7886760cc65834dcffa4f4364 | 9,520 | cpp | C++ | WaveletTL/tests/test_tbasis_equation.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | WaveletTL/tests/test_tbasis_equation.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | WaveletTL/tests/test_tbasis_equation.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | #include <iostream>
#include <fstream>
#include <set>
#include <algebra/vector.h>
#include <algebra/infinite_vector.h>
#include <utils/function.h>
#include <utils/fixed_array1d.h>
#include <numerics/bvp.h>
#include <numerics/bezier.h>
#include <geometry/sampled_mapping.h>
//#include <interval/ds_basis.h>
#include <interval/p_basis.h>
//#include <interval/jl_basis.h>
//#include <interval/jl_support.h>
//#include <interval/jl_evaluate.h>
#define _WAVELETTL_GALERKINUTILS_VERBOSITY 1
#include <cube/tbasis.h>
#include <galerkin/tbasis_equation.h>
#include <cube/tbasis_evaluate.h>
using namespace std;
using namespace MathTL;
using namespace WaveletTL;
/*
Some test problem for the Poisson equation on the cube with homogeneous Dirichlet b.c.'s:
1: -Delta u(x,y) = 2(x(1-x)+y(1-y)), u(x,y) = x(1-x)y(1-y)
2: -Delta u(x,y) = 2*pi^2*sin(pi*x)*sin(pi*y), u(x,y) = sin(pi*x)*sin(pi*y)
3: u cubic Hermite interpolant
*/
template <unsigned int N>
class myRHS
: public Function<2,double>
{
public:
virtual ~myRHS() {};
double value(const Point<2>& p, const unsigned int component = 0) const {
switch(N) {
case 1:
return 2*(p[0]*(1-p[0])+p[1]*(1-p[1]));
break;
case 2:
return 2*M_PI*M_PI*sin(M_PI*p[0])*sin(M_PI*p[1]);
break;
case 3:
return
-((p[0]<=0.5 ? 24-96*p[0] : 96*p[0]-72)
* (p[1]<=0.5 ? 4*p[1]*p[1]*(3-4*p[1]) : (2-2*p[1])*(2-2*p[1])*(4*p[1]-1))
+(p[0]<=0.5 ? 4*p[0]*p[0]*(3-4*p[0]) : (2-2*p[0])*(2-2*p[0])*(4*p[0]-1))
* (p[1]<=0.5 ? 24-96*p[1] : 96*p[1]-72));
break;
default:
return 1;
break;
}
}
void vector_value(const Point<2>& p, Vector<double>& values) const {
values[0] = value(p);
}
};
template <unsigned int N>
class mySolution
: public Function<2,double>
{
public:
virtual ~mySolution() {};
double value(const Point<2>& p, const unsigned int component = 0) const {
switch(N) {
case 1:
return p[0]*(1-p[0])*p[1]*(1-p[1]);
break;
case 2:
return sin(M_PI*p[0])*sin(M_PI*p[1]);
break;
case 3:
return
(p[0]<=0.5 ? 4*p[0]*p[0]*(3-4*p[0]) : (2-2*p[0])*(2-2*p[0])*(4*p[0]-1))
* (p[1]<=0.5 ? 4*p[1]*p[1]*(3-4*p[1]) : (2-2*p[1])*(2-2*p[1])*(4*p[1]-1));
break;
default:
return 0;
break;
}
}
void vector_value(const Point<2>& p, Vector<double>& values) const {
values[0] = value(p);
}
};
int main()
{
cout << "Testing wavelet-Galerkin solution of an elliptic equation on the cube ..." << endl;
#if 1
const int d = 4;
const int dT = 4; // be sure to use a continuous dual here, otherwise the RHS test will fail
const int dim = 2;
const int radius = 0; // range for the Level in the indexset of the stiffness matrix
ConstantFunction<dim> constant_rhs(Vector<double>(1, "1.0"));
PoissonBVP<dim> poisson(&constant_rhs);
//typedef DSBasis<d,dT> Basis1D;
typedef PBasis<d,dT> Basis1D;
#else
typedef JLBasis Basis1D; // does not work at the moment
#endif
typedef TensorBasis<Basis1D,dim> Basis;
typedef Basis::Index Index;
FixedArray1D<bool,(2*dim)> bc;
if (dim==1)
{
bc[0] = bc[1] = true;
}
else
{
bc[0] = bc[1] = bc[2] = bc[3] = true;
}
TensorEquation<Basis1D,dim,Basis> eq(&poisson, bc);
InfiniteVector<double, Index> coeffs;
#if 0
coeffs[first_generator<Basis1D,2,Basis>(&eq.basis())] = 1.0;
coeffs[last_generator<Basis1D,2,Basis>(&eq.basis())] = 2.0;
coeffs[first_wavelet<Basis1D,2,Basis>(&eq.basis(), eq.basis().j0())] = 3.0;
Index lambda = last_wavelet<Basis1D,2,Basis>(&eq.basis(), eq.basis().j0());
coeffs[lambda] = 4.0;
++lambda;
coeffs[lambda] = 5.0;
cout << "- a coefficient set:" << endl
<< coeffs << endl;
coeffs.scale(&eq, -1);
cout << "- after rescaling with D^{-1}:" << endl
<< coeffs << endl;
#endif
eq.RHS(1e-8, coeffs);
#if 0
// cout << "- approximate coefficient set of the right-hand side:" << endl
// << coeffs << endl;
cout << "- check expansion of the right-hand side in the dual basis:" << endl;
coeffs.scale(&eq, 1);
SampledMapping<2> S(evaluate<Basis1D,2>(eq.basis(), coeffs, false, 6));
// std::ofstream rhs_stream("constant_rhs.m");
// S.matlab_output(rhs_stream);
// rhs_stream.close();
// cout << " ... done, see file 'constant_rhs.m'" << endl;
S.add(-1.0, SampledMapping<2>(S, constant_rhs));
cout << " ... done, pointwise error: " << row_sum_norm(S.values()) << endl;
coeffs.scale(&eq, -1);
#endif
set<Index> Lambda;
for (Index lambda = first_generator<Basis1D,dim,Basis>(&eq.basis()), itend = last_wavelet<Basis1D,dim,Basis>(&eq.basis(), multi_degree(eq.basis().j0())+radius);; ++lambda)
//for (Index lambda = first_generator<Basis1D,2,Basis>(&eq.basis()), itend = last_wavelet<Basis1D,2,Basis>(&eq.basis(), eq.basis().j0());; ++lambda)
{
// Test fuer Richtigkeit der Reihenfolge die durch ++ gegeben wird (unzureichend!)
//Index tempindex(lambda);
//++tempindex;
//cout << "lambda = "<<lambda << " < " << tempindex << " = "<<(lambda<tempindex);
//cout << " #" << lambda.number() <<", #" << tempindex.number()<<endl;
Lambda.insert(lambda);
if (lambda == itend) break;
}
// cout << "- set up stiffness matrix with respect to the index set Lambda=" << endl;
// for (set<Index>::const_iterator it = Lambda.begin(); it != Lambda.end(); ++it)
// cout << *it << endl;
// choose another rhs
#if 1
const unsigned int N = 2;
//myRHS<N> rhs;
//poisson.set_f(&rhs);
eq.set_bvp(&poisson);
eq.RHS(1e-8, coeffs);
cout << "- set up (preconditioned) stiffness matrix..." << endl;
clock_t tstart, tend;
double time;
tstart = clock();
SparseMatrix<double> A;
setup_stiffness_matrix(eq, Lambda, A);
A.compress(1e-15);
// cout << " output in file \"stiff_out.m\"..." << endl;
// std::ofstream ofs("stiff_out.m");
// ofs << "A=";
// print_matrix(A, ofs);
// ofs << ";" << endl;
// ofs.close();
// cout << " ...done!" << endl;
tend = clock();
time = (double)(tend-tstart)/CLOCKS_PER_SEC;
cout << " ... done, time needed: " << time << " seconds" << endl;
// cout << "- (preconditioned) stiffness matrix A=" << endl << A << endl;
cout << "- set up right-hand side..." << endl;
tstart = clock();
Vector<double> b;
setup_righthand_side(eq, Lambda, b);
tend = clock();
time = (double)(tend-tstart)/CLOCKS_PER_SEC;
cout << " ... done, time needed: " << time << " seconds" << endl;
// cout << "- right hand side: " << b << endl;
Vector<double> x(Lambda.size()), err(Lambda.size()); x = 0;
unsigned int iterations;
CG(A, b, x, 1e-8, 100, iterations);
// cout << "- solution coefficients: " << x;
cout << " with residual (infinity) norm ";
A.apply(x, err);
err -= b;
cout << linfty_norm(err) << endl;
#endif
// test normA and normAinv (from cached_tproblem)
cout << "computing norm_Ainv() ..." << endl;
//Index tempindex(problem->basis().last_wavelet(multi_degree(problem->basis().j0())+5));
//cout << "number of last wavelet is "<<tempindex.number()<<endl;
set<Index> Lambda2;
cout << "hier sollte alles gleich aussehen: "<<endl;
cout << first_generator<Basis1D,dim,Basis>(&eq.basis()) << " =? " ;
cout <<( eq.basis().first_generator() )<<endl;
cout << last_wavelet<Basis1D,dim,Basis>(&eq.basis(), multi_degree(eq.basis().j0())+radius) << " =? ";
cout << (eq.basis().last_wavelet(multi_degree(eq.basis().j0())+radius)) << endl;
/*
for (Index lambda ( eq.basis().first_generator() ), itend(eq.basis().last_wavelet(multi_degree(eq.basis().j0())+radius));; ++lambda) {
Lambda2.insert(lambda);
if (lambda == itend) break;
}
SparseMatrix<double> A_Lambda2;
setup_stiffness_matrix(eq, Lambda2, A_Lambda2);
* */
double help, normA;
unsigned int iterations2;
LanczosIteration(A, 1e-6, help, normA, 200, iterations2);
double normAinv ( 1./help);
cout << "normA = "<<normA<<endl;
cout << "normAinv = "<<normAinv<<endl;
cout << "kond = "<<(normA*normAinv)<<endl;
//LanczosIteration(A_Lambda2, 1e-6, help, normA, 200, iterations2);
//normAinv = ( 1./help);
//cout << "normA = "<<normA<<endl;
//cout << "normAinv = "<<normAinv<<endl;
cout << "- point values of the solution:" << endl;
InfiniteVector<double,Index> u;
unsigned int i = 0;
for (set<Index>::const_iterator it = Lambda.begin(); it != Lambda.end(); ++it, ++i)
u.set_coefficient(*it, x[i]);
u.scale(&eq, -1);
// evaluate(eq.basis(), u, true, 6);
SampledMapping<2> s(evaluate(eq.basis(), u, true, 6));
std::ofstream u_Lambda_stream("u_lambda_t.m");
s.matlab_output(u_Lambda_stream);
u_Lambda_stream.close();
cout << " ... done, see file 'u_lambda_t.m'" << endl;
mySolution<N> u_Lambda;
s.add(-1.0, SampledMapping<2>(s, u_Lambda));
std::ofstream u_Lambda_error_stream("u_lambda_t_error.m");
s.matlab_output(u_Lambda_error_stream);
u_Lambda_error_stream.close();
cout << " ... done, see file 'u_lambda_t_error.m', pointwise maximal error: " << maximum_norm(s.values()) << endl;
SampledMapping<2> sexact(s, u_Lambda);
std::ofstream u_exact_stream("u_exact_t.m");
sexact.matlab_output(u_exact_stream);
u_exact_stream.close();
cout << " ... done writing the exact solution to file 'u_exact_t.m'"<<endl;
// SampledMapping<2> srhs(s, rhs);
// std::ofstream rhs_stream("rhs.m");
// srhs.matlab_output(rhs_stream);
// rhs_stream.close();
/*
*/
return 0;
}
| 31.315789 | 173 | 0.607668 | [
"geometry",
"vector"
] |
9048ceb784dbae7bd3f1fb3633d48abdae69d5e8 | 752 | cpp | C++ | src/devices/M5Atom.cpp | miso-develop/opniz-device | 203c019a2088ede9aab79ec69ebe4fd5f857ff9f | [
"MIT"
] | 3 | 2021-03-18T07:23:38.000Z | 2021-09-06T11:37:54.000Z | src/devices/M5Atom.cpp | miso-develop/opniz-device | 203c019a2088ede9aab79ec69ebe4fd5f857ff9f | [
"MIT"
] | null | null | null | src/devices/M5Atom.cpp | miso-develop/opniz-device | 203c019a2088ede9aab79ec69ebe4fd5f857ff9f | [
"MIT"
] | null | null | null | #include "devices/M5Atom.h"
Opniz::M5Atom::M5Atom(const char* address, uint16_t port) : Esp32(address, port) {
name = "m5atom";
addHandler({
new DrawpixHandler
});
addEmitter({
new ButtonEmitter
});
};
String Opniz::M5Atom::DrawpixHandler::handle(JsonArray parameters) {
uint8_t number = (uint8_t)parameters[0];
String color = parameters[1];
M5.dis.drawpix(number, str2crgb(color));
return "true";
}
boolean Opniz::M5Atom::ButtonEmitter::canEmit() {
M5.Btn.read();
return M5.Btn.wasPressed();
}
String Opniz::M5Atom::ButtonEmitter::emit() {
std::vector<String> parameters;
parameters.emplace_back("single-push");
return createMassageJson("button", parameters);
}
| 21.485714 | 82 | 0.655585 | [
"vector"
] |
904d797cd8c3f5405108d8101d633dd5dab78a78 | 292 | cpp | C++ | Cpp/1085.sum-of-digits-in-the-minimum-number.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | 1 | 2015-12-19T23:05:35.000Z | 2015-12-19T23:05:35.000Z | Cpp/1085.sum-of-digits-in-the-minimum-number.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | Cpp/1085.sum-of-digits-in-the-minimum-number.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | class Solution {
public:
int sumOfDigits(vector<int>& A) {
int min_num = INT_MAX;
for (int &a : A) min_num = std::min(min_num, a);
int sum = 0;
for (char c : std::to_string(min_num)) sum += (c - '0');
return sum % 2 == 0;
}
}; | 24.333333 | 64 | 0.476027 | [
"vector"
] |
9053831fd568f1d2bb2d5ebb761374c963506f39 | 4,972 | cpp | C++ | src/caffe/layers/roi_crop_layer.cpp | superxuang/caffe_3d_faster_rcnn | 5a18ab92997885f4b6033ed1f1b9ba907b1e2609 | [
"BSD-2-Clause"
] | 38 | 2018-07-30T07:53:56.000Z | 2022-02-23T13:57:49.000Z | src/caffe/layers/roi_crop_layer.cpp | superxuang/caffe_triple-branch_FCN | e6b3ce2969dc95c55c25921194b93b05513f09ef | [
"MIT"
] | 22 | 2018-07-12T03:33:35.000Z | 2021-09-07T16:29:41.000Z | src/caffe/layers/roi_crop_layer.cpp | Wangdali-jpg/caffe_3d_faster_rcnn | 5a18ab92997885f4b6033ed1f1b9ba907b1e2609 | [
"BSD-2-Clause"
] | 20 | 2019-01-01T07:33:56.000Z | 2021-09-17T12:50:17.000Z | // ------------------------------------------------------------------
// Fast R-CNN
// Copyright (c) 2015 Microsoft
// Licensed under The MIT License [see fast-rcnn/LICENSE for details]
// Written by Ross Girshick
// ------------------------------------------------------------------
#include <cfloat>
#include "caffe/layers/roi_crop_layer.hpp"
using std::max;
using std::min;
using std::floor;
using std::ceil;
namespace caffe {
template <typename Dtype>
void ROICropLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
ROICropParameter roi_crop_param = this->layer_param_.roi_crop_param();
spatial_scale_xy_ = roi_crop_param.spatial_scale_xy();
spatial_scale_z_ = roi_crop_param.spatial_scale_z();
}
template <typename Dtype>
void ROICropLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
num_ = bottom[0]->num();
channels_ = bottom[0]->channels();
length_ = bottom[0]->shape(2);
height_ = bottom[0]->shape(3);
width_ = bottom[0]->shape(4);
Dtype* roi_data = bottom[1]->mutable_cpu_data();
crop_start_w_ = round(roi_data[1] * spatial_scale_xy_);
crop_start_h_ = round(roi_data[2] * spatial_scale_xy_);
crop_start_l_ = round(roi_data[3] * spatial_scale_z_);
int crop_end_w = round(roi_data[4] * spatial_scale_xy_);
int crop_end_h = round(roi_data[5] * spatial_scale_xy_);
int crop_end_l = round(roi_data[6] * spatial_scale_z_);
crop_length_ = max(crop_end_l - crop_start_l_ + 1, 1);
crop_height_ = max(crop_end_h - crop_start_h_ + 1, 2);
crop_width_ = max(crop_end_w - crop_start_w_ + 1, 2);
std::vector<int> top_shape(5);
top_shape[0] = num_;
top_shape[1] = channels_;
top_shape[2] = crop_length_;
top_shape[3] = crop_height_;
top_shape[4] = crop_width_;
top[0]->Reshape(top_shape);
}
template <typename Dtype>
void ROICropLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
Dtype* bottom_data = bottom[0]->mutable_cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
int top_count = top[0]->count();
caffe_set(top_count, Dtype(0), top_data);
for (int n = 0; n < num_; ++n) {
for (int c = 0; c < channels_; ++c) {
std::vector<int> offset_inds(5);
offset_inds[0] = n;
offset_inds[1] = c;
offset_inds[2] = 0;
offset_inds[3] = 0;
offset_inds[4] = 0;
bottom_data = bottom[0]->mutable_cpu_data() + bottom[0]->offset(offset_inds);
top_data = top[0]->mutable_cpu_data() + top[0]->offset(offset_inds);
for (int top_l = 0; top_l < crop_length_; ++top_l) {
for (int top_h = 0; top_h < crop_height_; ++top_h) {
for (int top_w = 0; top_w < crop_width_; ++top_w) {
int bottom_l = top_l + crop_start_l_;
int bottom_h = top_h + crop_start_h_;
int bottom_w = top_w + crop_start_w_;
if (bottom_l >= 0 && bottom_l < length_ &&
bottom_h >= 0 && bottom_h < height_ &&
bottom_w >= 0 && bottom_w < width_) {
const int bottom_index = bottom_l * height_ * width_ + bottom_h * width_ + bottom_w;
const int top_index = top_l * crop_height_ * crop_width_ + top_h * crop_width_ + top_w;
top_data[top_index] = bottom_data[bottom_index];
}
}
}
}
}
}
}
template <typename Dtype>
void ROICropLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
Dtype* top_diff = top[0]->mutable_cpu_diff();
int bottom_count = bottom[0]->count();
caffe_set(bottom_count, Dtype(0), bottom_diff);
for (int n = 0; n < num_; ++n) {
for (int c = 0; c < channels_; ++c) {
std::vector<int> offset_inds(5);
offset_inds[0] = n;
offset_inds[1] = c;
offset_inds[2] = 0;
offset_inds[3] = 0;
offset_inds[4] = 0;
bottom_diff = bottom[0]->mutable_cpu_diff() + bottom[0]->offset(offset_inds);
top_diff = top[0]->mutable_cpu_diff() + top[0]->offset(offset_inds);
for (int top_l = 0; top_l < crop_length_; ++top_l) {
for (int top_h = 0; top_h < crop_height_; ++top_h) {
for (int top_w = 0; top_w < crop_width_; ++top_w) {
int bottom_l = top_l + crop_start_l_;
int bottom_h = top_h + crop_start_h_;
int bottom_w = top_w + crop_start_w_;
if (bottom_l >= 0 && bottom_l < length_ &&
bottom_h >= 0 && bottom_h < height_ &&
bottom_w >= 0 && bottom_w < width_) {
const int bottom_index = bottom_l * height_ * width_ + bottom_h * width_ + bottom_w;
const int top_index = top_l * crop_height_ * crop_width_ + top_h * crop_width_ + top_w;
bottom_diff[bottom_index] = top_diff[top_index];
}
}
}
}
}
}
}
#ifdef CPU_ONLY
STUB_GPU(ROICropLayer);
#endif
INSTANTIATE_CLASS(ROICropLayer);
REGISTER_LAYER_CLASS(ROICrop);
} // namespace caffe
| 34.769231 | 92 | 0.631939 | [
"shape",
"vector"
] |
9059fc82e173eea6c7ea4bfe49b1cc88e6685164 | 32,122 | cpp | C++ | application_sandbox/create_renderpass2/main.cpp | Linux-project/vulkan_test_applications | cc9b2a8075eb69bada9aafc0e6765dbf7e455db1 | [
"Apache-2.0"
] | null | null | null | application_sandbox/create_renderpass2/main.cpp | Linux-project/vulkan_test_applications | cc9b2a8075eb69bada9aafc0e6765dbf7e455db1 | [
"Apache-2.0"
] | null | null | null | application_sandbox/create_renderpass2/main.cpp | Linux-project/vulkan_test_applications | cc9b2a8075eb69bada9aafc0e6765dbf7e455db1 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google 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.
#include "application_sandbox/sample_application_framework/sample_application.h"
#include "support/entry/entry.h"
#include "vulkan_helpers/buffer_frame_data.h"
#include "vulkan_helpers/helper_functions.h"
#include "vulkan_helpers/vulkan_application.h"
#include "vulkan_helpers/vulkan_model.h"
#include <chrono>
#include "mathfu/matrix.h"
#include "mathfu/vector.h"
using Mat44 = mathfu::Matrix<float, 4, 4>;
using Vector4 = mathfu::Vector<float, 4>;
namespace cube_model {
#include "cube.obj.h"
}
const auto& cube_data = cube_model::model;
uint32_t cube_vertex_shader[] =
#include "cube.vert.spv"
;
uint32_t cube_fragment_shader[] =
#include "cube.frag.spv"
;
namespace plane_model {
#include "fullscreen_quad.obj.h"
}
const auto& plane_data = plane_model::model;
uint32_t final_fragment_shader[] =
#include "final.frag.spv"
;
uint32_t passthrough_vertex_shader[] =
#include "passthrough.vert.spv"
;
const VkFormat kDepthStencilFormat = VK_FORMAT_D32_SFLOAT_S8_UINT;
const uint32_t kMultiviewCount = 2;
static VkPhysicalDeviceMultiviewFeatures kMultiviewFeatures{
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES,
nullptr, // pNext
true, // multiview
true, // multiviewGeometryShader
true // multiviewTessellationShader
};
struct MixedSamplesFrameData {
containers::unique_ptr<vulkan::VkCommandBuffer> command_buffer_;
containers::unique_ptr<vulkan::VkFramebuffer> multiview_framebuffer_;
containers::unique_ptr<vulkan::VkFramebuffer> presentation_framebuffer_;
containers::unique_ptr<vulkan::DescriptorSet> cube_descriptor_set_;
containers::unique_ptr<vulkan::DescriptorSet> plane_descriptor_set_;
// The sample application assumes the depth format to VK_FORMAT_D16_UNORM.
// As we need to use stencil aspect, we declare another depth_stencil image
// and its view here.
vulkan::ImagePointer depth_stencil_image_;
vulkan::ImagePointer multiview_image_;
containers::unique_ptr<vulkan::VkImageView> depth_stencil_image_view_;
containers::unique_ptr<vulkan::VkImageView> multiview_image_view_;
};
// This creates an application with 16MB of image memory, and defaults
// for host, and device buffer sizes.
class MixedSamplesSample
: public sample_application::Sample<MixedSamplesFrameData> {
public:
MixedSamplesSample(const entry::EntryData* data)
: data_(data),
Sample<MixedSamplesFrameData>(
data->allocator(), data, 1, 512, 1, 1,
sample_application::SampleOptions().AddDeviceExtensionStructure(
(void*)&kMultiviewFeatures),
{0}, {},
{VK_KHR_MULTIVIEW_EXTENSION_NAME,
VK_KHR_MAINTENANCE2_EXTENSION_NAME,
VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}),
cube_(data->allocator(), data->logger(), cube_data),
plane_(data->allocator(), data->logger(), plane_data) {}
virtual void InitializeApplicationData(
vulkan::VkCommandBuffer* initialization_buffer,
size_t num_swapchain_images) override {
cube_.InitializeData(app(), initialization_buffer);
plane_.InitializeData(app(), initialization_buffer);
// Initialization for cube and floor rendering. Cube and floor shares the
// same transformation matrix, so they shares the same descriptor sets for
// vertex shader and pipeline layout. However, the fragment shaders are
// different, so two different pipelines are required.
descriptor_set_layouts_[0] = {
0, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // stageFlags
nullptr // pImmutableSamplers
};
descriptor_set_layouts_[1] = {
1, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // stageFlags
nullptr // pImmutableSamplers
};
descriptor_set_layouts_[2] = {
2, // binding
VK_DESCRIPTOR_TYPE_SAMPLER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_FRAGMENT_BIT, // stageFlags
nullptr // pImmutableSamplers
};
descriptor_set_layouts_[3] = {
3, // binding
VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_FRAGMENT_BIT, // stageFlags
nullptr // pImmutableSamplers
};
sampler_ = containers::make_unique<vulkan::VkSampler>(
data_->allocator(),
vulkan::CreateSampler(&app()->device(), VK_FILTER_LINEAR,
VK_FILTER_LINEAR));
cube_pipeline_layout_ = containers::make_unique<vulkan::PipelineLayout>(
data_->allocator(),
app()->CreatePipelineLayout(
{{descriptor_set_layouts_[0], descriptor_set_layouts_[1]}}));
plane_pipeline_layout_ = containers::make_unique<vulkan::PipelineLayout>(
data_->allocator(),
app()->CreatePipelineLayout(
{{descriptor_set_layouts_[2], descriptor_set_layouts_[3]}}));
VkAttachmentReference2KHR color_attachment = {
VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR, // sType
nullptr, // pNext
0, // attachment
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // layout
VK_IMAGE_ASPECT_COLOR_BIT // aspectMask
};
VkAttachmentReference2KHR depth_attachment = {
VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR, // sType
nullptr, // pNext
1, // attachment
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, // layout
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT // aspectMask
};
VkAttachmentDescription2KHR color_attachment_description{
VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
render_format(), // format
num_color_samples(), // samples
VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp
VK_ATTACHMENT_STORE_OP_STORE, // storeOp
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stencilLoadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // stencilStoreOp
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // finalLayout
};
VkAttachmentDescription2KHR depth_stencil_attachment_description{
VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
kDepthStencilFormat, // format
num_depth_stencil_samples(), // samples
VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp
VK_ATTACHMENT_STORE_OP_STORE, // storeOp
VK_ATTACHMENT_LOAD_OP_CLEAR, // stencilLoadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // stencilStoreOp
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // finalLayout
};
const uint32_t view_mask = 0b00000011;
const uint32_t correlation_mask = 0b00000011;
VkViewport multiview_viewport = viewport();
multiview_viewport.width = multiview_viewport.width / 2;
VkRect2D multiview_scissor = scissor();
multiview_scissor.extent.width = multiview_scissor.extent.width / 2;
multiview_render_pass_ = containers::make_unique<vulkan::VkRenderPass>(
data_->allocator(),
app()->CreateRenderPass2(
{color_attachment_description,
depth_stencil_attachment_description}, // AttachmentDescriptions
{{
VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint
view_mask, // viewMask
0, // inputAttachmentCount
nullptr, // pInputAttachments
1, // colorAttachmentCount
&color_attachment, // colorAttachment
nullptr, // pResolveAttachments
&depth_attachment, // pDepthStencilAttachment
0, // preserveAttachmentCount
nullptr // pPreserveAttachments
}}, // SubpassDescriptions
{}, // SubpassDependencies
1, // correlatedViewMaskCount
&correlation_mask // pCorrelatedViewMasks
));
presentation_render_pass_ = containers::make_unique<vulkan::VkRenderPass>(
data_->allocator(),
app()->CreateRenderPass2(
{color_attachment_description}, // AttachmentDescriptions
{{
VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, // sType
nullptr, // pNext
0, // flags
VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint
0, // viewMask
0, // inputAttachmentCount
nullptr, // pInputAttachments
1, // colorAttachmentCount
&color_attachment, // colorAttachment
nullptr, // pResolveAttachments
nullptr, // pDepthStencilAttachment
0, // preserveAttachmentCount
nullptr // pPreserveAttachments
}}, // SubpassDescriptions
{}, // SubpassDependencies
0, // correlatedViewMaskCount
nullptr // pCorrelatedViewMasks
));
for (uint32_t i = 0; i < kMultiviewCount; ++i) {
multiview_viewport.x = multiview_viewport.width * i;
multiview_scissor.offset.x = multiview_scissor.extent.width * i;
// Initialize cube shaders
cube_pipelines_[i] =
containers::make_unique<vulkan::VulkanGraphicsPipeline>(
data_->allocator(),
app()->CreateGraphicsPipeline(cube_pipeline_layout_.get(),
multiview_render_pass_.get(), 0));
cube_pipelines_[i]->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main",
cube_vertex_shader);
cube_pipelines_[i]->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main",
cube_fragment_shader);
cube_pipelines_[i]->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
cube_pipelines_[i]->SetInputStreams(&cube_);
cube_pipelines_[i]->SetViewport(multiview_viewport);
cube_pipelines_[i]->SetScissor(multiview_scissor);
cube_pipelines_[i]->SetSamples(num_samples());
cube_pipelines_[i]->AddAttachment();
cube_pipelines_[i]->Commit();
}
plane_pipeline_ = containers::make_unique<vulkan::VulkanGraphicsPipeline>(
data_->allocator(),
app()->CreateGraphicsPipeline(plane_pipeline_layout_.get(),
presentation_render_pass_.get(), 0));
plane_pipeline_->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main",
passthrough_vertex_shader);
plane_pipeline_->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main",
final_fragment_shader);
plane_pipeline_->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
plane_pipeline_->SetInputStreams(&cube_);
plane_pipeline_->SetViewport(viewport());
plane_pipeline_->SetScissor(scissor());
plane_pipeline_->SetSamples(num_samples());
plane_pipeline_->AddAttachment();
plane_pipeline_->Commit();
// Transformation data for viewing and cube/floor rotation.
camera_data_ = containers::make_unique<vulkan::BufferFrameData<CameraData>>(
data_->allocator(), app(), num_swapchain_images,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
model_data_ = containers::make_unique<vulkan::BufferFrameData<ModelData>>(
data_->allocator(), app(), num_swapchain_images,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
float aspect = ((float)app()->swapchain().width() / 2.0f) /
(float)app()->swapchain().height();
camera_data_->data().projection_matrix =
Mat44::FromScaleVector(mathfu::Vector<float, 3>{1.0f, -1.0f, 1.0f}) *
Mat44::Perspective(1.5708f, aspect, 0.1f, 100.0f);
model_data_->data().transform =
Mat44::FromTranslationVector(
mathfu::Vector<float, 3>{0.0f, 0.0f, -3.0f}) *
Mat44::FromRotationMatrix(Mat44::RotationX(3.14f * 0.2f));
}
virtual void InitializeFrameData(
MixedSamplesFrameData* frame_data,
vulkan::VkCommandBuffer* initialization_buffer,
size_t frame_index) override {
// Initalize the depth stencil image and the image view.
VkImageCreateInfo depth_stencil_image_create_info = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
VK_IMAGE_TYPE_2D, // imageType
kDepthStencilFormat, // format
{app()->swapchain().width(), app()->swapchain().height(),
app()->swapchain().depth()}, // extent
1, // mipLevels
kMultiviewCount, // arrayLayers
num_depth_stencil_samples(), // samples
VK_IMAGE_TILING_OPTIMAL, // tiling
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, // usage
VK_SHARING_MODE_EXCLUSIVE, // sharingMode
0, // queueFamilyIndexCount
nullptr, // pQueueFamilyIndices
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
};
frame_data->depth_stencil_image_ =
app()->CreateAndBindImage(&depth_stencil_image_create_info);
frame_data->depth_stencil_image_view_ = app()->CreateImageView(
frame_data->depth_stencil_image_.get(), VK_IMAGE_VIEW_TYPE_2D,
{VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0,
kMultiviewCount});
// Initialize the descriptor sets
frame_data->cube_descriptor_set_ =
containers::make_unique<vulkan::DescriptorSet>(
data_->allocator(),
app()->AllocateDescriptorSet(
{descriptor_set_layouts_[0], descriptor_set_layouts_[1]}));
VkDescriptorBufferInfo buffer_infos[2] = {
{
camera_data_->get_buffer(), // buffer
camera_data_->get_offset_for_frame(frame_index), // offset
camera_data_->size(), // range
},
{
model_data_->get_buffer(), // buffer
model_data_->get_offset_for_frame(frame_index), // offset
model_data_->size(), // range
}};
VkWriteDescriptorSet cube_write{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // sType
nullptr, // pNext
*frame_data->cube_descriptor_set_, // dstSet
0, // dstbinding
0, // dstArrayElement
2, // descriptorCount
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
nullptr, // pImageInfo
buffer_infos, // pBufferInfo
nullptr, // pTexelBufferView
};
app()->device()->vkUpdateDescriptorSets(app()->device(), 1, &cube_write, 0,
nullptr);
VkImageCreateInfo swapchain_image_create_info = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
VK_IMAGE_TYPE_2D, // imageType
app()->swapchain().format(), // format
{app()->swapchain().width(), app()->swapchain().height(),
app()->swapchain().depth()}, // extent
1, // mipLevels
kMultiviewCount, // arrayLayers
num_color_samples(), // samples
VK_IMAGE_TILING_OPTIMAL, // tiling
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
VK_IMAGE_USAGE_SAMPLED_BIT, // usage
VK_SHARING_MODE_EXCLUSIVE, // sharingMode
0, // queueFamilyIndexCount
nullptr, // pQueueFamilyIndices
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
};
frame_data->multiview_image_ =
app()->CreateAndBindImage(&swapchain_image_create_info);
frame_data->multiview_image_view_ = app()->CreateImageView(
frame_data->multiview_image_.get(), VK_IMAGE_VIEW_TYPE_2D,
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, kMultiviewCount});
::VkImageView multiview_raw_views[2] = {
*frame_data->multiview_image_view_,
*frame_data->depth_stencil_image_view_};
// Create a framebuffer with depth and image attachments
VkFramebufferCreateInfo multiview_framebuffer_create_info{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
*multiview_render_pass_, // renderPass
2, // attachmentCount
multiview_raw_views, // attachments
app()->swapchain().width(), // width
app()->swapchain().height(), // height
kMultiviewCount // layers
};
::VkFramebuffer multiview_raw_framebuffer;
app()->device()->vkCreateFramebuffer(app()->device(),
&multiview_framebuffer_create_info,
nullptr, &multiview_raw_framebuffer);
frame_data->multiview_framebuffer_ =
containers::make_unique<vulkan::VkFramebuffer>(
data_->allocator(),
vulkan::VkFramebuffer(multiview_raw_framebuffer, nullptr,
&app()->device()));
frame_data->plane_descriptor_set_ =
containers::make_unique<vulkan::DescriptorSet>(
data_->allocator(),
app()->AllocateDescriptorSet(
{descriptor_set_layouts_[2], descriptor_set_layouts_[3]}));
VkDescriptorImageInfo sampler_info = {
*sampler_, // sampler
VK_NULL_HANDLE, // imageView
VK_IMAGE_LAYOUT_UNDEFINED // imageLayout
};
VkDescriptorImageInfo texture_info = {
VK_NULL_HANDLE, // sampler
*frame_data->multiview_image_view_.get(), // imageView
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, // imageLayout
};
VkWriteDescriptorSet plane_writes[2]{
{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // sType
nullptr, // pNext
*frame_data->plane_descriptor_set_, // dstSet
2, // dstbinding
0, // dstArrayElement
1, // descriptorCount
VK_DESCRIPTOR_TYPE_SAMPLER, // descriptorType
&sampler_info, // pImageInfo
nullptr, // pBufferInfo
nullptr, // pTexelBufferView
},
{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // sType
nullptr, // pNext
*frame_data->plane_descriptor_set_, // dstSet
3, // dstbinding
0, // dstArrayElement
1, // descriptorCount
VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, // descriptorType
&texture_info, // pImageInfo
nullptr, // pBufferInfo
nullptr, // pTexelBufferView
}};
app()->device()->vkUpdateDescriptorSets(app()->device(), 2, plane_writes, 0,
nullptr);
::VkImageView presentation_raw_view = color_view(frame_data);
// Create a framebuffer with depth and image attachments
VkFramebufferCreateInfo presentation_framebuffer_create_info{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
*presentation_render_pass_, // renderPass
1, // attachmentCount
&presentation_raw_view, // attachments
app()->swapchain().width(), // width
app()->swapchain().height(), // height
1 // layers
};
::VkFramebuffer presentation_raw_framebuffer;
app()->device()->vkCreateFramebuffer(
app()->device(), &presentation_framebuffer_create_info, nullptr,
&presentation_raw_framebuffer);
frame_data->presentation_framebuffer_ =
containers::make_unique<vulkan::VkFramebuffer>(
data_->allocator(),
vulkan::VkFramebuffer(presentation_raw_framebuffer, nullptr,
&app()->device()));
// Populate the render command buffer
frame_data->command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
data_->allocator(), app()->GetCommandBuffer());
(*frame_data->command_buffer_)
->vkBeginCommandBuffer((*frame_data->command_buffer_),
&sample_application::kBeginCommandBuffer);
vulkan::VkCommandBuffer& cmdBuffer = (*frame_data->command_buffer_);
VkClearValue clears[2];
clears[0].color = {0.0f, 0.0f, 0.0f, 0.0f};
clears[1].depthStencil = {1.0f, 0};
VkRenderPassBeginInfo multiview_pass_begin = {
VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, // sType
nullptr, // pNext
*multiview_render_pass_, // renderPass
*frame_data->multiview_framebuffer_, // framebuffer
{{0, 0},
{app()->swapchain().width(),
app()->swapchain().height()}}, // renderArea
2, // clearValueCount
clears // clears
};
cmdBuffer->vkCmdBeginRenderPass(cmdBuffer, &multiview_pass_begin,
VK_SUBPASS_CONTENTS_INLINE);
cmdBuffer->vkCmdBindDescriptorSets(
cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
::VkPipelineLayout(*cube_pipeline_layout_), 0, 1,
&frame_data->cube_descriptor_set_->raw_set(), 0, nullptr);
for (uint32_t i = 0; i < kMultiviewCount; ++i) {
// Draw the cube
cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
*cube_pipelines_[i]);
cube_.Draw(&cmdBuffer);
}
cmdBuffer->vkCmdEndRenderPass(cmdBuffer);
VkImageMemoryBarrier barrier1{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // srcAccessMask
VK_ACCESS_SHADER_READ_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // oldLayout
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
*frame_data->multiview_image_, // image
{
VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask;
0, // baseMipLevel;
1, // levelCount;
0, // baseArrayLayer;
kMultiviewCount // layerCount;
} // subresourceRange;
};
cmdBuffer->vkCmdPipelineBarrier(
cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1,
&barrier1);
VkRenderPassBeginInfo presentation_pass_begin = {
VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, // sType
nullptr, // pNext
*presentation_render_pass_, // renderPass
*frame_data->presentation_framebuffer_, // framebuffer
{{0, 0},
{app()->swapchain().width(),
app()->swapchain().height()}}, // renderArea
1, // clearValueCount
clears // clears
};
cmdBuffer->vkCmdBeginRenderPass(cmdBuffer, &presentation_pass_begin,
VK_SUBPASS_CONTENTS_INLINE);
cmdBuffer->vkCmdBindDescriptorSets(
cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
::VkPipelineLayout(*plane_pipeline_layout_), 0, 1,
&frame_data->plane_descriptor_set_->raw_set(), 0, nullptr);
// Draw the plane
cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
*plane_pipeline_);
plane_.Draw(&cmdBuffer);
cmdBuffer->vkCmdEndRenderPass(cmdBuffer);
VkImageMemoryBarrier barrier2{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
VK_ACCESS_SHADER_READ_BIT, // srcAccessMask
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, // oldLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
*frame_data->multiview_image_, // image
{
VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask;
0, // baseMipLevel;
1, // levelCount;
0, // baseArrayLayer;
kMultiviewCount // layerCount;
} // subresourceRange;
};
cmdBuffer->vkCmdPipelineBarrier(
cmdBuffer, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0,
nullptr, 1, &barrier2);
(*frame_data->command_buffer_)
->vkEndCommandBuffer(*frame_data->command_buffer_);
}
virtual void Update(float time_since_last_render) override {
model_data_->data().transform = model_data_->data().transform *
Mat44::FromRotationMatrix(Mat44::RotationY(
3.14f * time_since_last_render * 0.5f));
}
virtual void Render(vulkan::VkQueue* queue, size_t frame_index,
MixedSamplesFrameData* frame_data) override {
// Update our uniform buffers.
camera_data_->UpdateBuffer(queue, frame_index);
model_data_->UpdateBuffer(queue, frame_index);
VkSubmitInfo init_submit_info{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
0, // waitSemaphoreCount
nullptr, // pWaitSemaphores
nullptr, // pWaitDstStageMask,
1, // commandBufferCount
&(frame_data->command_buffer_->get_command_buffer()),
0, // signalSemaphoreCount
nullptr // pSignalSemaphores
};
app()->render_queue()->vkQueueSubmit(app()->render_queue(), 1,
&init_submit_info,
static_cast<VkFence>(VK_NULL_HANDLE));
}
private:
struct CameraData {
Mat44 projection_matrix;
};
struct ModelData {
Mat44 transform;
};
const entry::EntryData* data_;
containers::unique_ptr<vulkan::PipelineLayout> cube_pipeline_layout_;
containers::unique_ptr<vulkan::PipelineLayout> plane_pipeline_layout_;
containers::unique_ptr<vulkan::VulkanGraphicsPipeline>
cube_pipelines_[kMultiviewCount];
containers::unique_ptr<vulkan::VulkanGraphicsPipeline> plane_pipeline_;
containers::unique_ptr<vulkan::VkRenderPass> multiview_render_pass_;
containers::unique_ptr<vulkan::VkRenderPass> presentation_render_pass_;
VkDescriptorSetLayoutBinding descriptor_set_layouts_[4];
vulkan::VulkanModel cube_;
vulkan::VulkanModel plane_;
containers::unique_ptr<vulkan::VkSampler> sampler_;
containers::unique_ptr<vulkan::BufferFrameData<CameraData>> camera_data_;
containers::unique_ptr<vulkan::BufferFrameData<ModelData>> model_data_;
};
int main_entry(const entry::EntryData* data) {
data->logger()->LogInfo("Application Startup");
MixedSamplesSample sample(data);
sample.Initialize();
while (!sample.should_exit() && !data->WindowClosing()) {
sample.ProcessFrame();
}
sample.WaitIdle();
data->logger()->LogInfo("Application Shutdown");
return 0;
}
| 46.553623 | 80 | 0.562294 | [
"render",
"vector",
"model",
"transform"
] |
905c39bff46f0f4bfdde027388522cc79698366f | 469 | hpp | C++ | demos/Asteroids/src/PlayerText.hpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | 2 | 2021-01-20T11:31:44.000Z | 2022-01-11T01:38:01.000Z | demos/Asteroids/src/PlayerText.hpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | null | null | null | demos/Asteroids/src/PlayerText.hpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | null | null | null | #pragma once
//SELF
#include "CustomData.hpp"
//LIBS
#include <Enki/Entity.hpp>
class PlayerText : public enki::Entity
{
public:
PlayerText(enki::EntityInfo info, CustomData* custom_data);
void onSpawn(enki::Packet p) final;
void update(float dt) final;
void draw(enki::Renderer* renderer) final;
std::vector<std::pair<std::string, std::string>> serializeToStrings() const final;
private:
CustomData* const custom_data;
std::unique_ptr<enki::Text> label;
}; | 21.318182 | 83 | 0.739872 | [
"vector"
] |
906234a122aed17e7a5fef3ec7c127e9db4c3958 | 9,976 | hpp | C++ | hex/cholmod/hala_cholmod.hpp | LIBHALA/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 1 | 2021-02-25T16:21:42.000Z | 2021-02-25T16:21:42.000Z | hex/cholmod/hala_cholmod.hpp | mkstoyanov/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 9 | 2020-09-03T23:31:22.000Z | 2020-10-21T23:40:11.000Z | hex/cholmod/hala_cholmod.hpp | mkstoyanov/hala | ff3950aef18b6cede48b45669be275b174f362a5 | [
"BSD-3-Clause"
] | 2 | 2020-03-03T17:39:37.000Z | 2020-11-05T16:01:28.000Z | #ifndef __HALA_CHOLMOD_WRAPPERS_HPP
#define __HALA_CHOLMOD_WRAPPERS_HPP
/*
* Code Author: Miroslav Stoyanov
*
* Copyright (C) 2018 Miroslav Stoyanov
*
* This file is part of
* Hardware Accelerated Linear Algebra (HALA)
*
*/
/*!
* \file hala_cholmod.hpp
* \brief HALA wrapper for Cholmod functions
* \author Miroslav Stoyanov
* \copyright BSD-3-Clause
* \ingroup HALACHOLMOD
*
* Contains the HALA-Cholmod wrapper template.
*/
/*!
* \defgroup HALACHOLMOD HALA Cholmod Wrapper Templates
*
* Cholmod wrapper templates allow easy integration between
* C++ containers and the direct sparse solver capabilities of
* the cholmod library.
*/
#define HALA_ENABLE_CHOLMOD
#include "hala_cholmod_defines.hpp"
namespace hala{
/*!
* \ingroup HALACHOLMOD
* \brief Wrapper around a factorization of a sparse matrix using the Cholmod library.
*
* Handle the background memory management, but unfortunately requires that data is copied unnecessarily.
* A copy of the sparse matrix is needed for factorization and the copy is preserved (in the non-spd matrix).
* A copy of each right-hand-side vector is also needed to solve any type of system.
* Nevertheless, the performance of the Cholmod library compensates for this relatively small overhead.
*/
template<typename T = double> // Cholmod only works with double precision and complex numbers
class cholmod_factor{
public:
//! \brief Default constructor, makes an empty factor.
cholmod_factor() : num_rows(0), chol_sparse(nullptr), chol_factor(nullptr), spd(false){}
//! \brief Construct a factor and factorize either symmetric-positive-definite or general matrix.
template<typename VectorLikeP, typename VectorLikeI, typename VectorLikeV>
cholmod_factor(bool is_spd, VectorLikeP const &pntr, VectorLikeI const &indx, VectorLikeV const &vals)
: cholmod_factor(){
static_assert(std::is_same<get_scalar_type<VectorLikeV>, double>::value, "Cholmod works only with double-precision real numbers.");
check_types_int(pntr, indx);
num_rows = get_size_int(pntr) - 1;
assert(num_rows > 0); // there is at least 1 row
chol_common.resize(3 * 1024); // guess the size of the common block
cholmod_start(convert(chol_common));
if (is_spd){
factorise_spd(pntr, indx, vals);
}else{
factorise_gen(pntr, indx, vals);
}
}
//! \brief Default destructor.
~cholmod_factor(){
if (chol_sparse != nullptr){
cholmod_free_sparse(pconvert(&chol_sparse), convert(chol_common));
chol_sparse = nullptr;
}
if (chol_factor != nullptr){
cholmod_free_factor(pconvert(&chol_factor), convert(chol_common));
chol_factor = nullptr;
}
cholmod_finish(convert(chol_common));
}
//! \brief Class cholmod_factor cannot be copied.
cholmod_factor(cholmod_factor<T> const &) = delete;
//! \brief Class cholmod_factor cannot be copied.
cholmod_factor<T>& operator = (cholmod_factor<T> const &) = delete;
//! \brief Move constructor.
cholmod_factor(cholmod_factor<T> &&) = default;
//! \brief Move assignment.
cholmod_factor<T>& operator = (cholmod_factor<T> &&) = default;
//! \brief Solve \f$ A x = b \f$ using the existing factorization, must be preceded by a call to **factoriseSPD()** or **factoriseGeneral()**
template<typename VectorLikeB, typename VectorLikeX>
void solve(VectorLikeB const &b, VectorLikeX &x){
check_size(b, num_rows);
check_set_size(assume_output, x, num_rows);
check_types(x, b);
static_assert(std::is_same<get_scalar_type<VectorLikeX>, T>::value, "cholmod_factor<T>::solve() can be called only with vectors with scalar type T");
auto chol_b = make_cholmod_dense(b);
if (spd){
make_cholmod_dense( cholmod_solve(solve_all, pconvert(chol_factor), chol_b, convert(chol_common)) ).put(x);
}else{
T alpha[2] = {1.0, 0.0}, beta[2] = {0.0, 0.0};
auto chol_z = make_cholmod_dense(num_rows);
cholmod_sdmult(pconvert(chol_sparse), non_tansp, pconvert(alpha), pconvert(beta), chol_b, chol_z, convert(chol_common));
make_cholmod_dense( cholmod_solve(solve_all, pconvert(chol_factor), chol_z, convert(chol_common)) ).put(x);
}
}
//! \brief Cholmod definition of real (i.e., double).
static constexpr int real = 1;
//! \brief Cholmod definition of symmetric.
static constexpr int symmetric = -1;
//! \brief Cholmod definition of general.
static constexpr int general = 0;
//! \brief Cholmod definition of solve all parts of the factorization.
static constexpr int solve_all = 0;
//! \brief Cholmod definition of multiply by non-transpose of a matrix.
static constexpr int non_tansp = 0;
protected:
/*!
* \internal
* \brief RAII management of Cholmod dense vectors.
*
* \endinternal
*/
class chol_dense_vector{
public:
//! \brief Make empty vector of size \b nrows.
chol_dense_vector(int nrows, std::vector<char>&h)
: handler(h), _data(cholmod_allocate_dense(nrows, 1, nrows, real, convert(handler))){}
//! \brief Copy \b x into a cholmod dense vector.
template<class VectorLike>
chol_dense_vector(VectorLike const &x, std::vector<char>&h)
: chol_dense_vector(get_size_int(x), h){
std::copy_n(get_data(x), get_size(x), cheat_cholmod::get_dense_x<T>(_data));
}
//! \brief Assume control of a cholmod dense vector (when returned from a solve call).
chol_dense_vector(void *data, std::vector<char> &h) : handler(h), _data(data){}
//! \brief Destrucor, deletes all memory.
~chol_dense_vector(){ cholmod_free_dense(&_data, convert(handler)); }
//! \brief Copy the cholmod dense vector into \b x, note that \b x \b must \b have \b correct \b size.
template<class VectorLike>
void put(VectorLike &x){
std::copy_n(cheat_cholmod::get_dense_x<T>(_data), get_size(x), get_data(x));
}
//! \brief Handle to easily pass to functions.
template<typename U> operator U* (){ return reinterpret_cast<U*>(_data); }
private:
std::vector<char> &handler;
void *_data;
};
//! \brief Creates a new dense vector and passes the chol_common.
auto make_cholmod_dense(int nrows){ return chol_dense_vector(nrows, chol_common); }
//! \brief Assumes control of the dense vector and passes the chol_common.
auto make_cholmod_dense(void *x){ return chol_dense_vector(x, chol_common); }
//! \brief Copies \b x into the dense vector and passes the chol_common.
template<class VectorLike>
auto make_cholmod_dense(VectorLike const &x){ return chol_dense_vector(x, chol_common); }
//! \brief Copies the sparse matrix into the \b chol_sparse data structure.
template<int mat_type, typename VectorLikeP, typename VectorLikeI, typename VectorLikeV>
void set_sparse(VectorLikeP const &pntr, VectorLikeI const &indx, VectorLikeV const &vals){
check_types_int(pntr, indx);
int num_nnz = pntr[num_rows];
chol_sparse = (void*) cholmod_allocate_sparse(num_rows, num_rows, num_nnz, 1, 1, mat_type, real, convert(chol_common)); // last 1 is CHOLMOD_REAL
std::copy_n(get_data(pntr), get_size(pntr), cheat_cholmod::get_sparse_pntr(chol_sparse));
std::copy_n(get_data(indx), num_nnz, cheat_cholmod::get_sparse_indx(chol_sparse));
std::copy_n(get_data(vals), num_nnz, cheat_cholmod::get_sparse_vals<T>(chol_sparse));
}
//! \brief Factorize a symmetric-positive-define matrix.
template<typename VectorLikeP, typename VectorLikeI, typename VectorLikeV>
void factorise_spd(VectorLikeP const &pntr, VectorLikeI const &indx, VectorLikeV const &vals){
std::vector<int> upper_pntr, lower_pntr, upper_indx, lower_indx;
std::vector<T> upper_vals, lower_vals;
split_matrix('U', 'N', pntr, indx, vals, upper_pntr, upper_indx, upper_vals, lower_pntr, lower_indx, lower_vals);
set_sparse<symmetric>(upper_pntr, upper_indx, upper_vals);
chol_factor = cholmod_analyze(pconvert(chol_sparse), convert(chol_common));
cholmod_factorize(pconvert(chol_sparse), pconvert(chol_factor), convert(chol_common));
cholmod_free_sparse(pconvert(&chol_sparse), convert(chol_common));
chol_sparse = nullptr;
spd = true;
}
//! \brief Factorize a general matrix.
template<typename VectorLikeP, typename VectorLikeI, typename VectorLikeV>
void factorise_gen(VectorLikeP const &pntr, VectorLikeI const &indx, VectorLikeV const &vals){
set_sparse<general>(pntr, indx, vals);
chol_factor = cholmod_analyze(pconvert(chol_sparse), convert(chol_common));
cholmod_factorize(pconvert(chol_sparse), pconvert(chol_factor), convert(chol_common));
spd = false;
}
private:
int num_rows;
void *chol_sparse, *chol_factor;
std::vector<char> chol_common;
bool spd;
};
/*!
* \ingroup HALACHOLMOD
* \brief Factorize the symmetric positive definite sparse matrix and return appropriate \b hala::cholmod_factor.
*
*/
template<typename VectorLikeP, typename VectorLikeI, typename VectorLikeV>
auto cholmod_factorize_spd(VectorLikeP const &pntr, VectorLikeI const &indx, VectorLikeV const &vals){
return cholmod_factor<get_scalar_type<VectorLikeV>>(true, pntr, indx, vals);
}
/*!
* \ingroup HALACHOLMOD
* \brief Factorize the general sparse matrix and return appropriate \b hala::cholmod_factor.
*
*/
template<typename VectorLikeP, typename VectorLikeI, typename VectorLikeV>
auto cholmod_factorize_gen(VectorLikeP const &pntr, VectorLikeI const &indx, VectorLikeV const &vals){
return cholmod_factor<get_scalar_type<VectorLikeV>>(false, pntr, indx, vals);
}
}
#endif
| 41.22314 | 157 | 0.692562 | [
"vector"
] |
906eab4dce0fee24918d8afe97d6caae5be124a1 | 3,933 | cpp | C++ | src/Planners/ThetaStarGeneratorSafetyCost.cpp | RafaelRey/3D_heuristic_path_planners | e23a286a730485db4c87b0ae3168d008699f9df8 | [
"MIT"
] | 20 | 2021-06-30T09:41:37.000Z | 2022-03-30T05:52:47.000Z | src/Planners/ThetaStarGeneratorSafetyCost.cpp | RafaelRey/3D_heuristic_path_planners | e23a286a730485db4c87b0ae3168d008699f9df8 | [
"MIT"
] | 3 | 2021-06-30T09:29:35.000Z | 2021-09-26T18:40:49.000Z | src/Planners/ThetaStarGeneratorSafetyCost.cpp | robotics-upo/3D_heuristic_path_planners | e23a286a730485db4c87b0ae3168d008699f9df8 | [
"MIT"
] | 2 | 2022-03-11T14:22:06.000Z | 2022-03-30T05:52:50.000Z | #include "Planners/ThetaStarGeneratorSafetyCost.hpp"
namespace Planners
{
ThetaStarGeneratorSafetyCost::ThetaStarGeneratorSafetyCost(bool _use_3d):ThetaStarGenerator(_use_3d, "thetastarsafetycost") {}
ThetaStarGeneratorSafetyCost::ThetaStarGeneratorSafetyCost(bool _use_3d, std::string _name = "thetastarsafetycost" ):ThetaStarGenerator(_use_3d, _name) {}
inline void ThetaStarGeneratorSafetyCost::ComputeCost(Node *_s_aux, Node *_s2_aux)
{
line_of_sight_checks_++;
if (LineOfSight::bresenham3D(_s_aux->parent, _s2_aux, discrete_world_, checked_nodes))
{
auto dist2 = geometry::distanceBetween2Nodes(_s_aux->parent, _s2_aux);
auto edge2 = ComputeEdgeCost(checked_nodes, _s_aux->parent, _s2_aux);
line_of_sight_checks_++;
LineOfSight::bresenham3D(_s_aux, _s2_aux, discrete_world_, checked_nodes_current);
auto dist1 = geometry::distanceBetween2Nodes(_s_aux, _s2_aux);
auto edge1 = ComputeEdgeCost(checked_nodes_current, _s_aux, _s2_aux);
if ( ( _s_aux->parent->G + dist2 + edge2 ) < ( _s_aux->G + dist1 + edge1))
{
_s2_aux->parent = _s_aux->parent;
_s2_aux->G = _s_aux->parent->G + dist2 + edge2; // This is the same than A*
_s2_aux->gplush = _s2_aux->G + _s2_aux->H;
_s2_aux->C = edge2;
}
else{
_s2_aux->parent =_s_aux;
_s2_aux->G = _s_aux->G + dist1 + edge1; // This is the same than A*
_s2_aux->gplush = _s2_aux->G + _s2_aux->H;
_s2_aux->C = edge1;
}
} else {
_s2_aux->parent=_s_aux;
line_of_sight_checks_++;
LineOfSight::bresenham3D(_s_aux, _s2_aux, discrete_world_, checked_nodes);
auto dist1 = geometry::distanceBetween2Nodes(_s_aux, _s2_aux);
auto edge1 = ComputeEdgeCost(checked_nodes, _s_aux, _s2_aux);
_s2_aux->G = _s_aux->G + dist1 + edge1; // This is the same than A*
_s2_aux->gplush = _s2_aux->G + _s2_aux->H;
_s2_aux->C = edge1;
}
checked_nodes->clear();
checked_nodes_current->clear();
}
inline unsigned int ThetaStarGeneratorSafetyCost::ComputeEdgeCost(const utils::CoordinateListPtr _checked_nodes, const Node* _s, const Node* _s2){
double dist_cost{0};
double mean_dist_cost{0};
auto n_checked_nodes = _checked_nodes->size();
if( n_checked_nodes >= 1 )
for(auto &it: *_checked_nodes)
dist_cost += discrete_world_.getNodePtr(it)->cost;
if( n_checked_nodes > 1){
mean_dist_cost = (( _s->cost - _s2->cost ) / 2) + dist_cost;
}
else if (n_checked_nodes == 1){
mean_dist_cost = (( _s->cost + _s2->cost ) / 2) + dist_cost;
}
else{
mean_dist_cost = (( _s->cost + _s2->cost ) / 2);
}
return static_cast<unsigned int>( mean_dist_cost * cost_weight_ * dist_scale_factor_reduced_);
}
inline unsigned int ThetaStarGeneratorSafetyCost::computeG(const Node* _current, Node* _suc, unsigned int _n_i, unsigned int _dirs){
unsigned int cost = 0;
if(_dirs == 8){
cost += (_n_i < 4 ? dist_scale_factor_ : dd_2D_); //This is more efficient
}else{
cost += (_n_i < 6 ? dist_scale_factor_ : (_n_i < 18 ? dd_2D_ : dd_3D_)); //This is more efficient
}
double cc = (_current->cost + _suc->cost) / 2;
auto edge_neighbour = static_cast<unsigned int>( cc * cost_weight_ * dist_scale_factor_reduced_);
cost += _current->G;
cost += edge_neighbour;
_suc->C = edge_neighbour;
return cost;
}
}
| 40.132653 | 158 | 0.587338 | [
"geometry"
] |
9070d7667fd831a4383b59e279358c247fe69a71 | 7,842 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/bindings/js/JSDictionary.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2021-02-09T10:24:31.000Z | 2021-02-09T10:24:31.000Z | src/qt/qtwebkit/Source/WebCore/bindings/js/JSDictionary.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/bindings/js/JSDictionary.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "JSDictionary.h"
#include "ArrayValue.h"
#include "Dictionary.h"
#include "JSCSSFontFaceRule.h"
#include "JSDOMError.h"
#include "JSDOMWindow.h"
#include "JSEventTarget.h"
#include "JSMessagePortCustom.h"
#include "JSNode.h"
#include "JSStorage.h"
#include "JSTrackCustom.h"
#include "JSUint8Array.h"
#include "JSVoidCallback.h"
#include "ScriptValue.h"
#include "SerializedScriptValue.h"
#include <wtf/HashMap.h>
#include <wtf/MathExtras.h>
#include <wtf/text/AtomicString.h>
#if ENABLE(ENCRYPTED_MEDIA)
#include "JSMediaKeyError.h"
#endif
#if ENABLE(MEDIA_STREAM)
#include "JSMediaStream.h"
#endif
#if ENABLE(SCRIPTED_SPEECH)
#include "JSSpeechRecognitionResultList.h"
#endif
using namespace JSC;
namespace WebCore {
JSDictionary::GetPropertyResult JSDictionary::tryGetProperty(const char* propertyName, JSValue& finalResult) const
{
ASSERT(isValid());
Identifier identifier(m_exec, propertyName);
PropertySlot slot(m_initializerObject.get());
if (!m_initializerObject.get()->getPropertySlot(m_exec, identifier, slot))
return NoPropertyFound;
if (m_exec->hadException())
return ExceptionThrown;
finalResult = slot.getValue(m_exec, identifier);
if (m_exec->hadException())
return ExceptionThrown;
return PropertyFound;
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, bool& result)
{
result = value.toBoolean(exec);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, int& result)
{
result = value.toInt32(exec);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, unsigned& result)
{
result = value.toUInt32(exec);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, unsigned short& result)
{
result = static_cast<unsigned short>(value.toUInt32(exec));
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, unsigned long& result)
{
result = static_cast<unsigned long>(value.toUInt32(exec));
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, unsigned long long& result)
{
double d = value.toNumber(exec);
doubleToInteger(d, result);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, double& result)
{
result = value.toNumber(exec);
}
void JSDictionary::convertValue(JSC::ExecState* exec, JSC::JSValue value, Dictionary& result)
{
result = Dictionary(exec, value);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, String& result)
{
result = value.toString(exec)->value(exec);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, Vector<String>& result)
{
if (value.isUndefinedOrNull())
return;
unsigned length = 0;
JSObject* object = toJSSequence(exec, value, length);
if (exec->hadException())
return;
for (unsigned i = 0 ; i < length; ++i) {
JSValue itemValue = object->get(exec, i);
if (exec->hadException())
return;
result.append(itemValue.toString(exec)->value(exec));
}
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, ScriptValue& result)
{
result = ScriptValue(exec->vm(), value);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, RefPtr<SerializedScriptValue>& result)
{
result = SerializedScriptValue::create(exec, value, 0, 0);
}
void JSDictionary::convertValue(ExecState*, JSValue value, RefPtr<DOMWindow>& result)
{
result = toDOMWindow(value);
}
void JSDictionary::convertValue(ExecState*, JSValue value, RefPtr<EventTarget>& result)
{
result = toEventTarget(value);
}
void JSDictionary::convertValue(ExecState*, JSValue value, RefPtr<Node>& result)
{
result = toNode(value);
}
void JSDictionary::convertValue(ExecState*, JSValue value, RefPtr<Storage>& result)
{
result = toStorage(value);
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, MessagePortArray& result)
{
ArrayBufferArray arrayBuffers;
fillMessagePortArray(exec, value, result, arrayBuffers);
}
#if ENABLE(VIDEO_TRACK)
void JSDictionary::convertValue(ExecState*, JSValue value, RefPtr<TrackBase>& result)
{
result = toTrack(value);
}
#endif
void JSDictionary::convertValue(ExecState* exec, JSValue value, HashSet<AtomicString>& result)
{
result.clear();
if (value.isUndefinedOrNull())
return;
unsigned length = 0;
JSObject* object = toJSSequence(exec, value, length);
if (exec->hadException())
return;
for (unsigned i = 0 ; i < length; ++i) {
JSValue itemValue = object->get(exec, i);
if (exec->hadException())
return;
result.add(itemValue.toString(exec)->value(exec));
}
}
void JSDictionary::convertValue(ExecState* exec, JSValue value, ArrayValue& result)
{
if (value.isUndefinedOrNull())
return;
result = ArrayValue(exec, value);
}
void JSDictionary::convertValue(JSC::ExecState*, JSC::JSValue value, RefPtr<Uint8Array>& result)
{
result = toUint8Array(value);
}
#if ENABLE(ENCRYPTED_MEDIA)
void JSDictionary::convertValue(JSC::ExecState*, JSC::JSValue value, RefPtr<MediaKeyError>& result)
{
result = toMediaKeyError(value);
}
#endif
#if ENABLE(MEDIA_STREAM)
void JSDictionary::convertValue(JSC::ExecState*, JSC::JSValue value, RefPtr<MediaStream>& result)
{
result = toMediaStream(value);
}
#endif
#if ENABLE(FONT_LOAD_EVENTS)
void JSDictionary::convertValue(JSC::ExecState*, JSC::JSValue value, RefPtr<CSSFontFaceRule>& result)
{
result = toCSSFontFaceRule(value);
}
void JSDictionary::convertValue(JSC::ExecState*, JSC::JSValue value, RefPtr<DOMError>& result)
{
result = toDOMError(value);
}
void JSDictionary::convertValue(JSC::ExecState* exec, JSC::JSValue value, RefPtr<VoidCallback>& result)
{
if (!value.isFunction())
return;
result = JSVoidCallback::create(asObject(value), jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()));
}
#endif
#if ENABLE(SCRIPTED_SPEECH)
void JSDictionary::convertValue(JSC::ExecState*, JSC::JSValue value, RefPtr<SpeechRecognitionResultList>& result)
{
result = toSpeechRecognitionResultList(value);
}
#endif
bool JSDictionary::getWithUndefinedOrNullCheck(const String& propertyName, String& result) const
{
ASSERT(isValid());
JSValue value;
if (tryGetProperty(propertyName.utf8().data(), value) != PropertyFound || value.isUndefinedOrNull())
return false;
result = value.toWTFString(m_exec);
return true;
}
} // namespace WebCore
| 28.516364 | 114 | 0.728258 | [
"object",
"vector"
] |
9073fcab4649ab7f1393f35d0cd417a92f7b007a | 52,656 | cpp | C++ | source/multi-cairo/opendl.cpp | dewf/opendl | 55930803b737e6679f3cacd546de79d8a9066f18 | [
"MIT"
] | 23 | 2019-04-12T10:34:29.000Z | 2021-02-01T21:04:30.000Z | source/multi-cairo/opendl.cpp | dewf/opendl | 55930803b737e6679f3cacd546de79d8a9066f18 | [
"MIT"
] | 2 | 2019-04-12T04:41:20.000Z | 2021-01-01T08:42:27.000Z | source/multi-cairo/opendl.cpp | dewf/opendl | 55930803b737e6679f3cacd546de79d8a9066f18 | [
"MIT"
] | 2 | 2019-04-13T01:46:50.000Z | 2019-07-02T09:48:25.000Z | #include "../opendl.h"
// opendl already includes cairo
#include <vector>
#include <string>
#include <glib.h>
#include <cstring>
#include <cassert>
#include <cairo.h>
#include <pango/pangocairo.h>
#include <cmath>
#include "pango-renderer/StringAttrManager.h"
#include "pango-renderer/CoreTextAttrManager.h"
#include <map>
#include "../common/geometry.h"
#include "../../deps/CFMinimal/source/CF/CFTypes.h"
#include "classes/CG/CGContext.h"
#include "classes/CG/CGBitmapContext.h"
#include "classes/CG/CGColor.h"
#include "classes/CG/CGColorSpace.h"
#include "classes/CG/CGGradient.h"
#include "classes/CG/CGPath.h"
#include "classes/CT/CTFont.h"
#include "classes/CT/CTLine.h"
#include "classes/CT/CTFrameSetter.h"
#include "classes/CT/CTParagraphStyle.h"
#include "util.h"
#include "../common/util.h"
const dl_CGPoint dl_CGPointZero = dl_CGPointMake(0, 0);
const dl_CGRect dl_CGRectZero = dl_CGRectMake(0, 0, 0, 0);
const dl_CGAffineTransform dl_CGAffineTransformIdentity = { 1, 0, 0, 1, 0, 0 }; // a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0
// TRANSFORM STUFF ===========================================================
//OPENDL_API dl_CGAffineTransform CDECL dl_CGAffineTransformInvert(dl_CGAffineTransform t)
//{
// auto mat = dl_to_cairo_matrix(t);
// cairo_matrix_invert(&mat);
// return cairo_to_dl_matrix(mat);
//}
OPENDL_API dl_CGAffineTransform CDECL dl_CGAffineTransformTranslate(dl_CGAffineTransform t, dl_CGFloat tx, dl_CGFloat ty)
{
auto cairo_m = dl_to_cairo_matrix(t);
cairo_matrix_translate(&cairo_m, tx, ty);
return cairo_to_dl_matrix(cairo_m);
}
OPENDL_API dl_CGAffineTransform CDECL dl_CGAffineTransformRotate(dl_CGAffineTransform t, dl_CGFloat angle)
{
auto cairo_m = dl_to_cairo_matrix(t);
cairo_matrix_rotate(&cairo_m, angle);
return cairo_to_dl_matrix(cairo_m);
}
OPENDL_API dl_CGAffineTransform CDECL dl_CGAffineTransformScale(dl_CGAffineTransform t, dl_CGFloat sx, dl_CGFloat sy)
{
auto cairo_m = dl_to_cairo_matrix(t);
cairo_matrix_scale(&cairo_m, sx, sy);
return cairo_to_dl_matrix(cairo_m);
}
OPENDL_API dl_CGAffineTransform CDECL dl_CGAffineTransformConcat(dl_CGAffineTransform t1, dl_CGAffineTransform t2)
{
auto cairo_m1 = dl_to_cairo_matrix(t1);
auto cairo_m2 = dl_to_cairo_matrix(t2);
cairo_matrix_t result;
cairo_matrix_multiply(&result, &cairo_m1, &cairo_m2);
printf("use of dl_CGAffineTransformConcat in linux -- please verify results, might have the order wrong\n");
return cairo_to_dl_matrix(result);
}
OPENDL_API int CDECL dl_Init(dl_PlatformOptions *options)
{
// nothing yet
}
OPENDL_API void CDECL dl_Shutdown()
{
// nothing yet
}
OPENDL_API dl_CGContextRef CDECL dl_CGContextCreateCairo(cairo_t *cr, int width, int height) {
return (dl_CGContextRef) new CGContext(cr, width, height);
}
OPENDL_API void dl_CGContextRelease(dl_CGContextRef c)
{
((CGContextRef)c)->release();
}
OPENDL_API void CDECL
dl_CGContextSetRGBFillColor(dl_CGContextRef c, dl_CGFloat red, dl_CGFloat green, dl_CGFloat blue, dl_CGFloat alpha) {
((CGContextRef)c)->setRGBFillColor(red, green, blue, alpha);
}
OPENDL_API void CDECL dl_CGContextFillRect(dl_CGContextRef c, dl_CGRect rect) {
((CGContextRef)c)->fillRect(rect);
}
OPENDL_API void CDECL
dl_CGContextSetRGBStrokeColor(dl_CGContextRef c, dl_CGFloat red, dl_CGFloat green, dl_CGFloat blue, dl_CGFloat alpha) {
((CGContextRef)c)->setRGBStrokeColor(red, green, blue, alpha);
}
OPENDL_API void CDECL dl_CGContextStrokeRect(dl_CGContextRef c, dl_CGRect rect) {
((CGContextRef)c)->strokeRect(rect);
}
OPENDL_API void CDECL dl_CGContextStrokeRectWithWidth(dl_CGContextRef c, dl_CGRect rect, dl_CGFloat width) {
((CGContextRef)c)->strokeRectWithWidth(rect, width);
}
OPENDL_API void CDECL dl_CGContextBeginPath(dl_CGContextRef c) {
((CGContextRef)c)->beginPath();
}
OPENDL_API void CDECL dl_CGContextClosePath(dl_CGContextRef c) {
((CGContextRef)c)->closePath();
}
OPENDL_API void CDECL dl_CGContextMoveToPoint(dl_CGContextRef c, dl_CGFloat x, dl_CGFloat y) {
((CGContextRef)c)->moveToPoint(x, y);
}
OPENDL_API void CDECL dl_CGContextAddLineToPoint(dl_CGContextRef c, dl_CGFloat x, dl_CGFloat y) {
((CGContextRef)c)->addLineToPoint(x, y);
}
OPENDL_API void CDECL dl_CGContextAddRect(dl_CGContextRef c, dl_CGRect rect) {
((CGContextRef)c)->addRect(rect);
}
OPENDL_API void CDECL
dl_CGContextAddArc(dl_CGContextRef c, dl_CGFloat x, dl_CGFloat y, dl_CGFloat radius, dl_CGFloat startAngle, dl_CGFloat endAngle,
int clockwise) {
((CGContextRef)c)->addArc(x, y, radius, startAngle, endAngle, clockwise);
}
OPENDL_API void CDECL dl_CGContextAddArcToPoint(dl_CGContextRef c, dl_CGFloat x1, dl_CGFloat y1, dl_CGFloat x2, dl_CGFloat y2, dl_CGFloat radius)
{
((CGContextRef)c)->addArcToPoint(x1, y1, x2, y2, radius);
}
OPENDL_API void CDECL dl_CGContextDrawPath(dl_CGContextRef c, dl_CGPathDrawingMode mode) {
((CGContextRef)c)->drawPath(mode);
}
OPENDL_API void CDECL dl_CGContextStrokePath(dl_CGContextRef c) {
((CGContextRef)c)->strokePath();
}
OPENDL_API void CDECL dl_CGContextFillPath(dl_CGContextRef c) {
((CGContextRef)c)->fillPath();
}
OPENDL_API void CDECL dl_CGContextSetLineWidth(dl_CGContextRef c, dl_CGFloat width) {
((CGContextRef)c)->setLineWidth(width);
}
OPENDL_API void CDECL dl_CGContextSetLineDash(dl_CGContextRef c, dl_CGFloat phase, const dl_CGFloat *lengths, size_t count) {
((CGContextRef)c)->setLineDash(phase, lengths, count);
}
OPENDL_API void CDECL dl_CGContextTranslateCTM(dl_CGContextRef c, dl_CGFloat tx, dl_CGFloat ty) {
((CGContextRef)c)->translateCTM(tx, ty);
}
OPENDL_API void CDECL dl_CGContextRotateCTM(dl_CGContextRef c, dl_CGFloat angle) {
((CGContextRef)c)->rotateCTM(angle);
}
OPENDL_API void CDECL dl_CGContextScaleCTM(dl_CGContextRef c, dl_CGFloat sx, dl_CGFloat sy) {
((CGContextRef)c)->scaleCTM(sx, sy);
}
OPENDL_API void CDECL dl_CGContextConcatCTM(dl_CGContextRef c, dl_CGAffineTransform transform) {
((CGContextRef)c)->concatCTM(transform);
}
OPENDL_API void CDECL dl_CGContextClip(dl_CGContextRef c) {
((CGContextRef)c)->clip();
}
OPENDL_API void CDECL dl_CGContextClipToRect(dl_CGContextRef c, dl_CGRect rect) {
((CGContextRef)c)->clipToRect(rect);
}
OPENDL_API void dl_CGContextSaveGState(dl_CGContextRef c) {
((CGContextRef)c)->saveGState();
}
OPENDL_API void dl_CGContextRestoreGState(dl_CGContextRef c) {
((CGContextRef)c)->restoreGState();
}
// path stuff ===========================================
OPENDL_API dl_CGPathRef CDECL dl_CGPathCreateWithRect(dl_CGRect rect, const dl_CGAffineTransform *transform)
{
return (dl_CGPathRef)CGPath::createWithRect(rect, transform);
}
OPENDL_API dl_CGPathRef CDECL dl_CGPathCreateWithEllipseInRect(dl_CGRect rect, const dl_CGAffineTransform *transform)
{
return (dl_CGPathRef)CGPath::createWithEllipseInRect(rect, transform);
}
OPENDL_API dl_CGPathRef CDECL dl_CGPathCreateWithRoundedRect(dl_CGRect rect, dl_CGFloat cornerWidth, dl_CGFloat cornerHeight, const dl_CGAffineTransform *transform)
{
return (dl_CGPathRef)CGPath::createWithRoundedRect(rect, cornerWidth, cornerHeight, transform);
}
OPENDL_API dl_CGMutablePathRef CDECL dl_CGPathCreateMutable(void)
{
return (dl_CGMutablePathRef) new CGMutablePath();
}
OPENDL_API dl_CGPathRef CDECL dl_CGPathCreateCopy(dl_CGPathRef path)
{
return (dl_CGPathRef) ((CGPathRef)path)->copy();
}
OPENDL_API dl_CGMutablePathRef CDECL dl_CGPathCreateMutableCopy(dl_CGPathRef path)
{
return (dl_CGMutablePathRef) new CGMutablePath((CGPathRef)path);
}
OPENDL_API void CDECL dl_CGPathMoveToPoint(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGFloat x, dl_CGFloat y)
{
((CGMutablePathRef)path)->moveToPoint(m, x, y);
}
OPENDL_API void CDECL dl_CGPathAddArc(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGFloat x, dl_CGFloat y, dl_CGFloat radius, dl_CGFloat startAngle, dl_CGFloat endAngle, bool clockwise)
{
((CGMutablePathRef)path)->addArc(m, x, y, radius, startAngle, endAngle, clockwise);
}
OPENDL_API void CDECL dl_CGPathAddRelativeArc(dl_CGMutablePathRef path, const dl_CGAffineTransform *matrix, dl_CGFloat x, dl_CGFloat y, dl_CGFloat radius, dl_CGFloat startAngle, dl_CGFloat delta)
{
((CGMutablePathRef)path)->addRelativeArc(matrix, x, y, radius, startAngle, delta);
}
OPENDL_API void CDECL dl_CGPathAddArcToPoint(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGFloat x1, dl_CGFloat y1, dl_CGFloat x2, dl_CGFloat y2, dl_CGFloat radius)
{
((CGMutablePathRef)path)->addArcToPoint(m, x1, y1, x2, y2, radius);
}
OPENDL_API void CDECL dl_CGPathAddCurveToPoint(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGFloat cp1x, dl_CGFloat cp1y, dl_CGFloat cp2x, dl_CGFloat cp2y, dl_CGFloat x, dl_CGFloat y)
{
((CGMutablePathRef)path)->addCurveToPoint(m, cp1x, cp1y, cp2x, cp2y, x, y);
}
OPENDL_API void CDECL dl_CGPathAddLines(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, const dl_CGPoint *points, size_t count)
{
((CGMutablePathRef)path)->addLines(m, points, count);
}
OPENDL_API void CDECL dl_CGPathAddLineToPoint(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGFloat x, dl_CGFloat y)
{
((CGMutablePathRef)path)->addLineToPoint(m, x, y);
}
OPENDL_API void CDECL dl_CGPathAddPath(dl_CGMutablePathRef path1, const dl_CGAffineTransform *m, dl_CGPathRef path2)
{
((CGMutablePathRef)path1)->addPath(m, (CGPathRef)path2);
}
OPENDL_API void CDECL dl_CGPathAddQuadCurveToPoint(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGFloat cpx, dl_CGFloat cpy, dl_CGFloat x, dl_CGFloat y)
{
((CGMutablePathRef)path)->addQuadCurveToPoint(m, cpx, cpy, x, y);
}
OPENDL_API void CDECL dl_CGPathAddRect(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGRect rect)
{
((CGMutablePathRef)path)->addRect(m, rect);
}
OPENDL_API void CDECL dl_CGPathAddRects(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, const dl_CGRect *rects, size_t count)
{
((CGMutablePathRef)path)->addRects(m, rects, count);
}
OPENDL_API void CDECL dl_CGPathAddRoundedRect(dl_CGMutablePathRef path, const dl_CGAffineTransform *transform, dl_CGRect rect, dl_CGFloat cornerWidth, dl_CGFloat cornerHeight)
{
((CGMutablePathRef)path)->addRoundedRect(transform, rect, cornerWidth, cornerHeight);
}
OPENDL_API void CDECL dl_CGPathAddEllipseInRect(dl_CGMutablePathRef path, const dl_CGAffineTransform *m, dl_CGRect rect)
{
((CGMutablePathRef)path)->addEllipseInRect(m, rect);
}
OPENDL_API void CDECL dl_CGPathCloseSubpath(dl_CGMutablePathRef path)
{
((CGMutablePathRef)path)->closeSubpath();
}
OPENDL_API dl_CGPathRef CDECL dl_CGPathRetain(dl_CGPathRef path)
{
return (dl_CGPathRef) ((CGPathRef)path)->retain();
}
OPENDL_API void CDECL dl_CGPathRelease(dl_CGPathRef path)
{
((CGPathRef)path)->release();
}
OPENDL_API dl_CGPoint CDECL dl_CGPathGetCurrentPoint(dl_CGPathRef path)
{
return ((CGPathRef)path)->getCurrentPoint();
}
OPENDL_API void CDECL dl_CGContextAddPath(dl_CGContextRef context, dl_CGPathRef path)
{
// "if the source is non-empty, the path elements are appended in order onto the current
// path. the CTM is applied to the points before adding them to the path(!)
// after the call completes, the start point and current point of the path are those of the
// last subpath in 'path'
((CGContextRef)context)->addPath((CGPathRef)path);
}
/* colorspace and gradient stuff */
const dl_CFStringRef dl_kCGColorSpaceGenericGray = dl_CFSTR("dl_kCGColorSpaceGenericGray");
const dl_CFStringRef dl_kCGColorSpaceGenericRGB = dl_CFSTR("dl_kCGColorSpaceGenericRGB");
const dl_CFStringRef dl_kCGColorSpaceGenericCMYK = dl_CFSTR("dl_kCGColorSpaceGenericCMYK");
const dl_CFStringRef dl_kCGColorSpaceGenericRGBLinear = dl_CFSTR("dl_kCGColorSpaceGenericRGBLinear");
const dl_CFStringRef dl_kCGColorSpaceAdobeRGB1998 = dl_CFSTR("dl_kCGColorSpaceAdobeRGB1998");
const dl_CFStringRef dl_kCGColorSpaceSRGB = dl_CFSTR("dl_kCGColorSpaceSRGB");
const dl_CFStringRef dl_kCGColorSpaceGenericGrayGamma2_2 = dl_CFSTR("dl_kCGColorSpaceGenericGrayGamma2_2");
OPENDL_API dl_CGColorSpaceRef CDECL dl_CGColorSpaceCreateWithName(dl_CFStringRef name) {
return (dl_CGColorSpaceRef) new CGColorSpace((cf::StringRef)name);
}
OPENDL_API dl_CGColorSpaceRef CDECL dl_CGColorSpaceCreateDeviceGray(void)
{
return (dl_CGColorSpaceRef) new CGColorSpace(CGColorSpace::DeviceSpace_Gray);
}
OPENDL_API void CDECL dl_CGColorSpaceRelease(dl_CGColorSpaceRef colorSpace)
{
((CGColorSpaceRef)colorSpace)->release();
}
// color stuff ==============
OPENDL_API dl_CGColorRef CDECL dl_CGColorCreateGenericRGB(dl_CGFloat red, dl_CGFloat green, dl_CGFloat blue, dl_CGFloat alpha)
{
return (dl_CGColorRef) new CGColor(red, green, blue, alpha);
}
OPENDL_API void CDECL dl_CGColorRelease(dl_CGColorRef color)
{
((CGColorRef)color)->release();
}
OPENDL_API void CDECL dl_CGContextSetFillColorWithColor(dl_CGContextRef c, dl_CGColorRef color)
{
((CGContextRef)c)->setFillColorWithColor(color);
}
OPENDL_API void CDECL dl_CGContextSetStrokeColorWithColor(dl_CGContextRef c, dl_CGColorRef color)
{
((CGContextRef)c)->setStrokeColorWithColor(color);
}
const dl_CFStringRef dl_kCGColorWhite = dl_CFSTR("dl_kCGColorWhite");
const dl_CFStringRef dl_kCGColorBlack = dl_CFSTR("dl_kCGColorBlack");
const dl_CFStringRef dl_kCGColorClear = dl_CFSTR("dl_kCGColorClear");
OPENDL_API dl_CGColorRef CDECL dl_CGColorGetConstantColor(dl_CFStringRef colorName)
{
if (colorName == dl_kCGColorWhite) {
return (dl_CGColorRef)CGColor::White;
} else if (colorName == dl_kCGColorBlack) {
return (dl_CGColorRef)CGColor::Black;
} else if (colorName == dl_kCGColorClear) {
return (dl_CGColorRef)CGColor::Clear;
} else {
printf("dl_CGColorGetConstantColor asked for unknown color - returning null");
return nullptr;
}
}
OPENDL_API size_t CDECL dl_CGColorGetNumberOfComponents(dl_CGColorRef color)
{
return ((CGColorRef)color)->getNumberOfComponents();
}
OPENDL_API const dl_CGFloat* CDECL dl_CGColorGetComponents(dl_CGColorRef color)
{
return ((CGColorRef)color)->getComponents();
}
// gradients =======
OPENDL_API dl_CGGradientRef CDECL
dl_CGGradientCreateWithColorComponents(dl_CGColorSpaceRef space, const dl_CGFloat components[], const dl_CGFloat locations[],
size_t count) {
return (dl_CGGradientRef) CGGradient::createWithColorComponents((CGColorSpaceRef)space, components, locations, count);
}
OPENDL_API void CDECL dl_CGGradientRelease(dl_CGGradientRef gradient) {
((CGGradientRef)gradient)->release();
}
OPENDL_API void CDECL
dl_CGContextDrawLinearGradient(dl_CGContextRef c, dl_CGGradientRef gradient, dl_CGPoint startPoint, dl_CGPoint endPoint,
dl_CGGradientDrawingOptions options)
{
((CGContextRef)c)->drawLinearGradient(gradient, startPoint, endPoint, options);
}
// text =============================
const dl_CFStringRef dl_kCTForegroundColorAttributeName = dl_CFSTR("dl_kCTForegroundColorAttributeName");
const dl_CFStringRef dl_kCTForegroundColorFromContextAttributeName = dl_CFSTR("dl_kCTForegroundColorFromContextAttributeName");
const dl_CFStringRef dl_kCTFontAttributeName = dl_CFSTR("dl_kCTFontAttributeName");
const dl_CFStringRef dl_kCTStrokeWidthAttributeName = dl_CFSTR("dl_kCTStrokeWidthAttributeName");
const dl_CFStringRef dl_kCTStrokeColorAttributeName = dl_CFSTR("dl_kCTStrokeColorAttributeName");
OPENDL_API void dl_CGContextSetTextMatrix(dl_CGContextRef c, dl_CGAffineTransform t)
{
((CGContextRef)c)->setTextMatrix(t);
}
OPENDL_API dl_CTFramesetterRef CDECL dl_CTFramesetterCreateWithAttributedString(dl_CFAttributedStringRef attrString)
{
return (dl_CTFramesetterRef) new CTFrameSetter((cf::AttributedStringRef)attrString);
}
OPENDL_API dl_CTFrameRef CDECL
dl_CTFramesetterCreateFrame(dl_CTFramesetterRef framesetter, dl_CFRange stringRange, dl_CGPathRef path, dl_CFDictionaryRef frameAttributes)
{
return (dl_CTFrameRef)((CTFrameSetterRef)framesetter)->createFrame(STRUCT_CAST(stringRange, CFRange), (CGPathRef)path, (cf::DictionaryRef)frameAttributes);
}
OPENDL_API dl_CFArrayRef CDECL dl_CTFrameGetLines(dl_CTFrameRef frame)
{
return (dl_CFArrayRef)((CTFrameRef)frame)->getLines();
}
OPENDL_API void CDECL dl_CTFrameGetLineOrigins(dl_CTFrameRef frame, dl_CFRange range, dl_CGPoint origins[])
{
((CTFrameRef)frame)->getLineOrigins(range, origins);
}
OPENDL_API dl_CFDictionaryRef CDECL dl_CTRunGetAttributes(dl_CTRunRef run)
{
(dl_CFDictionaryRef)((CTRunRef)run)->getAttributes();
}
OPENDL_API double CDECL dl_CTRunGetTypographicBounds(dl_CTRunRef run, dl_CFRange range, dl_CGFloat* ascent, dl_CGFloat* descent, dl_CGFloat* leading)
{
return ((CTRunRef)run)->getTypographicBounds(range, ascent, descent, leading);
}
OPENDL_API dl_CFRange CDECL dl_CTRunGetStringRange(dl_CTRunRef run)
{
return ((CTRunRef)run)->getStringRange();
}
OPENDL_API dl_CTFontRef CDECL dl_CTFontCreateWithName(dl_CFStringRef name, dl_CGFloat size, const dl_CGAffineTransform *matrix)
{
auto nameStr = ((cf::StringRef)name)->getUtf8String();
return (dl_CTFontRef) new CTFont(nameStr, size, matrix);
}
OPENDL_API dl_CFArrayRef CDECL dl_CTFontManagerCreateFontDescriptorsFromURL(dl_CFURLRef fileURL)
{
return (dl_CFArrayRef) CTFontDescriptor::createFontDescriptorsFromURL((cf::URLRef)fileURL);
}
OPENDL_API dl_CTFontRef CDECL dl_CTFontCreateWithFontDescriptor(dl_CTFontDescriptorRef descriptor, dl_CGFloat size, const dl_CGAffineTransform *matrix)
{
return (dl_CTFontRef) CTFont::createWithFontDescriptor((CTFontDescriptorRef)descriptor, size, matrix);
}
OPENDL_API dl_CTFontRef CDECL dl_CTFontCreateCopyWithSymbolicTraits(dl_CTFontRef font, dl_CGFloat size, const dl_CGAffineTransform *matrix, dl_CTFontSymbolicTraits symTraitValue, dl_CTFontSymbolicTraits symTraitMask)
{
return (dl_CTFontRef)CTFont::createCopyWithSymbolicTraits((CTFontRef)font, size, matrix, symTraitValue, symTraitMask);
}
OPENDL_API dl_CGFloat CDECL dl_CTFontGetAscent(dl_CTFontRef font)
{
return ((CTFontRef)font)->getAscent();
}
OPENDL_API dl_CGFloat CDECL dl_CTFontGetDescent(dl_CTFontRef font)
{
return ((CTFontRef)font)->getDescent();
}
OPENDL_API dl_CGFloat CDECL dl_CTFontGetUnderlineThickness(dl_CTFontRef font)
{
return ((CTFontRef)font)->getUnderlineThickness();
}
OPENDL_API dl_CGFloat CDECL dl_CTFontGetUnderlinePosition(dl_CTFontRef font)
{
return ((CTFontRef)font)->getUnderlinePosition();
}
OPENDL_API dl_CTRunStatus CDECL dl_CTRunGetStatus(dl_CTRunRef run)
{
return ((CTRunRef)run)->getRunStatus();
}
OPENDL_API void CDECL dl_CTFrameDraw(dl_CTFrameRef frame, dl_CGContextRef context)
{
((CTFrameRef)frame)->draw((CGContextRef)context);
}
OPENDL_API dl_CTParagraphStyleRef CDECL dl_CTParagraphStyleCreate(const dl_CTParagraphStyleSetting * settings, size_t settingCount)
{
return (dl_CTParagraphStyleRef) CTParagraphStyle::create(settings, settingCount);
}
const dl_CFStringRef dl_kCTParagraphStyleAttributeName = dl_CFSTR("dl_kCTParagraphStyleAttributeName");
OPENDL_API dl_CTLineRef CDECL dl_CTLineCreateWithAttributedString(dl_CFAttributedStringRef string)
{
return (dl_CTLineRef) CTLine::createWithAttributedString((cf::AttributedStringRef)string);
}
OPENDL_API dl_CGRect CDECL dl_CTLineGetBoundsWithOptions(dl_CTLineRef line, dl_CTLineBoundsOptions options)
{
return ((CTLineRef)line)->getBoundsWithOptions(options);
}
OPENDL_API double CDECL dl_CTLineGetTypographicBounds(dl_CTLineRef line, dl_CGFloat *ascent, dl_CGFloat *descent, dl_CGFloat *leading)
{
return ((CTLineRef)line)->getTypographicBounds(ascent, descent, leading);
}
OPENDL_API dl_CGFloat CDECL dl_CTLineGetOffsetForStringIndex(dl_CTLineRef line, dl_CFIndex charIndex, dl_CGFloat* secondaryOffset)
{
return ((CTLineRef)line)->getOffsetForStringIndex(charIndex, secondaryOffset);
}
OPENDL_API dl_CFIndex CDECL dl_CTLineGetStringIndexForPosition(dl_CTLineRef line, dl_CGPoint position)
{
return ((CTLineRef)line)->getStringIndexForPosition(position);
}
OPENDL_API dl_CFRange CDECL dl_CTLineGetStringRange(dl_CTLineRef line)
{
return ((CTLineRef)line)->getStringRange();
}
OPENDL_API dl_CFArrayRef CDECL dl_CTLineGetGlyphRuns(dl_CTLineRef line)
{
return (dl_CFArrayRef)((CTLineRef)line)->getGlyphRuns();
}
OPENDL_API void CDECL dl_CTLineDraw(dl_CTLineRef line, dl_CGContextRef context)
{
((CTLineRef)line)->draw((CGContextRef)context);
}
OPENDL_API void CDECL dl_CGContextSetTextPosition(dl_CGContextRef c, dl_CGFloat x, dl_CGFloat y)
{
((CGContextRef)c)->setTextPosition(x, y);
}
OPENDL_API void CDECL dl_CGContextSetTextDrawingMode(dl_CGContextRef c, dl_CGTextDrawingMode mode)
{
((CGContextRef)c)->setTextDrawingMode(mode);
}
OPENDL_API dl_CGContextRef CDECL dl_CGBitmapContextCreate(void *data, size_t width,
size_t height, size_t bitsPerComponent, size_t bytesPerRow,
dl_CGColorSpaceRef space, dl_CGBitmapInfo bitmapInfo)
{
return (dl_CGContextRef) CGBitmapContext::create(data, width, height, bitsPerComponent, bytesPerRow, (CGColorSpaceRef)space, bitmapInfo);
}
OPENDL_API void * CDECL dl_CGBitmapContextGetData(dl_CGContextRef bitmap)
{
return ((CGBitmapContextRef)bitmap)->getData();
}
OPENDL_API void CDECL dl_CGBitmapContextReleaseData(dl_CGContextRef bitmap)
{
((CGBitmapContextRef)bitmap)->releaseData();
}
OPENDL_API dl_CGImageRef CDECL dl_CGBitmapContextCreateImage(dl_CGContextRef context)
{
// takes a snapshot of a bitmap context, to be used as a mask or what-have-you
// wrapper around a new surface which can be used as a drawing/mask source
return (dl_CGImageRef) ((CGBitmapContextRef)context)->createImage();
}
OPENDL_API void dl_CGImageRelease(dl_CGImageRef image)
{
((CGImageRef)image)->release();
}
OPENDL_API void CDECL dl_CGContextClipToMask(dl_CGContextRef c, dl_CGRect rect, dl_CGImageRef mask)
{
((CGContextRef)c)->clipToMask(rect, (CGImageRef)mask);
}
OPENDL_API void CDECL dl_CGContextDrawImage(dl_CGContextRef c, dl_CGRect rect, dl_CGImageRef image)
{
((CGContextRef)c)->drawImage(rect, (CGImageRef)image);
}
// old font page code below ======================
// ===============================================
//dl_CGGradientRef easyGrad(dl_CGFloat fromR, dl_CGFloat fromG, dl_CGFloat fromB, dl_CGFloat fromA,
// dl_CGFloat toR, dl_CGFloat toG, dl_CGFloat toB, dl_CGFloat toA) {
// static auto colorSpace = dl_CGColorSpaceCreateWithName(dl_kCGColorSpaceGenericRGB);
//
// dl_CGFloat components[] = {
// fromR, fromG, fromB, fromA,
// toR, toG, toB, toA
// };
// dl_CGFloat locations[] = {
// 0.0, 1.0
// };
// return dl_CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
//}
//
//void gradientRectAround(dl_CGContextRef c, PangoLayout *layout, PangoFontMetrics *metrics, int y) {
// PangoRectangle inkRect, logicalRect;
//
// dl_CGContextSaveGState(c);
//
// auto line = pango_layout_get_line(layout, 0);
// pango_layout_line_get_pixel_extents(line, &inkRect, &logicalRect);
//
// auto useRect = logicalRect;
// useRect.x = 20;
// useRect.y = y; // + pango_font_metrics_get_descent(metrics) / PANGO_SCALE;
//
// dl_CGContextClipToRect(c, {{(dl_CGFloat) useRect.x, (dl_CGFloat) useRect.y},
// {(dl_CGFloat) useRect.width, (dl_CGFloat) useRect.height}});
// auto grad = easyGrad(0.8, 0.8, 0.3, 1, 1, 0.5, 0.4, 1);
// dl_CGContextDrawLinearGradient(c, grad, {(dl_CGFloat) useRect.x, (dl_CGFloat) useRect.y},
// {(dl_CGFloat) (useRect.x + useRect.width), (dl_CGFloat) (useRect.y + useRect.height)}, 0);
//
// // dotted border
// double dashes[2] = {2, 2};
// cairo_set_dash(c->cr, dashes, 2, 0);
// cairo_set_line_width(c->cr, 1);
// cairo_rectangle(c->cr, useRect.x, useRect.y, useRect.width, useRect.height);
// cairo_set_source_rgb(c->cr, 0, 0, 0);
// cairo_stroke(c->cr);
//
// dl_CGContextRestoreGState(c);
//}
//
//void pointAt(dl_CGContextRef c, int x, int y) {
// cairo_arc(c->cr, x, y, 1, 0, 2 * M_PI);
// cairo_set_source_rgb(c->cr, 1, 0, 0);
// cairo_fill(c->cr);
//}
//
//OPENDL_API void CDECL dlFontPage01(dl_CGContextRef c, int width, int height) {
// dl_CGContextSetRGBFillColor(c, 0.5, 0.5, 0.5, 1);
// dl_CGContextFillRect(c, {{0, 0},
// {(float) width, (float) height}});
// dl_CGContextScaleCTM(c, 3, 3);
//
// const char *text = "Quartz♪❦♛あぎ";
// int y = 20;
//
// auto layout = pango_cairo_create_layout(c->cr);
// auto pango_context = pango_layout_get_context(layout);
// pango_cairo_context_set_resolution(pango_context, 72);
//
// pango_layout_set_text(layout, text, -1);
//
// auto arial12Desc = pango_font_description_from_string("Arial 12");
// auto arial12Metrics = pango_context_get_metrics(pango_context, arial12Desc, pango_language_get_default());
//
// pointAt(c, 20, y);
// pango_layout_set_font_description(layout, arial12Desc);
// gradientRectAround(c, layout, arial12Metrics, y);
// cairo_move_to(c->cr, 20, y);
// cairo_set_source_rgb(c->cr, 0, 0, 0);
// pango_cairo_show_layout(c->cr, layout);
//
// // larger lines
// auto times40Desc = pango_font_description_from_string("Times 40");
// auto times40Metrics = pango_context_get_metrics(pango_context, times40Desc, pango_language_get_default());
//// auto times40Ascent = pango_font_metrics_get_ascent(times40Metrics) / PANGO_SCALE;
//
// pango_layout_set_font_description(layout, times40Desc);
//
// // solid blue
// y += 30;
// pointAt(c, 20, y);
// gradientRectAround(c, layout, times40Metrics, y);
// cairo_move_to(c->cr, 20, y);
// cairo_set_source_rgb(c->cr, 0, 0.3, 1.0);
// pango_cairo_show_layout(c->cr, layout);
//
// // w/ stroke below
// cairo_set_line_width(c->cr, 0.5);
//
// // stroked only
// y += 60;
// pointAt(c, 20, y);
// gradientRectAround(c, layout, times40Metrics, y);
// cairo_move_to(c->cr, 20, y);
// cairo_set_source_rgb(c->cr, 0, 0.3, 1.0);
// pango_cairo_layout_path(c->cr, layout);
// cairo_stroke(c->cr);
//
// // stroked and filled
// y += 60;
// pointAt(c, 20, y);
// gradientRectAround(c, layout, times40Metrics, y);
//
// cairo_move_to(c->cr, 20, y);
// cairo_set_source_rgb(c->cr, 0, 0.3, 1.0);
// pango_cairo_layout_path(c->cr, layout);
// cairo_fill(c->cr);
//
// cairo_move_to(c->cr, 20, y);
// pango_cairo_layout_path(c->cr, layout);
// cairo_set_source_rgb(c->cr, 0, 0, 0);
// cairo_stroke(c->cr);
//
// // baseline render
// auto baseline = pango_layout_get_baseline(layout) / PANGO_SCALE;
//
// y += 100;
// pointAt(c, 20, y);
//
// cairo_move_to(c->cr, 20, y - baseline);
// cairo_set_source_rgb(c->cr, 0, 0.3, 1.0);
// pango_cairo_layout_path(c->cr, layout);
// cairo_fill(c->cr);
//
// cairo_move_to(c->cr, 20, y - baseline);
// pango_cairo_layout_path(c->cr, layout);
// cairo_set_source_rgb(c->cr, 0, 0, 0);
// cairo_set_line_width(c->cr, 0.5);
// cairo_stroke(c->cr);
//
// // end
// g_object_unref(layout);
// pango_font_description_free(times40Desc);
// pango_font_description_free(arial12Desc);
//}
#define MATCH(SUBSTR) \
strFind = SUBSTR; \
start = text.find(strFind); \
length = strFind.length();
#define APPLY(ATTR) \
attr = ATTR; \
attr->start_index = (guint)start; \
attr->end_index = (guint)(attr->start_index + length); \
pango_attr_list_insert(attrList, attr); \
todestroy.push_back(attr);
#define EXAPPLY(ATTR) \
attrManager.setAttr(ATTR, start, length); \
todestroy.push_back(ATTR);
// removed two below lines: they should be happening elsewhere (applyRangeSpec callback in StringAttrManager)
// ATTR->start_index = (guint)start; \
// ATTR->end_index = (guint)(attr->start_index + length); \
#define MATCHAPPLY(SUBSTR, ATTR) \
MATCH(SUBSTR); \
APPLY(ATTR);
#define EXMATCHAPPLY(SUBSTR, ATTR) \
MATCH(SUBSTR); \
EXAPPLY(ATTR);
#include "pango-renderer/ExtendedAttrs.h"
static void render_layout(cairo_t *cr, PangoLayout *layout, RGBAColor *defaultColor) {
double last_y = -1;
int line_i = 0;
auto iter2 = pango_layout_get_iter(layout);
do {
PangoRectangle line_exts, line_ink_exts;
auto line = pango_layout_iter_get_line_readonly(iter2);
pango_layout_iter_get_line_extents(iter2, &line_ink_exts, &line_exts);
auto baseline = pango_units_to_double(pango_layout_iter_get_baseline(iter2));
//printf("line iter, baseline %.2f\n", baseline);
do {
// runs
auto run = pango_layout_iter_get_run_readonly(iter2);
if (run) {
PangoRectangle run_exts;
pango_layout_iter_get_run_extents(iter2, nullptr, &run_exts);
auto lang = pango_script_get_sample_language((PangoScript) run->item->analysis.script);
auto metrics = pango_font_get_metrics(run->item->analysis.font, lang);
RGBAColor *fgColor = nullptr;
RGBAColor *bgColor = nullptr;
// PangoColor *fgColor = nullptr;
// PangoColor *bgColor = nullptr;
RGBAColor *highColor = nullptr;
IntWrapper *strikeCount = nullptr;
RGBAColor *strikeColor = nullptr;
IntWrapper *ulStyle = nullptr;
RGBAColor *ulColor = nullptr;
for (auto item = run->item->analysis.extra_attrs; item != NULL; item = item->next) {
auto attr = (PangoAttribute *) item->data;
switch (attr->klass->type) {
// case PANGO_ATTR_FOREGROUND:
// fgColor = &((PangoAttrColor *) attr)->color;
// break;
// case PANGO_ATTR_BACKGROUND:
// bgColor = &((PangoAttrColor *) attr)->color;
// break;
default:
if (attr->klass->type == ExtendedAttrs::pangoAttrType()) {
auto *extAttrs = (ExtendedAttrs *) attr;
fgColor = (RGBAColor *) extAttrs->getFormatFor(kCustomFormatForeground);
bgColor = (RGBAColor *) extAttrs->getFormatFor(kCustomFormatBackground);
highColor = (RGBAColor *) extAttrs->getFormatFor(kCustomFormatHighlight);
ulStyle = (IntWrapper *) extAttrs->getFormatFor(kCustomFormatUnderlineStyle);
ulColor = (RGBAColor *) extAttrs->getFormatFor(kCustomFormatUnderlineColor);
strikeCount = (IntWrapper *) extAttrs->getFormatFor(kCustomFormatStrikeCount);
strikeColor = (RGBAColor *) extAttrs->getFormatFor(kCustomFormatStrikeColor);
}
break;
}
}
auto x = pango_units_to_double(run_exts.x);
auto y = pango_units_to_double(run_exts.y);
// if (y > last_y) {
// printf("new line %d\n", line_i++);
// printf("==============\n");
// last_y = y;
// }
// printf(" - y: %.2f\n", y);
auto width = pango_units_to_double(run_exts.width);
auto height = pango_units_to_double(
line_exts.height); // use line height instead, won't change with font
if (bgColor) {
bgColor->set_cairo_color(cr);
// cairo_set_source_rgb(cr, bgColor->red / 65535.0, bgColor->green / 65535.0, bgColor->blue / 65535.0);
cairo_rectangle(cr, x, y, width, height);
cairo_fill(cr);
}
if (ulStyle && ulStyle->value != UnderlineStyle::None) {
auto ul_pos = pango_units_to_double(
pango_font_metrics_get_underline_position(metrics));
auto ul_thickness = pango_units_to_double(
pango_font_metrics_get_underline_thickness(metrics));
auto ul_y = y + baseline - ul_pos;
cairo_set_line_width(cr, ul_thickness);
if (ulColor) {
ulColor->set_cairo_color(cr);
} else if (fgColor) {
fgColor->set_cairo_color(cr);
} else {
defaultColor->set_cairo_color(cr);
}
if (ulStyle->value >= UnderlineStyle::Single && ulStyle->value <= UnderlineStyle::Triple) {
cairo_move_to(cr, x, ul_y);
cairo_line_to(cr, x + width, ul_y);
cairo_stroke(cr);
if (ulStyle->value >= UnderlineStyle::Double) {
ul_y += ul_thickness * 2.0;
cairo_move_to(cr, x, ul_y);
cairo_line_to(cr, x + width, ul_y);
cairo_stroke(cr);
if (ulStyle->value == UnderlineStyle::Triple) {
ul_y += ul_thickness * 2.0;
cairo_move_to(cr, x, ul_y);
cairo_line_to(cr, x + width, ul_y);
cairo_stroke(cr);
}
}
} else if (ulStyle->value == UnderlineStyle::Squiggly) {
auto amplitude = ul_thickness;
auto period = ul_thickness * 5.0;
for (int t = 0; t < width; t++) {
auto ux = x + t;
auto angle = ((2.0f * M_PI * fmod(ux, period)) / period);
auto uy = ul_y + amplitude * sin(angle);
if (t == 0) {
cairo_move_to(cr, ux, uy);
} else {
cairo_line_to(cr, ux, uy);
}
}
cairo_stroke(cr);
} else if (ulStyle->value == UnderlineStyle::Overline) {
auto ink_y = pango_units_to_double(line_ink_exts.y);
auto ol_y = y + ink_y;
cairo_move_to(cr, x, ol_y);
cairo_line_to(cr, x + width, ol_y);
cairo_stroke(cr);
}
}
// draw glyphs
if (fgColor) {
fgColor->set_cairo_color(cr);
// cairo_set_source_rgb(cr, fgColor->red / 65535.0, fgColor->green / 65535.0, fgColor->blue / 65535.0);
} else {
defaultColor->set_cairo_color(cr);
}
//printf("y + baseline: %.2f\n", y + baseline);
cairo_move_to(cr, x, y + baseline);
pango_cairo_show_glyph_string(cr, run->item->analysis.font, run->glyphs);
//pango_cairo_glyph_string_path ()
//pango_cairo_layout_line_path() etc
// strikethrough on top
if (strikeCount) {
auto strike_pos = pango_units_to_double(
pango_font_metrics_get_strikethrough_position(metrics));
auto strike_thickness = pango_units_to_double(
pango_font_metrics_get_strikethrough_thickness(metrics));
cairo_set_line_width(cr, strike_thickness);
if (strikeColor) {
strikeColor->set_cairo_color(cr);
} else if (fgColor) {
fgColor->set_cairo_color(cr);
} else {
defaultColor->set_cairo_color(cr);
}
auto strike_y = y + baseline - strike_pos;
if (strikeCount->value == 1 || strikeCount->value == 3) {
// center line
cairo_move_to(cr, x, strike_y);
cairo_line_to(cr, x + width, strike_y);
cairo_stroke(cr);
}
if (strikeCount->value == 2 || strikeCount->value == 3) {
auto offset = strike_thickness * (strikeCount->value - 1); // 1 or 2
// two lines alone, or flanking a center line
auto top_y = strike_y - offset;
cairo_move_to(cr, x, top_y);
cairo_line_to(cr, x + width, top_y);
cairo_stroke(cr);
auto bottom_y = strike_y + offset;
cairo_move_to(cr, x, bottom_y);
cairo_line_to(cr, x + width, bottom_y);
cairo_stroke(cr);
}
}
// highlight on top
if (highColor) {
highColor->set_cairo_color(cr);
cairo_rectangle(cr, x, y, width, height);
cairo_fill(cr);
}
pango_font_metrics_unref(metrics);
} else {
// null run = end of line?
}
} while (pango_layout_iter_next_run(iter2));
} while (pango_layout_iter_next_line(iter2));
pango_layout_iter_free(iter2);
}
OPENDL_API void CDECL dlFontPage02Old(dl_CGContextRef c, int width, int height) {
RGBAColor black(0, 0, 0, 1);
RGBAColor red(1, 0, 0, 1);
RGBAColor green(0, 1, 0, 1);
RGBAColor blue(0, 0, 1, 1);
RGBAColor yellow(1, 1, 0, 1);
RGBAColor alphaYellow(1, 1, 0, 0.5);
RGBAColor magenta(1, 0, 1, 1);
// woot
dl_CGContextSetRGBFillColor(c, 0.39, 0.58, 0.92, 1);
dl_CGContextFillRect(c, {{0, 0},
{(float) width, (float) height}});
dl_CGContextSetTextMatrix(c, dl_CGAffineTransformIdentity);
std::string text =
"This paragraph of text rendered with DirectWrite is based on IDWriteTextFormat and IDWriteTextLayout objects"
" and uses a custom format specifier passed to the SetDrawingEffect method, and thus is capable of different"
" RBG RGB foreground colors, such as red, green, and blue as well as double underline, triple underline,"
" single strikethrough, double strikethrough, triple strikethrough, or combinations thereof. Also possible is"
" something often referred to as an overline, as well as a squiggly (squiggly?) underline.";
auto cr = ((CGContextRef)c)->getCairoContext();
auto layout = pango_cairo_create_layout(cr);
auto pango_context = pango_layout_get_context(layout);
auto fontMap = pango_cairo_font_map_get_default();
//auto pango_context = pango_font_map_create_context(fontMap);
//pango_cairo_context_set_resolution(pango_context, 72);
pango_layout_set_text(layout, text.c_str(), -1);
auto timesDesc = pango_font_description_from_string("Liberation Serif 40");
// auto fmres = pango_cairo_font_map_get_resolution((PangoCairoFontMap *)fontMap);
// printf("####fmres: %.2f\n", fmres);
auto font = pango_font_map_load_font(fontMap, pango_context, timesDesc);
auto timesMetrics = pango_context_get_metrics(pango_context, timesDesc, pango_language_get_default());
pango_layout_set_font_description(layout, timesDesc);
pango_layout_set_width(layout, pango_units_from_double(width));
pango_layout_set_height(layout, pango_units_from_double(height));
pango_layout_set_wrap(layout, PANGO_WRAP_WORD);
//pango_layout_set_justify(layout, TRUE);
auto attrList = pango_attr_list_new();
std::vector<PangoAttribute *> todestroy;
PangoAttribute *attr;
std::string strFind;
unsigned int start, length;
StringAttrManager attrManager;
EXMATCHAPPLY("IDWriteTextFormat and IDWriteTextLayout objects",
ExtendedAttrs::createFormat(kCustomFormatBackground, &magenta));
MATCHAPPLY("IDWriteTextFormat", pango_attr_style_new(PANGO_STYLE_ITALIC));
MATCHAPPLY("IDWriteTextLayout", pango_attr_style_new(PANGO_STYLE_ITALIC));
MATCHAPPLY("SetDrawingEffect", pango_attr_style_new(PANGO_STYLE_ITALIC));
MATCH("RBG");
auto single_strike = ExtendedAttrs::createFormat(kCustomFormatStrikeCount, new IntWrapper(1));
EXAPPLY(single_strike);
length = 1;
EXAPPLY(ExtendedAttrs::createFormat(kCustomFormatForeground, &red));
start += 1;
EXAPPLY(ExtendedAttrs::createFormat(kCustomFormatForeground, &blue));
start += 1;
EXAPPLY(ExtendedAttrs::createFormat(kCustomFormatForeground, &green));
MATCH("RGB");
auto yellow_underline = ExtendedAttrs::createFormat(kCustomFormatUnderlineStyle,
new IntWrapper(UnderlineStyle::Single));
yellow_underline->addFormat(kCustomFormatUnderlineColor, &yellow);
EXAPPLY(yellow_underline);
length = 1;
EXAPPLY(ExtendedAttrs::createFormat(kCustomFormatForeground, &red));
start += 1;
EXAPPLY(ExtendedAttrs::createFormat(kCustomFormatForeground, &green));
start += 1;
EXAPPLY(ExtendedAttrs::createFormat(kCustomFormatForeground, &blue));
EXMATCHAPPLY(" red", ExtendedAttrs::createFormat(kCustomFormatForeground, &red));
EXMATCHAPPLY("green", ExtendedAttrs::createFormat(kCustomFormatForeground, &green));
EXMATCHAPPLY("blue", ExtendedAttrs::createFormat(kCustomFormatForeground, &blue));
MATCH("double underline");
auto double_underline = ExtendedAttrs::createFormat(kCustomFormatUnderlineStyle,
new IntWrapper(UnderlineStyle::Double));
double_underline->addFormat(kCustomFormatUnderlineColor, &red);
EXAPPLY(double_underline);
MATCH("triple underline");
auto triple_underline = ExtendedAttrs::createFormat(kCustomFormatUnderlineStyle,
new IntWrapper(UnderlineStyle::Triple));
triple_underline->addFormat(kCustomFormatUnderlineColor, &black);
EXAPPLY(triple_underline);
MATCH("single strikethrough");
auto single_strike2 = ExtendedAttrs::createFormat(kCustomFormatStrikeCount, new IntWrapper(1));
EXAPPLY(single_strike2);
MATCH("double strikethrough");
auto double_strike = ExtendedAttrs::createFormat(kCustomFormatStrikeCount, new IntWrapper(2));
EXAPPLY(double_strike);
MATCH("triple strikethrough");
auto triple_strike = ExtendedAttrs::createFormat(kCustomFormatStrikeCount, new IntWrapper(3));
EXAPPLY(triple_strike);
MATCH("combinations");
auto combs = ExtendedAttrs::createFormat(kCustomFormatStrikeCount, new IntWrapper(2));
combs->addFormat(kCustomFormatStrikeColor, &red);
combs->addFormat(kCustomFormatUnderlineStyle, new IntWrapper(UnderlineStyle::Triple));
EXAPPLY(combs);
MATCH("thereof");
auto thereof = ExtendedAttrs::createFormat(kCustomFormatStrikeCount, new IntWrapper(3));
thereof->addFormat(kCustomFormatUnderlineStyle, new IntWrapper(UnderlineStyle::Double));
thereof->addFormat(kCustomFormatUnderlineColor, &blue);
EXAPPLY(thereof);
MATCH("squiggly (squiggly?) underline");
auto squiggly_blue = ExtendedAttrs::createFormat(kCustomFormatUnderlineStyle,
new IntWrapper(UnderlineStyle::Squiggly));
squiggly_blue->addFormat(kCustomFormatUnderlineColor, &blue);
EXAPPLY(squiggly_blue);
MATCH("(squiggly?)");
auto squiggly_red = ExtendedAttrs::createFormat(kCustomFormatUnderlineColor, &red);
EXAPPLY(squiggly_red);
MATCH("overline");
auto overline = ExtendedAttrs::createFormat(kCustomFormatUnderlineStyle, new IntWrapper(UnderlineStyle::Overline));
overline->addFormat(kCustomFormatUnderlineColor, &blue);
EXAPPLY(overline);
auto highlight = ExtendedAttrs::createFormat(kCustomFormatHighlight, &alphaYellow);
EXMATCHAPPLY("the SetDrawingEffect method", highlight);
auto squiggly_high = ExtendedAttrs::createFormat(kCustomFormatHighlight, &alphaYellow);
squiggly_high->addFormat(kCustomFormatUnderlineStyle, new IntWrapper(UnderlineStyle::Squiggly));
squiggly_high->addFormat(kCustomFormatUnderlineColor, &blue);
EXMATCHAPPLY("IDWriteTextLayout", squiggly_high);
// sort out all the extended attributes (properly merges all the overlapping ones)
attrManager.apply(attrList);
// apply all of them, the regular and extended attributes
pango_layout_set_attributes(layout, attrList);
// release, layout should own the attrs now
pango_attr_list_unref(attrList);
// yay!
render_layout(cr, layout, &black);
// // release
// pango_attr_list_unref(attrList);
// for (auto i = todestroy.begin(); i < todestroy.end(); i++) {
// pango_attribute_destroy(*i);
// }
g_object_unref(layout);
g_object_unref(font);
// g_object_unref(fontMap);
pango_font_description_free(timesDesc);
}
//static void luminance_to_alpha(cairo_surface_t *surface, int width, int height) {
// //16843009 (UINT_MAX / 255)
// // * 0.2126 = 3580823.7134 (r coeff)
// // * 0.7152 = 12046120.0368 (g coeff)
// // * 0.0722 = 1216065.2498 (b coeff)
// auto const r_coeff = (uint32_t) 3580823 + 1; // the +1 is to account for the roundoff error (lost fractional parts)
// auto const g_coeff = (uint32_t) 12046120;
// auto const b_coeff = (uint32_t) 1216065;
//
// auto data = (uint32_t *) cairo_image_surface_get_data(surface);
// for (int i = 0; i < width * height; i++) {
// auto pixel = *data;
// uint8_t r = pixel & 0xFF;
// uint8_t g = (pixel & 0xFF00) >> 8;
// uint8_t b = (pixel & 0xFF0000) >> 16;
// uint32_t alpha = (r * r_coeff) + (g * g_coeff) + (b *
// b_coeff); // essentially a fixed point multiplication where we only care about the top 8 bits of the result
// pixel &= 0x00FFFFFF; // clear any existing alpha on the target pixel
// pixel |= alpha & 0xFF000000; // set pixel alpha to top 8 bits of calculated luminance
// (*data++) = pixel;
// }
//}
//
//OPENDL_API void CDECL dlFontPage03(dl_CGContextRef c, int width, int height) {
// dl_CGContextSetRGBFillColor(c, 0, 0, 0, 1);
// dl_CGContextFillRect(c, dl_CGRectMake(0, 0, width, height));
//
// auto alpha_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
// auto alpha_context = cairo_create(alpha_surface);
// // clear alpha to black
// cairo_set_source_rgb(alpha_context, 0, 0, 0);
// cairo_paint(alpha_context);
//
// // when API is told to apply mask,
// // create offscreen buffer for all drawing until mask is released
// // all drawing happens on that buffer and then is mask-applied to real context
// // (buffer is cleared after every application)
// auto buffer_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
// auto buffer_context = cairo_create(buffer_surface);
// auto bc = dl_CGContextCreateCairo(buffer_context, width, height);
//
// // stroke text outline to mask surface
// const char *text = "Quartz♪❦♛あぎ";
// int y = 20;
//
// auto layout = pango_cairo_create_layout(alpha_context);
// auto pango_context = pango_layout_get_context(layout);
// pango_cairo_context_set_resolution(pango_context, 72);
//
// pango_layout_set_text(layout, text, -1);
//
// auto fontDesc = pango_font_description_from_string("Arial 160");
//// auto fontMetrics = pango_context_get_metrics(pango_context, fontDesc, pango_language_get_default());
//
// pango_layout_set_font_description(layout, fontDesc);
// cairo_move_to(alpha_context, 20, y);
//
// pango_cairo_layout_path(alpha_context, layout); // text outline to path
//
// cairo_set_source_rgb(alpha_context, 1, 1, 1); // white
// cairo_set_line_width(alpha_context, 8);
// cairo_stroke(alpha_context);
//
// // draw gradient to buffer
// PangoRectangle inkRect, logicalRect;
// auto line = pango_layout_get_line(layout, 0);
// pango_layout_line_get_pixel_extents(line, &inkRect, &logicalRect);
//
// dl_CGContextSaveGState(bc);
//
// auto useRect = logicalRect;
// printf("useRect: %d,%d,%d,%d\n", useRect.x, useRect.y, useRect.width, useRect.height);
// useRect.x = 20;
// useRect.y = y + 30; // + pango_font_metrics_get_descent(metrics) / PANGO_SCALE;
// useRect.height -= 40;
//
// // draw rect line for debugging
// dl_CGContextSetRGBStrokeColor(c, 1, 0, 0, 1);
// dl_CGContextSetLineWidth(c, 2);
// dl_CGContextStrokeRect(c, dl_CGRectMake(useRect.x, useRect.y, useRect.width, useRect.height));
//
//
// dl_CGContextClipToRect(bc, {{(dl_CGFloat) useRect.x, (dl_CGFloat) useRect.y},
// {(dl_CGFloat) useRect.width, (dl_CGFloat) useRect.height}});
// auto grad = easyGrad(0, 0, 0, 1, 0, 1, 1, 1);
// auto start = dl_CGPointMake(useRect.x, useRect.y);
// auto end = dl_CGPointMake(useRect.x, useRect.y + useRect.height);
// dl_CGContextDrawLinearGradient(bc, grad, start, end, 0);
//
// dl_CGContextRestoreGState(bc);
// // buffer now contains raw gradient
//
// // apply mask
// cairo_set_source_surface(c->cr, buffer_surface, 0, 0); // implicitly creates pattern source
// // convert luminance to alpha first, that's how cairo masks
// luminance_to_alpha(alpha_surface, width, height);
// cairo_mask_surface(c->cr, alpha_surface, 0, 0);
//
// // clear buffer when done
// dl_CGContextSetRGBFillColor(bc, 0, 0, 0, 1);
// dl_CGContextFillRect(bc, dl_CGRectMake(0, 0, width, height));
//
// // clear alpha buffer (luminance only)
// cairo_set_source_rgb(alpha_context, 0, 0, 0); // black
// cairo_paint(alpha_context);
//// cairo_set_operator(alpha_context, CAIRO_OPERATOR_CLEAR);
//// cairo_paint(alpha_context);
//// cairo_set_operator(alpha_context, CAIRO_OPERATOR_SOURCE);
//
// // new path =====
// cairo_move_to(alpha_context, 20, y);
// pango_cairo_layout_path(alpha_context, layout);
// cairo_set_source_rgb(alpha_context, 1, 1, 1); // white
// cairo_fill(alpha_context);
//
// // new gradient
// line = pango_layout_get_line(layout, 0);
// pango_layout_line_get_pixel_extents(line, &inkRect, &logicalRect);
//
// dl_CGContextSaveGState(bc);
//
// useRect = logicalRect;
// useRect.x = 20;
// useRect.y = y + 50; // + pango_font_metrics_get_descent(metrics) / PANGO_SCALE;
//
// dl_CGContextClipToRect(bc, {{(dl_CGFloat) useRect.x, (dl_CGFloat) useRect.y},
// {(dl_CGFloat) useRect.width, (dl_CGFloat) useRect.height}});
// grad = easyGrad(1, 0.5, 0, 1, 0, 0, 0, 1);
// start = dl_CGPointMake(useRect.x, useRect.y);
// end = dl_CGPointMake(useRect.x, useRect.y + useRect.height);
// dl_CGContextDrawLinearGradient(bc, grad, start, end, 0);
//
// dl_CGContextRestoreGState(bc);
// // buffer now contains raw gradient
//
// // apply mask
// cairo_set_source_surface(c->cr, buffer_surface, 0, 0); // implicitly creates pattern source
// luminance_to_alpha(alpha_surface, width, height);
// cairo_mask_surface(c->cr, alpha_surface, 0, 0);
//
// // clear buffer when done
// dl_CGContextSetRGBFillColor(bc, 0, 0, 0, 0);
// dl_CGContextFillRect(bc, dl_CGRectMake(0, 0, width, height));
//
// // clear alpha surface
// cairo_set_source_rgb(alpha_context, 0, 0, 0);
// cairo_paint(alpha_context);
//
// // ========
// g_object_unref(layout);
// pango_font_description_free(fontDesc);
//
// dl_CGContextDestroy(bc);
// cairo_destroy(buffer_context);
// cairo_surface_destroy(buffer_surface);
//
// cairo_destroy(alpha_context);
// cairo_surface_destroy(alpha_surface);
//}
| 39.442697 | 216 | 0.678517 | [
"geometry",
"render",
"vector",
"transform",
"solid"
] |
907718b3ca15ca239d56127a1c7ee999db0697d6 | 526 | cpp | C++ | lib/support/ConsoleInputProvider.cpp | SavchenkoValeriy/rooster | 1c7b75bb1909102bbb6e1707697f5753a5072b8f | [
"MIT"
] | 1 | 2016-10-19T13:10:22.000Z | 2016-10-19T13:10:22.000Z | lib/support/ConsoleInputProvider.cpp | SavchenkoValeriy/rooster | 1c7b75bb1909102bbb6e1707697f5753a5072b8f | [
"MIT"
] | null | null | null | lib/support/ConsoleInputProvider.cpp | SavchenkoValeriy/rooster | 1c7b75bb1909102bbb6e1707697f5753a5072b8f | [
"MIT"
] | null | null | null | #include <support/ConsoleInputProvider.h>
#include <llvm/ADT/StringExtras.h>
#include <iostream>
#include <vector>
namespace interactive {
std::string ConsoleInputProvider::read() {
std::vector<std::string> lines;
unsigned index = 0;
while (true) {
lines.push_back("");
std::string &buffer = lines.back();
std::getline(std::cin, buffer);
if (buffer.empty()) {
lines.pop_back();
break;
}
}
return std::move(llvm::join(lines.begin(), lines.end(), ""));
}
}
| 23.909091 | 65 | 0.606464 | [
"vector"
] |
907bc0db21e1769b946b743bd19bc7b1b0cde617 | 7,671 | cc | C++ | Calibration/HcalIsolatedTrackReco/plugins/SubdetFEDSelector.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 1 | 2021-11-30T16:24:46.000Z | 2021-11-30T16:24:46.000Z | Calibration/HcalIsolatedTrackReco/plugins/SubdetFEDSelector.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 4 | 2021-11-29T13:57:56.000Z | 2022-03-29T06:28:36.000Z | Calibration/HcalIsolatedTrackReco/plugins/SubdetFEDSelector.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 1 | 2021-11-23T09:25:45.000Z | 2021-11-23T09:25:45.000Z | // user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/global/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "DataFormats/FEDRawData/interface/FEDRawDataCollection.h"
#include "DataFormats/FEDRawData/interface/FEDRawData.h"
#include "DataFormats/FEDRawData/interface/FEDNumbering.h"
#include "EventFilter/RawDataCollector/interface/RawDataFEDSelector.h"
class SubdetFEDSelector : public edm::global::EDProducer<> {
public:
SubdetFEDSelector(const edm::ParameterSet&);
~SubdetFEDSelector() override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void beginJob() override {}
void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override;
void endJob() override {}
// ----------member data ---------------------------
const bool getEcal_;
const bool getHcal_;
const bool getStrip_;
const bool getPixel_;
const bool getMuon_;
const bool getTrigger_;
const edm::EDGetTokenT<FEDRawDataCollection> tok_raw_;
};
SubdetFEDSelector::SubdetFEDSelector(const edm::ParameterSet& iConfig)
: getEcal_(iConfig.getParameter<bool>("getECAL")),
getHcal_(iConfig.getParameter<bool>("getHCAL")),
getStrip_(iConfig.getParameter<bool>("getSiStrip")),
getPixel_(iConfig.getParameter<bool>("getSiPixel")),
getMuon_(iConfig.getParameter<bool>("getMuon")),
getTrigger_(iConfig.getParameter<bool>("getTrigger")),
tok_raw_(consumes<FEDRawDataCollection>(iConfig.getParameter<edm::InputTag>("rawInputLabel"))) {
produces<FEDRawDataCollection>();
}
SubdetFEDSelector::~SubdetFEDSelector() {}
void SubdetFEDSelector::produce(edm::StreamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const {
auto producedData = std::make_unique<FEDRawDataCollection>();
const edm::Handle<FEDRawDataCollection>& rawIn = iEvent.getHandle(tok_raw_);
std::vector<int> selFEDs;
if (getEcal_) {
for (int i = FEDNumbering::MINECALFEDID; i <= FEDNumbering::MAXECALFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINPreShowerFEDID; i <= FEDNumbering::MAXPreShowerFEDID; i++) {
selFEDs.push_back(i);
}
}
if (getMuon_) {
for (int i = FEDNumbering::MINCSCFEDID; i <= FEDNumbering::MAXCSCFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINCSCTFFEDID; i <= FEDNumbering::MAXCSCTFFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINDTFEDID; i <= FEDNumbering::MAXDTFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINDTTFFEDID; i <= FEDNumbering::MAXDTTFFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINRPCFEDID; i <= FEDNumbering::MAXRPCFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINCSCDDUFEDID; i <= FEDNumbering::MAXCSCDDUFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINCSCContingencyFEDID; i <= FEDNumbering::MAXCSCContingencyFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINCSCTFSPFEDID; i <= FEDNumbering::MAXCSCTFSPFEDID; i++) {
selFEDs.push_back(i);
}
}
if (getHcal_) {
for (int i = FEDNumbering::MINHCALFEDID; i <= FEDNumbering::MAXHCALFEDID; i++) {
selFEDs.push_back(i);
}
}
if (getStrip_) {
for (int i = FEDNumbering::MINSiStripFEDID; i <= FEDNumbering::MAXSiStripFEDID; i++) {
selFEDs.push_back(i);
}
}
if (getPixel_) {
for (int i = FEDNumbering::MINSiPixelFEDID; i <= FEDNumbering::MAXSiPixelFEDID; i++) {
selFEDs.push_back(i);
}
}
if (getTrigger_) {
for (int i = FEDNumbering::MINTriggerEGTPFEDID; i <= FEDNumbering::MAXTriggerEGTPFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerGTPFEDID; i <= FEDNumbering::MAXTriggerGTPFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCFEDID; i <= FEDNumbering::MAXTriggerLTCFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCmtccFEDID; i <= FEDNumbering::MAXTriggerLTCmtccFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerGCTFEDID; i <= FEDNumbering::MAXTriggerGCTFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCTriggerFEDID; i <= FEDNumbering::MAXTriggerLTCTriggerFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCHCALFEDID; i <= FEDNumbering::MAXTriggerLTCHCALFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCSiStripFEDID; i <= FEDNumbering::MAXTriggerLTCSiStripFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCECALFEDID; i <= FEDNumbering::MAXTriggerLTCECALFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCTotemCastorFEDID; i <= FEDNumbering::MAXTriggerLTCTotemCastorFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCRPCFEDID; i <= FEDNumbering::MAXTriggerLTCRPCFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCCSCFEDID; i <= FEDNumbering::MAXTriggerLTCCSCFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCDTFEDID; i <= FEDNumbering::MAXTriggerLTCDTFEDID; i++) {
selFEDs.push_back(i);
}
for (int i = FEDNumbering::MINTriggerLTCSiPixelFEDID; i <= FEDNumbering::MAXTriggerLTCSiPixelFEDID; i++) {
selFEDs.push_back(i);
}
}
for (int i = FEDNumbering::MINDAQeFEDFEDID; i <= FEDNumbering::MAXDAQeFEDFEDID; i++) {
selFEDs.push_back(i);
}
// Copying:
const FEDRawDataCollection* rdc = rawIn.product();
// if ( ( rawData[i].provenance()->processName() != e.processHistory().rbegin()->processName() ) )
// continue ; // skip all raw collections not produced by the current process
for (int j = 0; j < FEDNumbering::MAXFEDID; ++j) {
bool rightFED = false;
for (uint32_t k = 0; k < selFEDs.size(); k++) {
if (j == selFEDs[k]) {
rightFED = true;
}
}
if (!rightFED)
continue;
const FEDRawData& fedData = rdc->FEDData(j);
size_t size = fedData.size();
if (size > 0) {
// this fed has data -- lets copy it
FEDRawData& fedDataProd = producedData->FEDData(j);
if (fedDataProd.size() != 0) {
// std::cout << " More than one FEDRawDataCollection with data in FED ";
// std::cout << j << " Skipping the 2nd\n";
continue;
}
fedDataProd.resize(size);
unsigned char* dataProd = fedDataProd.data();
const unsigned char* data = fedData.data();
for (unsigned int k = 0; k < size; ++k) {
dataProd[k] = data[k];
}
}
}
iEvent.put(std::move(producedData));
}
void SubdetFEDSelector::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add<edm::InputTag>("rawInputLabel", edm::InputTag("rawDataCollector"));
desc.add<bool>("getSiPixel", true);
desc.add<bool>("getHCAL", true);
desc.add<bool>("getECAL", false);
desc.add<bool>("getMuon", false);
desc.add<bool>("getTrigger", true);
desc.add<bool>("getSiStrip", false);
descriptions.add("subdetFED", desc);
}
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(SubdetFEDSelector);
| 35.027397 | 118 | 0.672794 | [
"vector"
] |
907d7c0725c4ac76b973cc6d61b5905d09177977 | 3,653 | hpp | C++ | src/libshit/ref_counted.hpp | u3shit/libshit | 8ab8f12b4068edc269356debef78cd04de67edb4 | [
"WTFPL",
"BSD-3-Clause"
] | null | null | null | src/libshit/ref_counted.hpp | u3shit/libshit | 8ab8f12b4068edc269356debef78cd04de67edb4 | [
"WTFPL",
"BSD-3-Clause"
] | null | null | null | src/libshit/ref_counted.hpp | u3shit/libshit | 8ab8f12b4068edc269356debef78cd04de67edb4 | [
"WTFPL",
"BSD-3-Clause"
] | null | null | null | #ifndef GUARD_UNCYNICALLY_NOA_CONVALLASAPONIN_ANTICROSSES_8395
#define GUARD_UNCYNICALLY_NOA_CONVALLASAPONIN_ANTICROSSES_8395
#pragma once
#include "libshit/assert.hpp"
#include <atomic>
#include <cstdint>
#include <type_traits>
#include <utility>
namespace Libshit
{
class RefCounted
{
public:
RefCounted() = default;
RefCounted(const RefCounted&) = delete;
void operator=(const RefCounted&) = delete;
virtual ~RefCounted() noexcept = default;
virtual void Dispose() noexcept {}
unsigned use_count() const // emulate boost refcount
{ return strong_count.load(std::memory_order_relaxed); }
unsigned weak_use_count() const
{ return weak_count.load(std::memory_order_relaxed); }
void AddRef()
{
LIBSHIT_ASSERT(use_count() >= 1);
strong_count.fetch_add(1, std::memory_order_relaxed);
}
void RemoveRef()
{
if (strong_count.fetch_sub(1, std::memory_order_acq_rel) == 1)
{
LIBSHIT_ASSERT(weak_use_count() > 0);
Dispose();
LIBSHIT_ASSERT(weak_use_count() > 0);
RemoveWeakRef();
}
}
void AddWeakRef()
{
LIBSHIT_ASSERT(weak_use_count() >= 1);
weak_count.fetch_add(1, std::memory_order_relaxed);
}
void RemoveWeakRef()
{
if (weak_count.fetch_sub(1, std::memory_order_acq_rel) == 1)
delete this;
}
bool LockWeak()
{
auto count = strong_count.load(std::memory_order_relaxed);
do
if (count == 0) return false;
while (!strong_count.compare_exchange_weak(
count, count+1,
std::memory_order_acq_rel, std::memory_order_relaxed));
return true;
}
private:
inline void StackUnref() noexcept
{
// decrease strong count even in release mode, so Dispose will see
// strong_count == 0 (resurrecting is not supported by current RefCounted
// but whatever)
auto c = strong_count.fetch_sub(1, std::memory_order_acq_rel);
LIBSHIT_ASSERT_MSG(
c == 1, "RefCountedStackHolder: strong references remain");
Dispose();
// we're dead anyway, we don't have to update the weak_count
LIBSHIT_ASSERT_MSG(
weak_count.load(std::memory_order_acquire) == 1,
"RefCountedStackHolder: weak references remain");
}
template <typename T> friend class RefCountedStackHolder;
// every object has an implicit weak_count, removed when removing last
// strong ref
std::atomic<std::uint_least32_t> weak_count{1}, strong_count{1};
};
template <typename T>
constexpr bool IS_REFCOUNTED = std::is_base_of<RefCounted, T>::value;
/**
* Helper class that can be used to place a RefCounted object on the
* stack/inside a struct/etc. Upon destruction it will assert that there are
* no shared/weak pointers to it. (In release mode, it will just let the app
* crash randomly in this case...)
*/
template <typename T>
class RefCountedStackHolder
{
public:
static_assert(IS_REFCOUNTED<T>);
template <typename... Args>
RefCountedStackHolder(Args&&... args)
noexcept(std::is_nothrow_constructible_v<T, Args&&...>)
: t(std::forward<Args>(args)...) {}
RefCountedStackHolder(const RefCountedStackHolder&) = delete;
void operator=(const RefCountedStackHolder&) = delete;
~RefCountedStackHolder() noexcept
{ static_cast<RefCounted&>(t).StackUnref(); }
T& operator*() noexcept { return t; }
const T& operator*() const noexcept { return t; }
T* operator->() noexcept { return &t; }
const T* operator->() const noexcept { return &t; }
private:
T t;
};
}
#endif
| 28.76378 | 79 | 0.664933 | [
"object"
] |
9085450fecee9604d7fda1c4a0879c77c85ffb1a | 645 | cpp | C++ | src/frontends/onnx/frontend/src/op/mean.cpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 2,406 | 2020-04-22T15:47:54.000Z | 2022-03-31T10:27:37.000Z | ngraph/frontend/onnx/frontend/src/op/mean.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 4,948 | 2020-04-22T15:12:39.000Z | 2022-03-31T18:45:42.000Z | ngraph/frontend/onnx/frontend/src/op/mean.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 991 | 2020-04-23T18:21:09.000Z | 2022-03-31T18:40:57.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "op/mean.hpp"
#include "default_opset.hpp"
#include "utils/variadic.hpp"
namespace ngraph {
namespace onnx_import {
namespace op {
namespace set_1 {
OutputVector mean(const Node& node) {
auto sum = variadic::make_ng_variadic_op<default_opset::Add>(node).front();
auto count = default_opset::Constant::create(sum.get_element_type(), Shape{}, {node.get_ng_inputs().size()});
return {std::make_shared<default_opset::Divide>(sum, count)};
}
} // namespace set_1
} // namespace op
} // namespace onnx_import
} // namespace ngraph
| 23.035714 | 113 | 0.714729 | [
"shape"
] |
9087e7dfb21388291eb556b10d6853ab9978797f | 18,324 | cpp | C++ | Sim/SimpleFtl/SimpleFtl.cpp | DustParticle/SsdSim | 7a090e4b34dd194bbb1fe76d4565bbf03762aa1d | [
"MIT"
] | 4 | 2021-01-19T06:39:24.000Z | 2022-03-28T06:55:42.000Z | Sim/SimpleFtl/SimpleFtl.cpp | DustParticle/SsdSim | 7a090e4b34dd194bbb1fe76d4565bbf03762aa1d | [
"MIT"
] | null | null | null | Sim/SimpleFtl/SimpleFtl.cpp | DustParticle/SsdSim | 7a090e4b34dd194bbb1fe76d4565bbf03762aa1d | [
"MIT"
] | 8 | 2019-01-22T02:37:48.000Z | 2020-10-27T11:03:51.000Z | #include "SimpleFtl.h"
SimpleFtl::SimpleFtl() : _ProcessingCommand(nullptr)
{
_EventQueue = std::unique_ptr<boost::lockfree::queue<Event>>(new boost::lockfree::queue<Event>{ 1024 });
}
void SimpleFtl::SetProtocol(CustomProtocolHal* customProtocolHal)
{
SimpleFtl::_CustomProtocolHal = customProtocolHal;
}
void SimpleFtl::SetNandHal(NandHal* nandHal)
{
_NandHal = nandHal;
NandHal::Geometry geometry = _NandHal->GetGeometry();
SimpleFtlTranslation::SetGeometry(geometry);
}
void SimpleFtl::SetBufferHal(BufferHal* bufferHal)
{
_BufferHal = bufferHal;
SetSectorInfo(DefaultSectorInfo);
}
bool SimpleFtl::SetSectorInfo(const SectorInfo& sectorInfo)
{
if (_BufferHal->SetSectorInfo(sectorInfo) == false)
{
return false;
}
NandHal::Geometry geometry = _NandHal->GetGeometry();
_SectorsPerPage = geometry.BytesPerPage >> sectorInfo.SectorSizeInBit;
_TotalSectors = geometry.ChannelCount * geometry.DevicesPerChannel
* geometry.BlocksPerDevice * geometry.PagesPerBlock * _SectorsPerPage;
SimpleFtlTranslation::SetSectorSize(sectorInfo.SectorSizeInBit);
// The buffer size must be larger than MAX_CACHING_BLOCKS_PER_COMMAND blocks' size to support read-modify-write
auto blockSizeInBytes = geometry.PagesPerBlock * geometry.BytesPerPage;
assert(_BufferHal->GetBufferMaxSizeInBytes() >= blockSizeInBytes * MAX_PROCESSED_BLOCKS_PER_COMMAND);
_SectorsPerSegment = _SectorsPerPage;
_PagesPerBlock = geometry.PagesPerBlock;
_BufferHal->SetImplicitAllocationSectorCount(_SectorsPerSegment);
return true;
}
void SimpleFtl::operator()()
{
while (_EventQueue->empty() == false)
{
ProcessEvent();
}
}
void SimpleFtl::ProcessEvent()
{
Event event;
_EventQueue->pop(event);
switch (event.EventType)
{
case Event::Type::CustomProtocolCommand:
{
OnNewCustomProtocolCommand(event.EventParams.CustomProtocolCommand);
} break;
case Event::Type::TransferCompleted:
{
OnTransferCommandCompleted(event.EventParams.TransferCommand);
} break;
case Event::Type::NandCommandCompleted:
{
OnNandCommandCompleted(event.EventParams.NandCommand);
} break;
default:
{
assert(0);
}
}
}
void SimpleFtl::OnNewCustomProtocolCommand(CustomProtocolCommand* command)
{
// NOTE: only support for handling single command at a time
assert(_ProcessingCommand == nullptr);
// Set default command staus is Success
_ProcessingCommand = command;
command->CommandStatus = CustomProtocolCommand::Status::Success;
switch (command->Command)
{
case CustomProtocolCommand::Code::Write:
{
_RemainingSectorCount = command->Descriptor.SimpleFtlPayload.SectorCount;
_CurrentLba = command->Descriptor.SimpleFtlPayload.Lba;
_ProcessedSectorOffset = 0;
_PendingTransferCommandCount = 0;
_PendingNandCommandCount = 0;
_ProcessingBlockCount = 0;
// Write command to nand
OnNewWriteCommand();
} break;
case CustomProtocolCommand::Code::LoopbackWrite:
{
command->CommandStatus = CustomProtocolCommand::Status::Success;
SubmitResponse();
} break;
case CustomProtocolCommand::Code::Read:
{
// Read command from nand
_RemainingSectorCount = command->Descriptor.SimpleFtlPayload.SectorCount;
_CurrentLba = command->Descriptor.SimpleFtlPayload.Lba;
_ProcessedSectorOffset = 0;
_PendingTransferCommandCount = 0;
_PendingNandCommandCount = 0;
ReadNextLbas();
} break;
case CustomProtocolCommand::Code::LoopbackRead:
{
command->CommandStatus = CustomProtocolCommand::Status::Success;
SubmitResponse();
} break;
case CustomProtocolCommand::Code::GetDeviceInfo:
{
command->Descriptor.DeviceInfoPayload.TotalSector = _TotalSectors;
command->Descriptor.DeviceInfoPayload.SectorInfo = _BufferHal->GetSectorInfo();
command->Descriptor.DeviceInfoPayload.SectorsPerPage = _SectorsPerPage;
command->CommandStatus = CustomProtocolCommand::Status::Success;
SubmitResponse();
} break;
case CustomProtocolCommand::Code::SetSectorSize:
{
SectorInfo sectorInfo = command->Descriptor.SectorInfoPayload.SectorInfo;
if (SetSectorInfo(sectorInfo))
{
command->CommandStatus = CustomProtocolCommand::Status::Success;
}
else
{
command->CommandStatus = CustomProtocolCommand::Status::Failed;
}
SubmitResponse();
} break;
}
}
void SimpleFtl::ReadNextLbas()
{
Buffer buffer;
NandHal::NandAddress nandAddress;
U32 nextLba;
U32 remainingSectorCount;
while (_RemainingSectorCount > 0)
{
SimpleFtlTranslation::LbaToNandAddress(_CurrentLba, _RemainingSectorCount, nandAddress, nextLba, remainingSectorCount);
if (_BufferHal->AllocateBuffer(BufferType::User, buffer))
{
ReadPage(nandAddress, buffer, _ProcessedSectorOffset);
_ProcessedSectorOffset += nandAddress.SectorCount;
_CurrentLba = nextLba;
_RemainingSectorCount = remainingSectorCount;
}
else
{
break;
}
}
}
void SimpleFtl::TransferOut(const Buffer& buffer, const tSectorOffset& bufferOffset, const tSectorOffset& commandOffset, const tSectorCount& sectorCount)
{
CustomProtocolHal::TransferCommandDesc transferCommand;
transferCommand.Buffer = buffer;
transferCommand.BufferOffset = bufferOffset; //NOTE: if NAND sector and buffer sector ever differ, need a conversion
transferCommand.Command = _ProcessingCommand;
transferCommand.Direction = CustomProtocolHal::TransferCommandDesc::Direction::Out;
transferCommand.CommandOffset = commandOffset;
transferCommand.SectorCount = sectorCount;
transferCommand.Listener = this;
_CustomProtocolHal->QueueCommand(transferCommand);
++_PendingTransferCommandCount;
}
void SimpleFtl::ReadPage(const NandHal::NandAddress& nandAddress, const Buffer& outBuffer, const tSectorOffset& descSectorIndex)
{
assert((nandAddress.Sector + nandAddress.SectorCount) <= _SectorsPerPage);
NandHal::CommandDesc commandDesc;
commandDesc.Address = nandAddress;
commandDesc.Operation = (nandAddress.SectorCount == _SectorsPerPage)
? NandHal::CommandDesc::Op::Read : NandHal::CommandDesc::Op::ReadPartial;
commandDesc.Buffer = outBuffer;
commandDesc.BufferOffset = nandAddress.Sector; //NOTE: if NAND sector and buffer sector ever differ, need a conversion
commandDesc.DescSectorIndex = descSectorIndex;
commandDesc.Listener = this;
_NandHal->QueueCommand(commandDesc);
++_PendingNandCommandCount;
}
void SimpleFtl::OnNewWriteCommand()
{
NandHal::NandAddress processingPage;
U32 blockIndex;
while (_RemainingSectorCount > 0)
{
SimpleFtlTranslation::LbaToNandAddress(_CurrentLba, _RemainingSectorCount,
processingPage, _CurrentLba, _RemainingSectorCount);
if (true == IsNewBlock(processingPage))
{
// Allocate a large buffer for the whole block
blockIndex = _ProcessingBlockCount;
++_ProcessingBlockCount;
_ProcessingBlocks[blockIndex] = processingPage;
bool success = _BufferHal->AllocateBuffer(BufferType::User, _PagesPerBlock * _SectorsPerPage,
_ProcessingBlockBuffers[blockIndex]);
assert(success == true); // MUST success
// New block to be written
// Read head pages/sectors of this block into buffer
ReadHeadPages(processingPage, blockIndex);
}
else
{
blockIndex = GetBlockIndex(processingPage);
}
// Transfer data from current lba to page
TransferIn(GetSubBuffer(blockIndex, processingPage), tSectorOffset{ processingPage.Sector }, _ProcessedSectorOffset, processingPage.SectorCount);
_ProcessingBlocks[blockIndex] = processingPage;
}
// Read all tail pages/sectors of the writing blocks
for (U32 i = 0; i < _ProcessingBlockCount; ++i)
{
ReadTailPages(_ProcessingBlocks[i], i);
}
}
void SimpleFtl::OnNandReadAndTransferCompleted()
{
if (0 == _PendingNandCommandCount && 0 == _PendingTransferCommandCount)
{
// All read commands and transfer command are completed
// All data are in buffers
// Submit erase command
for (U32 i = 0; i < _ProcessingBlockCount; ++i)
{
EraseBlock(_ProcessingBlocks[i]);
}
}
}
void SimpleFtl::OnNandEraseCompleted()
{
if (0 == _PendingNandCommandCount)
{
// All blocks are erased
// Submit write data from buffers to erased blocks
U32 index = 0;
NandHal::NandAddress address;
for (U32 i = 0; i < _ProcessingBlockCount; ++i)
{
address = _ProcessingBlocks[i];
address.Sector = 0;
address.SectorCount = _SectorsPerPage;
for (address.Page = 0; address.Page < _PagesPerBlock; ++address.Page)
{
WritePage(address, GetSubBuffer(i, address));
}
}
}
}
void SimpleFtl::ReadHeadPages(const NandHal::NandAddress& writingStartingPage, const U32& blockIndex)
{
NandHal::NandAddress nandAddress = writingStartingPage;
// Read head pages of the starting block
nandAddress.Page = 0;
nandAddress.Sector = 0;
nandAddress.SectorCount = _SectorsPerPage;
for (; nandAddress.Page < writingStartingPage.Page; ++nandAddress.Page)
{
ReadPage(nandAddress, GetSubBuffer(blockIndex, nandAddress), tSectorOffset{ 0 });
}
// Transfer data from host
// First writing page
// Read head sectors of the page
if (writingStartingPage.Sector > 0)
{
// Starting LBA doesn't align to a page. Starting page has head sectors.
// Read head sectors of the page
nandAddress.Sector = 0;
nandAddress.SectorCount = writingStartingPage.Sector;
ReadPage(nandAddress, GetSubBuffer(blockIndex, nandAddress), tSectorOffset{ 0 });
}
}
void SimpleFtl::ReadTailPages(const NandHal::NandAddress& writingEndingPage, const U32& blockIndex)
{
NandHal::NandAddress nandAddress = writingEndingPage;
U32 tailStartingSector = writingEndingPage.Sector + writingEndingPage.SectorCount;
if (tailStartingSector < _SectorsPerPage)
{
// Ending LBA doesn't align to a page. Ending page has tail sectors.
// Read tail sectors of the page
nandAddress.Sector = tailStartingSector;
nandAddress.SectorCount = _SectorsPerPage - tailStartingSector;
ReadPage(nandAddress, GetSubBuffer(blockIndex, nandAddress), tSectorOffset{ tailStartingSector });
}
// Read tail pages of the writing block
++nandAddress.Page;
nandAddress.Sector = 0;
nandAddress.SectorCount = _SectorsPerPage;
for (; nandAddress.Page < _PagesPerBlock; ++nandAddress.Page)
{
ReadPage(nandAddress, GetSubBuffer(blockIndex, nandAddress), tSectorOffset{ 0 });
}
}
bool SimpleFtl::IsSameBlock(const NandHal::NandAddress& nandAddress1, const NandHal::NandAddress& nandAddress2)
{
return (nandAddress1.Channel == nandAddress2.Channel)
&& (nandAddress1.Device == nandAddress2.Device)
&& (nandAddress1.Block == nandAddress2.Block);
}
bool SimpleFtl::IsNewBlock(const NandHal::NandAddress& nandAddress)
{
for (U32 i = 0; i < _ProcessingBlockCount; ++i)
{
if (IsSameBlock(nandAddress, _ProcessingBlocks[i]))
{
return false;
}
}
return true;
}
U32 SimpleFtl::GetBlockIndex(const NandHal::NandAddress& nandAddress)
{
for (U32 i = 0; i < _ProcessingBlockCount; ++i)
{
if (IsSameBlock(nandAddress, _ProcessingBlocks[i]))
{
return i;
}
}
assert(false);
return -1;
}
Buffer SimpleFtl::GetSubBuffer(const U32& blockIndex, const NandHal::NandAddress& nandAddress)
{
assert(_ProcessingBlockCount > blockIndex);
Buffer buffer = _ProcessingBlockBuffers[blockIndex];
buffer.SubBufferOffset = nandAddress.Page * _SectorsPerPage; // Set the corresponding SubBufferOffset for the page
return buffer;
}
void SimpleFtl::TransferIn(const Buffer& buffer, const tSectorOffset& bufferOffset, const tSectorOffset& commandOffset, const tSectorCount& sectorCount)
{
CustomProtocolHal::TransferCommandDesc transferCommand;
transferCommand.Buffer = buffer;
transferCommand.BufferOffset = bufferOffset; //NOTE: if NAND sector and buffer sector ever differ, need a conversion
transferCommand.Command = _ProcessingCommand;
transferCommand.Direction = CustomProtocolHal::TransferCommandDesc::Direction::In;
transferCommand.CommandOffset = commandOffset;
transferCommand.SectorCount = sectorCount;
transferCommand.Listener = this;
_CustomProtocolHal->QueueCommand(transferCommand);
_ProcessedSectorOffset += sectorCount;
++_PendingTransferCommandCount;
}
void SimpleFtl::WritePage(const NandHal::NandAddress& nandAddress, const Buffer& inBuffer)
{
assert((nandAddress.Sector + nandAddress.SectorCount) <= _SectorsPerPage);
NandHal::CommandDesc commandDesc;
commandDesc.Address = nandAddress;
commandDesc.Operation = (nandAddress.SectorCount == _SectorsPerPage)
? NandHal::CommandDesc::Op::Write : NandHal::CommandDesc::Op::WritePartial;
commandDesc.Buffer = inBuffer;
commandDesc.BufferOffset = nandAddress.Sector; //NOTE: if NAND sector and buffer sector ever differ, need a conversion
commandDesc.Listener = this;
_NandHal->QueueCommand(commandDesc);
++_PendingNandCommandCount;
}
void SimpleFtl::EraseBlock(const NandHal::NandAddress& nandAddress)
{
NandHal::CommandDesc commandDesc;
commandDesc.Address = nandAddress;
commandDesc.Operation = NandHal::CommandDesc::Op::Erase;
commandDesc.Listener = this;
_NandHal->QueueCommand(commandDesc);
++_PendingNandCommandCount;
}
void SimpleFtl::OnTransferCommandCompleted(const CustomProtocolHal::TransferCommandDesc& command)
{
if (CustomProtocolCommand::Code::Read == _ProcessingCommand->Command)
{
_BufferHal->DeallocateBuffer(command.Buffer);
--_PendingTransferCommandCount;
if (_RemainingSectorCount == 0 && _PendingTransferCommandCount == 0 && _PendingNandCommandCount == 0)
{
SubmitResponse();
}
else
{
ReadNextLbas();
}
}
else
{
--_PendingTransferCommandCount;
OnNandReadAndTransferCompleted();
}
}
void SimpleFtl::OnNandCommandCompleted(const NandHal::CommandDesc& command)
{
if (CustomProtocolCommand::Code::Read == _ProcessingCommand->Command)
{
TransferOut(command.Buffer, tSectorOffset{ command.Address.Sector }, command.DescSectorIndex, command.Address.SectorCount);
--_PendingNandCommandCount;
if (NandHal::CommandDesc::Status::Success != command.CommandStatus)
{
_ProcessingCommand->CommandStatus = CustomProtocolCommand::Status::ReadError;
}
}
else
{
if (NandHal::CommandDesc::Op::Read == command.Operation
|| NandHal::CommandDesc::Op::ReadPartial == command.Operation)
{
--_PendingNandCommandCount;
OnNandReadAndTransferCompleted();
}
else if (NandHal::CommandDesc::Op::Erase == command.Operation)
{
--_PendingNandCommandCount;
OnNandEraseCompleted();
}
else if (NandHal::CommandDesc::Op::Write == command.Operation)
{
if (NandHal::CommandDesc::Status::Success != command.CommandStatus)
{
_ProcessingCommand->CommandStatus = CustomProtocolCommand::Status::WriteError;
}
--_PendingNandCommandCount;
if (_RemainingSectorCount == 0 && _PendingNandCommandCount == 0 && _PendingTransferCommandCount == 0)
{
// Release all buffers
for (U32 i = 0; i < _ProcessingBlockCount; ++i)
{
_BufferHal->DeallocateBuffer(_ProcessingBlockBuffers[i]);
}
SubmitResponse();
}
}
}
}
void SimpleFtl::SubmitCustomProtocolCommand(CustomProtocolCommand* command)
{
Event event;
event.EventType = Event::Type::CustomProtocolCommand;
event.EventParams.CustomProtocolCommand = command;
_EventQueue->push(event);
}
void SimpleFtl::HandleCommandCompleted(const CustomProtocolHal::TransferCommandDesc& command)
{
Event event;
event.EventType = Event::Type::TransferCompleted;
event.EventParams.TransferCommand = command;
assert(_EventQueue->push(event) == true);
}
void SimpleFtl::HandleCommandCompleted(const NandHal::CommandDesc& command)
{
Event event;
event.EventType = Event::Type::NandCommandCompleted;
event.EventParams.NandCommand = command;
assert(_EventQueue->push(event) == true);
}
bool SimpleFtl::IsProcessingCommand()
{
return (nullptr != _ProcessingCommand);
}
void SimpleFtl::SubmitResponse()
{
assert(_ProcessingCommand != nullptr);
_CustomProtocolHal->SubmitResponse(_ProcessingCommand);
_ProcessingCommand = nullptr;
} | 34.770398 | 154 | 0.657389 | [
"geometry"
] |
9090889e3eeb35fdacf0f3f2e220b87566a3b8ee | 2,604 | hpp | C++ | include/AnnLevelManager.hpp | Ybalrid/Annwvyn | 30d63c722524c35a9054d51dcdd9f39af0599a3d | [
"MIT"
] | 39 | 2015-04-02T15:32:19.000Z | 2022-03-26T12:48:28.000Z | include/AnnLevelManager.hpp | Ybalrid/Annwvyn | 30d63c722524c35a9054d51dcdd9f39af0599a3d | [
"MIT"
] | 136 | 2015-02-24T19:45:59.000Z | 2019-02-21T15:01:12.000Z | include/AnnLevelManager.hpp | Ybalrid/Annwvyn | 30d63c722524c35a9054d51dcdd9f39af0599a3d | [
"MIT"
] | 12 | 2015-02-24T19:37:38.000Z | 2019-05-13T12:07:26.000Z | /**
* \file AnnLevelManager.hpp
* \brief Main class of the level system
* The Level Manager load and unload levels from the internal Ogre Scene.
* It also permit to switchToLevel from a level to another one.
* \author A. Brainville (Ybalrid)
*/
#pragma once
#include <vector>
#include "AnnLevel.hpp"
#include "AnnSubsystem.hpp"
#include "AnnGameObject.hpp"
namespace Annwvyn
{
using AnnLevelID = size_t;
///Class that take care of switching between different levels dynamically and clearing the memory afterwards
class AnnDllExport AnnLevelManager : public AnnSubSystem
{
public:
///Construct LevelManager
AnnLevelManager();
///Destroy the level manager
~AnnLevelManager();
///Jump to an index referenced level
///\param levelId Index of the level in the order they have been declared
void switchToLevel(AnnLevelID levelId);
///Jump to a pointer referenced level
///\param level address of a subclass instance of AnnLevel
void switchToLevel(AnnLevelPtr level);
///Add a level to the level manager
///\param level address of a subclass instance of AnnLevel
void addLevel(AnnLevelPtr level);
///Uitility overload to easilly create and add levels at the same time
template <class LevelType, class... Args>
decltype(auto) addLevel(Args&&... args)
{
auto level = std::make_shared<LevelType>(args...);
addLevel(level);
return level;
}
///Jump to the first level that was loaded into the engine
void switchToFirstLoadedLevel();
///Jump to the first level that was loaded into the engine
void switchToLastLoadedLevel();
///Run level logic
void update() override;
///Unload the level currently running
void unloadCurrentLevel();
///Retrieve the last loaded level pointer
AnnLevelPtr getLastLoadedLevel();
///Retrieve the first loaded level pointer
AnnLevelPtr getFirstLoadedLevel();
///Retrieve the `id`th loaded level pointer
AnnLevelPtr getLevelByIndex(AnnLevelID id);
///Get the current level
AnnLevelPtr getCurrentLevel() const;
///Add an orphan object to the current level
void addToCurrentLevel(AnnGameObjectPtr obj) const;
///Remove an object from the current level (make it orphan)
void removeFromCurrentLevel(AnnGameObjectPtr obj) const;
private:
///List of levels
std::vector<AnnLevelPtr> loadedLevels;
///Address to the currently running level
AnnLevelPtr current;
///Will jumpt to a level at next update
bool jumpRequested;
///Level to switchToLevel to at next update
AnnLevelID jumpTo;
};
using AnnLevelManagerPtr = std::shared_ptr<AnnLevelManager>;
}
| 27.125 | 109 | 0.739247 | [
"object",
"vector"
] |
909126e1846e9c696f85759eeb81ee787426641f | 7,899 | hxx | C++ | main/sax/source/fastparser/fastparser.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sax/source/fastparser/fastparser.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sax/source/fastparser/fastparser.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _SAX_FASTPARSER_HXX_
#define _SAX_FASTPARSER_HXX_
#include <vector>
#include <stack>
#include <hash_map>
#include <boost/shared_ptr.hpp>
#include <rtl/ref.hxx>
#include <com/sun/star/xml/sax/XFastParser.hpp>
#include <com/sun/star/xml/sax/XFastTokenHandler.hpp>
#include <com/sun/star/xml/sax/XFastDocumentHandler.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <cppuhelper/implbase2.hxx>
#include <expat.h>
#include "xml2utf.hxx"
#include <sax/fastattribs.hxx>
#define PARSER_IMPLEMENTATION_NAME "com.sun.star.comp.extensions.xml.sax.FastParser"
#define PARSER_SERVICE_NAME "com.sun.star.xml.sax.FastParser"
namespace sax_fastparser {
class FastLocatorImpl;
struct NamespaceDefine;
struct SaxContextImpl;
typedef ::boost::shared_ptr< SaxContextImpl > SaxContextImplPtr;
typedef ::boost::shared_ptr< NamespaceDefine > NamespaceDefineRef;
typedef ::std::hash_map< ::rtl::OUString, sal_Int32,
::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > NamespaceMap;
// --------------------------------------------------------------------
struct ParserData
{
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastDocumentHandler > mxDocumentHandler;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastTokenHandler > mxTokenHandler;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XErrorHandler > mxErrorHandler;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XEntityResolver > mxEntityResolver;
::com::sun::star::lang::Locale maLocale;
ParserData();
~ParserData();
};
// --------------------------------------------------------------------
// Entity binds all information needed for a single file
struct Entity : public ParserData
{
::com::sun::star::xml::sax::InputSource maStructSource;
XML_Parser mpParser;
::sax_expatwrap::XMLFile2UTFConverter maConverter;
::rtl::Reference< FastAttributeList > mxAttributes;
// Exceptions cannot be thrown through the C-XmlParser (possible resource leaks),
// therefore the exception must be saved somewhere.
::com::sun::star::uno::Any maSavedException;
::std::stack< SaxContextImplPtr > maContextStack;
::std::vector< NamespaceDefineRef > maNamespaceDefines;
explicit Entity( const ParserData& rData );
~Entity();
};
// --------------------------------------------------------------------
// This class implements the external Parser interface
class FastSaxParser : public ::cppu::WeakImplHelper2< ::com::sun::star::xml::sax::XFastParser, ::com::sun::star::lang::XServiceInfo >
{
public:
FastSaxParser();
virtual ~FastSaxParser();
// The implementation details
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void);
// XFastParser
virtual void SAL_CALL parseStream( const ::com::sun::star::xml::sax::InputSource& aInputSource ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setFastDocumentHandler( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastDocumentHandler >& Handler ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTokenHandler( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastTokenHandler >& Handler ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL registerNamespace( const ::rtl::OUString& NamespaceURL, sal_Int32 NamespaceToken ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setErrorHandler( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XErrorHandler >& Handler ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setEntityResolver( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XEntityResolver >& Resolver ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setLocale( const ::com::sun::star::lang::Locale& rLocale ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);
// called by the C callbacks of the expat parser
void callbackStartElement( const XML_Char* name, const XML_Char** atts );
void callbackEndElement( const XML_Char* name );
void callbackCharacters( const XML_Char* s, int nLen );
int callbackExternalEntityRef( XML_Parser parser, const XML_Char *openEntityNames, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId);
inline void pushEntity( const Entity& rEntity ) { maEntities.push( rEntity ); }
inline void popEntity() { maEntities.pop(); }
Entity& getEntity() { return maEntities.top(); }
private:
void parse();
sal_Int32 GetToken( const ::rtl::OString& rToken );
sal_Int32 GetToken( const sal_Char* pToken, sal_Int32 nTokenLen = 0 );
sal_Int32 GetTokenWithPrefix( const ::rtl::OString& rPrefix, const ::rtl::OString& rName ) throw (::com::sun::star::xml::sax::SAXException);
sal_Int32 GetTokenWithPrefix( const sal_Char*pPrefix, int nPrefixLen, const sal_Char* pName, int nNameLen ) throw (::com::sun::star::xml::sax::SAXException);
::rtl::OUString GetNamespaceURL( const ::rtl::OString& rPrefix ) throw (::com::sun::star::xml::sax::SAXException);
::rtl::OUString GetNamespaceURL( const sal_Char*pPrefix, int nPrefixLen ) throw (::com::sun::star::xml::sax::SAXException);
sal_Int32 GetNamespaceToken( const ::rtl::OUString& rNamespaceURL );
sal_Int32 GetTokenWithNamespaceURL( const ::rtl::OUString& rNamespaceURL, const sal_Char* pName, int nNameLen );
void DefineNamespace( const ::rtl::OString& rPrefix, const sal_Char* pNamespaceURL );
sal_Int32 CreateCustomToken( const sal_Char* pToken, int len = 0 );
void pushContext();
void popContext();
void splitName( const XML_Char *pwName, const XML_Char *&rpPrefix, sal_Int32 &rPrefixLen, const XML_Char *&rpName, sal_Int32 &rNameLen );
private:
::osl::Mutex maMutex;
::rtl::Reference< FastLocatorImpl > mxDocumentLocator;
NamespaceMap maNamespaceMap;
ParserData maData; /// Cached parser configuration for next call of parseStream().
::std::stack< Entity > maEntities; /// Entity stack for each call of parseStream().
};
}
#endif // _SAX_FASTPARSER_HXX_
| 49.062112 | 226 | 0.675275 | [
"vector"
] |
90927b189fc058b60301374adabdc891bde639f0 | 53,597 | cpp | C++ | hi_scripting/scripting/api/DspUnitTests.cpp | jukea/HISE | 9e867c746d48f24c7fe6fdedad801ecafa3481e6 | [
"Intel"
] | null | null | null | hi_scripting/scripting/api/DspUnitTests.cpp | jukea/HISE | 9e867c746d48f24c7fe6fdedad801ecafa3481e6 | [
"Intel"
] | null | null | null | hi_scripting/scripting/api/DspUnitTests.cpp | jukea/HISE | 9e867c746d48f24c7fe6fdedad801ecafa3481e6 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE 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.
*
* HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
#include "AppConfig.h"
#if HI_RUN_UNIT_TESTS
#include "JuceHeader.h"
#include <ipp.h>
using namespace hise;
class DspUnitTests : public UnitTest
{
public:
DspUnitTests():
UnitTest("Testing Scripting DSP classes")
{
}
void runTest() override
{
testVariantBuffer();
testVariantBufferWithCorruptValues();
testDspInstances();
testCircularBuffers();
}
void testCircularBuffers()
{
beginTest("Testing circular audio buffers");
int numSamples = r.nextInt({ 258, 512 });
AudioSampleBuffer input(1, numSamples);
fillFloatArrayWithRandomNumbers(input.getWritePointer(0), numSamples);
AudioSampleBuffer output(1, numSamples);
CircularAudioSampleBuffer b(1, 1024);
expectEquals<int>(b.getNumAvailableSamples(), 0, "Num Samples available");
b.writeSamples(input, 0, numSamples);
expectEquals<int>(b.getNumAvailableSamples(), numSamples, "Num Samples available");
b.readSamples(output, 0, numSamples);
expectEquals<int>(b.getNumAvailableSamples(), 0, "Num Samples available");
expect(checkBuffersEqual(input, output), "Basic Read/Write operation");
beginTest("Testing MIDI circular Buffers");
CircularAudioSampleBuffer mb(1, 1024);
testMidiWrite(mb, 1000, 600);
testMidiWrite(mb, 1000, 600);
testMidiWrite(mb, r.nextInt({ 0, 512 }));
testMidiWrite(mb, r.nextInt({ 0, 512 }));
testMidiWrite(mb, r.nextInt({ 0, 512 }));
testMidiWrite(mb, r.nextInt({ 0, 512 }));
testMidiWrite(mb, r.nextInt({ 0, 512 }));
testMidiWrite(mb, r.nextInt({ 0, 512 }));
}
void testMidiWrite(CircularAudioSampleBuffer& mb, int numThisTime, int timeStamp=-1)
{
MidiBuffer mInput;
MidiBuffer mOutput;
if(timeStamp == -1)
timeStamp = r.nextInt({ 0, numThisTime });
const int noteNumber = r.nextInt({ 0, 127 });
String s;
s << "Buffersize: " << numThisTime << ", Timestamp: " << timeStamp << ", NoteNumber: " << noteNumber;
logMessage(s);
mInput.addEvent(MidiMessage::noteOn(1, noteNumber, 1.0f), timeStamp);
mb.writeMidiEvents(mInput, 0, numThisTime);
mb.readMidiEvents(mOutput, 0, numThisTime);
MidiBuffer::Iterator iter(mOutput);
MidiMessage m;
int pos;
iter.getNextEvent(m, pos);
jassert(timeStamp == pos);
expect(m.getNoteNumber() == noteNumber, "Wrong event.");
expectEquals<int>(pos, timeStamp, "Wrong timestamp.");
expect(mb.getNumMidiEvents() == 0, "Buffer should be empty. Size: " + String(mb.getNumMidiEvents()));
}
void testVariantBuffer()
{
beginTest("Testing VariantBuffer class");
VariantBuffer b(256);
expectEquals<int>(b.buffer.getNumSamples(), 256, "VariantBuffer size");
expectEquals<int>(b.size, 256, "VariantBuffer size 2");
for (int i = 0; i < 256; i++)
{
expect((float)b.getSample(i) == 0.0f, "Clear sample at index " + String(i));
expect(b.buffer.getSample(0, i) == 0.0f, "Clear sample at index " + String(i));
}
float otherData[128];
fillFloatArrayWithRandomNumbers(otherData, 128);
b.referToData(otherData, 128);
for (int i = 0; i < 128; i++)
{
expectEquals<float>(otherData[i], b[i], "Sample at index " + String(i));
}
beginTest("Starting VariantBuffer operators");
const float random1 = r.nextFloat();
random1 >> b;
for (int i = 0; i < b.size; i++)
{
expectEquals<float>(b[i], random1, "Testing fill operator");
}
}
void testDspInstances()
{
DspFactory::Handler handler;
DspFactory::Handler::registerStaticFactory<HiseCoreDspFactory>(&handler);
DspFactory* coreFactory = handler.getFactory("core", "");
expect(coreFactory != nullptr, "Creating the core factory");
var sm = coreFactory->createModule("stereo");
DspInstance* stereoModule = dynamic_cast<DspInstance*>(sm.getObject());
expect(stereoModule != nullptr, "Stereo Module creation");
VariantBuffer::Ptr lData = new VariantBuffer(256);
VariantBuffer::Ptr rData = new VariantBuffer(256);
Array<var> channels;
channels.add(var(lData));
channels.add(var(rData));
try
{
stereoModule->processBlock(channels);
}
catch (String message)
{
expectEquals<String>(message, "stereo: prepareToPlay must be called before processing buffers.");
}
}
void testVariantBufferWithCorruptValues()
{
VariantBuffer b(6);
b.setSample(0, INFINITY);
b.setSample(1, FLT_MIN / 20.0f);
b.setSample(2, FLT_MIN / -14.0f);
b.setSample(3, NAN);
b.setSample(4, 24.0f);
b.setSample(5, 0.0052f);
expectEquals<float>(b[0], 0.0f, "Storing Infinity");
expectEquals<float>(b[1], 0.0f, "Storing Denormal");
expectEquals<float>(b[2], 0.0f, "Storing Negative Denormal");
expectEquals<float>(b[3], 0.0f, "Storing NaN");
expectEquals<float>(b[4], 24.0f, "Storing Normal Number");
expectEquals<float>(b[5], 0.0052f, "Storing Small Number");
1.0f >> b;
b * INFINITY;
expectEquals<float>(b.getSample(0), 0.0f, "Multiplying with infinity");
1.0f >> b;
b * (FLT_MIN / 20.0f);
expectEquals<float>(b.getSample(0), 0.0f, "Multiplying with positive denormal");
1.0f >> b;
b * (FLT_MIN / -14.0f);
expectEquals<float>(b.getSample(0), 0.0f, "Multiplying with negative denormal");
1.0f >> b;
b * NAN;
expectEquals<float>(b.getSample(0), 0.0f, "Multiplying with NaN");
VariantBuffer a(6);
float* aData = a.buffer.getWritePointer(0);
aData[0] = INFINITY;
aData[1] = FLT_MIN / 20.0f;
aData[2] = FLT_MIN / -14.0f;
aData[3] = NAN;
aData[4] = 24.0f;
aData[5] = 0.0052f;
a >> b;
expectEquals<float>(b[0], 0.0f, "Copying Infinity");
expectEquals<float>(b[1], 0.0f, "Copying Denormal");
expectEquals<float>(b[2], 0.0f, "Copying Negative Denormal");
expectEquals<float>(b[3], 0.0f, "Copying NaN");
expectEquals<float>(b[4], 24.0f, "Copying Normal Number");
expectEquals<float>(b[5], 0.0052f, "Copying Small Number");
}
void fillFloatArrayWithRandomNumbers(float *data, int numSamples)
{
for (int i = 0; i < numSamples; i++)
{
data[i] = r.nextFloat();
}
}
bool checkBuffersEqual(const AudioSampleBuffer& first, const AudioSampleBuffer& second)
{
if (first.getNumSamples() != second.getNumSamples())
return false;
auto r1 = first.getReadPointer(0);
auto r2 = second.getReadPointer(0);
for (int i = 0; i < first.getNumSamples(); i++)
{
if (fabsf(*r2 - *r1) > 0.0001f)
return false;
r1++;
r2++;
}
return true;
}
Random r;
};
static DspUnitTests dspUnitTest;
constexpr int sampleRate = 44100;
class ModulationTests : public UnitTest
{
public:
using ScopedProcessor = ScopedPointer<BackendProcessor>;
ModulationTests() :
UnitTest("Modulation Tests")
{
}
void runTest() override
{
runBasicTest();
}
private:
void runBasicTest()
{
ScopedValueSetter<bool> s(MainController::unitTestMode, true);
testResuming(false);
testResuming(true);
testSimpleEnvelopeWithoutAttack(true);
testSimpleEnvelopeWithoutAttack(false);
testSimpleEnvelopeWithAttack(false);
testSimpleEnvelopeWithAttack(true);
testAhdsrSustain(true);
testAhdsrSustain(false);
testConstantModulator(false);
testConstantModulator(true);
testLFOSeq(false);
testLFOSeq(true);
testModulatorCombo(false);
testModulatorCombo(true);
testPanModulation(false);
testPanModulation(true);
testSynthGroup();
testGlobalModulators(false);
testGlobalModulators(true);
testGlobalModulatorIntensity(false);
testGlobalModulatorIntensity(true);
testScriptPitchFade(false);
testScriptPitchFade(true);
}
void testPanModulation(bool useGroup)
{
beginTestWithOptionalGroup("Testing pan modulation ", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
auto effect = Helpers::addVoiceEffectToOptionalGroup<StereoEffect>(bp);
auto lfo = Helpers::addTimeModulator<StereoEffect, LfoModulator>(bp, 0);
Helpers::setLfoToDefaultSquare(lfo);
// Process
auto testData = Helpers::createTestDataWithOneSecondNote(1024);
Helpers::process(bp, testData, 512);
// Tests
expect(testData.isWithinErrorRange(10000, sqrtf(2.0f), 0), "Left channel 1");
expect(testData.isWithinErrorRange(10000, 0.0f, 1), "Right channel 1");
expect(testData.isWithinErrorRange(15000, 0.0f, 0), "Left channel 2");
expect(testData.isWithinErrorRange(15000, sqrtf(2.0f), 1), "Left channel 2");
bp = nullptr;
}
void testScriptPitchFade(bool useGroup)
{
beginTestWithOptionalGroup("Testing script pitch fade", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DiracTrain, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
auto pitchFade = HiseEvent::createPitchFade(1, 1000, 12, 0);
const String pitchMidiProcessor = R"(function onNoteOn(){Synth.addPitchFade(Message.getEventId(),500,12,0);})" \
R"(function onNoteOff(){}function onController(){}function onTimer(){}function onControl(number, value){})";
auto jp = new JavascriptMidiProcessor(bp, "scripter");
auto mpc = dynamic_cast<MidiProcessorChain*>(bp->getMainSynthChain()->getChildProcessor(ModulatorSynth::MidiProcessor));
jp->setOwnerSynth(bp->getMainSynthChain());
jp->parseSnippetsFromString(pitchMidiProcessor, true);
mpc->getHandler()->add(jp, nullptr);
// Process
auto testData = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData, 512);
Helpers::DiracIterator di(testData.audioBuffer, 0, false);
expectResult(di.scan(), "Dirac scan");
auto& data = di.getData();
expectResult(data.matchesStartAndEnd(256, 128), "Start and end");
expectResult(data.isWithinRange({ 128, 256 }), "Outside range");
// Tests
bp = nullptr;
}
void testGlobalModulatorIntensity(bool useGroup)
{
beginTestWithOptionalGroup("Testing global modulator intensity ", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 10.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 20.0f);
// Setup
Helpers::addGlobalContainer(bp, useGroup);
auto sender = Helpers::addTimeModulator<GlobalModulatorContainer, ControlModulator>(bp, ModulatorSynth::GainModulation);
auto receiver = Helpers::addTimeModulatorToOptionalGroup<GlobalTimeVariantModulator>(bp, ModulatorSynth::GainModulation);
auto checkMod = Helpers::addTimeModulatorToOptionalGroup<ControlModulator>(bp, ModulatorSynth::GainModulation);
bp->prepareToPlay(sampleRate, 512);
sender->setAttribute(ControlModulator::SmoothTime, 0.0f, dontSendNotification);
sender->setAttribute(ControlModulator::DefaultValue, 0.0f, dontSendNotification);
sender->setIntensity(0.75f);
checkMod->setAttribute(ControlModulator::SmoothTime, 0.0f, dontSendNotification);
checkMod->setAttribute(ControlModulator::DefaultValue, 0.0f, dontSendNotification);
checkMod->setIntensity(0.75f);
receiver->setBypassed(true);
checkMod->setBypassed(true);
receiver->connectToGlobalModulator("Container:" + sender->getId());
expect(receiver->isConnected(), "Connection failed");
// Process
receiver->setBypassed(true);
checkMod->setBypassed(false);
Random r;
const int startOffset = r.nextInt(4096);
const int stopOffset = r.nextInt({ 8192, 32768 });
const float nextIntensity = r.nextFloat();
auto testData = Helpers::createTestDataWithOneSecondNote(startOffset, stopOffset);
Helpers::process(bp, testData, 512, 16384);
checkMod->setIntensity(nextIntensity);
Helpers::resumeProcessing(bp, testData, 512, -1, 16384);
receiver->setBypassed(false);
checkMod->setBypassed(true);
auto testData2 = Helpers::createTestDataWithOneSecondNote(startOffset, stopOffset);
Helpers::process(bp, testData2, 512, 16384);
sender->setIntensity(nextIntensity);
Helpers::resumeProcessing(bp, testData2, 512, -1, 16384);
// Tests
expect(testData == testData2, "Compare static intensity");
bp = nullptr;
}
void testGlobalModulators(bool useGroup)
{
beginTestWithOptionalGroup("Testing global modulators", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DiracTrain, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
Helpers::addGlobalContainer(bp, useGroup);
auto sender = Helpers::addVoiceModulator<GlobalModulatorContainer, VelocityModulator>(bp, ModulatorSynth::GainModulation);
auto receiver = Helpers::addVoiceModulatorToOptionalGroup<GlobalVoiceStartModulator>(bp, ModulatorSynth::GainModulation);
receiver->connectToGlobalModulator("Container:" + sender->getId());
expect(receiver->isConnected(), "Connection failed");
// Process
auto testData = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData, 512);
// Tests
bp = nullptr;
}
void testSynthGroup()
{
beginTest("Testing SynthGroup modulators");
// Init
ScopedProcessor bp = Helpers::createAndInitialiseProcessorWithGroup(NoiseSynth::DiracTrain);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
auto group = ProcessorHelpers::getFirstProcessorWithType<ModulatorSynthGroup>(bp->getMainSynthChain());
group->setAttribute(ModulatorSynthGroup::SpecialParameters::UnisonoVoiceAmount, 2.0f, dontSendNotification);
group->setAttribute(ModulatorSynthGroup::SpecialParameters::UnisonoDetune, 6.0f, dontSendNotification);
auto sineSynth = new SineSynth(bp, "FM", NUM_POLYPHONIC_VOICES);
sineSynth->setAttribute(ModulatorSynth::Gain, 0.0f, dontSendNotification);
group->getHandler()->add(sineSynth, nullptr);
group->setAttribute(ModulatorSynthGroup::SpecialParameters::EnableFM, false, dontSendNotification);
group->setAttribute(ModulatorSynthGroup::SpecialParameters::CarrierIndex, 1, dontSendNotification);
group->setAttribute(ModulatorSynthGroup::SpecialParameters::ModulatorIndex, 2, dontSendNotification);
auto constantPitch = Helpers::addVoiceModulator<ModulatorSynthGroup, ConstantModulator>(bp, ModulatorSynth::PitchModulation);
const float pf = 1.5f;
auto npf = Modulation::PitchConverters::pitchFactorToNormalisedRange(pf);
constantPitch->setIntensity(npf);
// Process
const int offset = 128;
auto testData = Helpers::createTestDataWithOneSecondNote(offset);
Helpers::process(bp, testData, 512);
group->setAttribute(ModulatorSynthGroup::SpecialParameters::EnableFM, true, dontSendNotification);
expect(group->fmIsCorrectlySetup(), "FM not Working");
auto testData2 = Helpers::createTestDataWithOneSecondNote(offset);
Helpers::process(bp, testData2, 512);
// Test
expect(testData.isWithinErrorRange(offset, -1.0f, 0), "First sample left");
expect(testData.isWithinErrorRange(offset, -1.0f, 1), "First sample right");
float pitchFactorRight = pf * sqrtf(2.0f); // 6 semitones down
float pitchFactorLeft = 0.5f * pitchFactorRight;
const int leftNextDirac = offset + roundDoubleToInt(ceil(256.0 / pitchFactorLeft));
const int rightNextDirac = offset + roundDoubleToInt(ceil(256.0 / pitchFactorRight));
expect(testData.isWithinErrorRange(leftNextDirac - 1, 0.0f, 0), "leftNextDirac - 1");
expect(testData.isWithinErrorRange(rightNextDirac - 1, 0.0f, 1), "rightNextDirac - 1");
expect(testData.isWithinErrorRange(leftNextDirac, 1.0f, 0), "leftNextDirac + 1");
expect(testData.isWithinErrorRange(rightNextDirac, 1.0f, 1), "rightNextDirac - 1");
expect(testData.isWithinErrorRange(leftNextDirac + 1, 0.0f, 0), "leftNextDirac + 1");
expect(testData.isWithinErrorRange(rightNextDirac + 1, 0.0f, 1), "rightNextDirac - 1");
expect(testData == testData2, "Detune for FM");
bp = nullptr;
}
void testModulatorCombo(bool useGroup)
{
beginTestWithOptionalGroup("Test modulator combination", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
// Setup
const int attackSamples = 2048;
const float attackMs = (float)attackSamples / (float)sampleRate * 1000.0f;
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, attackMs);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 20.0f);
auto constantMod = Helpers::addVoiceModulatorToOptionalGroup<ConstantModulator>(bp, ModulatorSynth::GainModulation);
const float cModValue = 0.3f;
constantMod->setIntensity(cModValue);
auto lfoMod = Helpers::addTimeModulatorToOptionalGroup<LfoModulator>(bp, ModulatorSynth::GainModulation);
Helpers::setLfoToDefaultSquare(lfoMod);
const float lfoModValue = 0.25f;
lfoMod->setIntensity(lfoModValue);
const float gainFactorWhenLFO = (1.0f - cModValue) * (1.0f - lfoModValue);
const float gainFactorWhenNoLFO = (1.0f - cModValue);
// Process
auto testData = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData, 512);
// Test
expect(testData.isWithinErrorRange(0, 0.0f), "First sample");
float halfEnvelopeSample = 0.5f;
int halfEnvelopeIndex = attackSamples / 2;
expect(testData.isWithinErrorRange(halfEnvelopeIndex, halfEnvelopeSample * gainFactorWhenNoLFO), "Half Envelope");
float fullEnvelopeSample = 1.0f;
expect(testData.isWithinErrorRange(attackSamples, fullEnvelopeSample * gainFactorWhenNoLFO), "Full Envelope");
const int sampleIndexWhenNoLFO = 2205;
const int sampleIndexWhenLFO = 8802;
expect(testData.isWithinErrorRange(sampleIndexWhenLFO, fullEnvelopeSample * gainFactorWhenLFO), "LFO On");
expect(testData.isWithinErrorRange(sampleIndexWhenNoLFO, fullEnvelopeSample * gainFactorWhenNoLFO), "LFO Off");
}
void testResuming(bool useGroup)
{
beginTestWithOptionalGroup("Testing resuming", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
// Process
auto testData = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData, 512);
auto testData2 = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData2, 512, 16384);
Helpers::resumeProcessing(bp, testData2, 512, -1, 16384);
// Tests
expect(testData == testData2, "Resume OK");
bp = nullptr;
}
void testSimpleEnvelopeWithoutAttack(bool useGroup)
{
beginTestWithOptionalGroup("Testing simple envelope without attack", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DiracTrain, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
// Process
Random r;
const int stopOffset = r.nextInt({ 20000, 40000 });
logMessage("Offset: " + String(stopOffset));
auto testData = Helpers::createTestDataWithOneSecondNote(0, stopOffset);
Helpers::process(bp, testData, 512);
// Tests
expectEquals<float>(testData.audioBuffer.getSample(0, 0), -1.0f, "First Dirac doesn't match");
expectEquals<float>(testData.audioBuffer.getSample(0, 256), 1.0f, "Second Dirac doesn't match");
double rasterValue = (double)stopOffset / (double)HISE_CONTROL_RATE_DOWNSAMPLING_FACTOR;
int rasteredTimestamp = (int)(floor(rasterValue) * (double)HISE_CONTROL_RATE_DOWNSAMPLING_FACTOR);
auto diracBeforeNoteOff = (int)(floor((double)rasteredTimestamp / 256.0) * 256.0);
auto diracAfterNoteOff = diracBeforeNoteOff + 256;
expectEquals<float>(testData.audioBuffer.getSample(0, diracBeforeNoteOff), 1.0f, "Dirac before note off");
expectEquals<float>(testData.audioBuffer.getSample(0, diracAfterNoteOff), 0.0f, "Dirac after note off");
bp = nullptr;
}
void testSimpleEnvelopeWithAttack(bool useGroup)
{
beginTestWithOptionalGroup("Testing simple envelope without attack", useGroup);
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
auto testData = Helpers::createTestDataWithOneSecondNote();
float attackSamples = 512;
float attackMs = (float)attackSamples / (float)sampleRate * 1000.0f;
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, attackMs);
Helpers::process(bp, testData, 512);
expectEquals<float>(testData.audioBuffer.getSample(0, 0), 0, "First Dirac doesn't match");
expectEquals<float>(testData.audioBuffer.getSample(0, (int)attackSamples/2), 0.5f, "First Dirac doesn't match");
expectEquals<float>(testData.audioBuffer.getSample(0, (int)attackSamples), 1.0f, "First Dirac doesn't match");
}
void testConstantModulator(bool useGroup)
{
beginTestWithOptionalGroup("Testing constant modulator", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DiracTrain, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
// Gain Mod -> 0.5
// Pan Mod -> 25 R
// Pitch Mod -1 octave => 512 Dirac
const float balance = 0.25f;
const float gain = 0.5f;
auto constantGainMod = Helpers::addVoiceModulatorToOptionalGroup<ConstantModulator>(bp, ModulatorSynth::GainModulation);
auto constantPitchMod = Helpers::addVoiceModulatorToOptionalGroup<ConstantModulator>(bp, ModulatorSynth::PitchModulation);
auto stereoEffect = Helpers::addVoiceEffectToOptionalGroup<StereoEffect>(bp);
stereoEffect->setAttribute(StereoEffect::Pan, 100.0f, dontSendNotification);
auto constantPanMod = Helpers::addVoiceModulator<StereoEffect, ConstantModulator>(bp, StereoEffect::BalanceChain);
constantGainMod->setIntensity(gain);
constantPitchMod->setIntensityFromSlider(-12.0f);
constantPanMod->setIntensity(balance);
// Process
auto testData = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData, 512);
// Test
Helpers::DiracIterator di(testData.audioBuffer, 0, false);
di.scan();
di.dump(this);
Helpers::DiracIterator di2(testData.audioBuffer, 1, false);
di2.scan();
di2.dump(this);
auto expectedFirstValue = -1.0f;
auto gain_l = BalanceCalculator::getGainFactorForBalance(balance * 100, true) * gain;
auto gain_r = BalanceCalculator::getGainFactorForBalance(balance * 100, false) * gain;
expectResult(testData.isWithinErrorRange(0, expectedFirstValue * gain_l, 0), "Gain + Pan");
expectResult(testData.isWithinErrorRange(0, expectedFirstValue * gain_r, 1), "Gain + Pan");
auto expectedHalfValue = 0.0f;
expectResult(testData.isWithinErrorRange(256, expectedHalfValue, 0), "Test pitch");
expectResult(testData.isWithinErrorRange(256, expectedHalfValue, 1), "Test pitch");
auto expectedFullValue = 1.0f;
expectResult(testData.isWithinErrorRange(512, expectedFullValue * gain_l, 0), "Test pitch");
expectResult(testData.isWithinErrorRange(512, expectedFullValue * gain_r, 1), "Test pitch");
}
void testAhdsrSustain(bool useGroup)
{
beginTestWithOptionalGroup("Testing AHDSR envelope sustain value", useGroup);
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
Helpers::get<SimpleEnvelope>(bp)->setBypassed(true);
Helpers::addVoiceModulatorToOptionalGroup<AhdsrEnvelope>(bp, ModulatorSynth::GainModulation);
const float sustainLevel = 0.25f;
Helpers::setAttribute<AhdsrEnvelope>(bp, AhdsrEnvelope::Attack, 0.0f);
Helpers::setAttribute<AhdsrEnvelope>(bp, AhdsrEnvelope::Hold, 0.0f);
Helpers::setAttribute<AhdsrEnvelope>(bp, AhdsrEnvelope::Decay, 100.0f);
Helpers::setAttribute<AhdsrEnvelope>(bp, AhdsrEnvelope::Sustain, Decibels::gainToDecibels(sustainLevel));
auto testData = Helpers::createTestDataWithOneSecondNote();
Helpers::process(bp, testData, 512);
expectResult(testData.isWithinErrorRange(22050, sustainLevel), "Sustain value");
}
void testLFOSeq(bool useGroup)
{
beginTestWithOptionalGroup("Testing LFO Seq", useGroup);
// Init
ScopedProcessor bp = Helpers::createWithOptionalGroup(NoiseSynth::DC, useGroup);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Attack, 0.0f);
Helpers::setAttribute<SimpleEnvelope>(bp, SimpleEnvelope::Release, 0.0f);
// Setup
auto squareLFO = Helpers::addTimeModulatorToOptionalGroup<LfoModulator>(bp, ModulatorSynth::GainModulation);
auto seqLFO = Helpers::addTimeModulatorToOptionalGroup<LfoModulator>(bp, ModulatorSynth::GainModulation);
squareLFO->setAttribute(LfoModulator::Parameters::TempoSync, 1.0f, dontSendNotification);
seqLFO->setAttribute(LfoModulator::Parameters::TempoSync, 1.0f, dontSendNotification);
squareLFO->setAttribute(LfoModulator::Frequency, (float)(int)TempoSyncer::Eighth, dontSendNotification);
seqLFO->setAttribute(LfoModulator::Frequency, (float)(int)TempoSyncer::Sixteenth, dontSendNotification);
squareLFO->setAttribute(LfoModulator::SmoothingTime, 0.0f, dontSendNotification);
seqLFO->setAttribute(LfoModulator::SmoothingTime, 0.0f, dontSendNotification);
squareLFO->setAttribute(LfoModulator::WaveFormType, LfoModulator::Waveform::Square, dontSendNotification);
seqLFO->setAttribute(LfoModulator::WaveFormType, LfoModulator::Waveform::Steps, dontSendNotification);
squareLFO->setAttribute(LfoModulator::Parameters::FadeIn, 0.0f, dontSendNotification);
seqLFO->setAttribute(LfoModulator::Parameters::FadeIn, 0.0f, dontSendNotification);
seqLFO->getSliderPackData(0)->setNumSliders(2);
seqLFO->getSliderPackData(0)->setValue(1, 0.0f, dontSendNotification);
// Process
squareLFO->setBypassed(true);
seqLFO->setBypassed(false);
auto seqData = Helpers::createTestDataWithOneSecondNote(56);
Helpers::process(bp, seqData, 512);
squareLFO->setBypassed(false);
seqLFO->setBypassed(true);
auto squareData = Helpers::createTestDataWithOneSecondNote(56);
Helpers::process(bp, squareData, 512);
// Tests
expectResult(seqData.matches(squareData, this, -3.0f), "Step doesn't match Square");
bp = nullptr;
}
void expectResult(Result r, String errorMessage)
{
expect(r.wasOk(), errorMessage + " - " + r.getErrorMessage());
}
void beginTestWithOptionalGroup(const String& testName, bool useGroup)
{
beginTest(testName + String(useGroup ? " in group" : ""));
}
struct Helpers
{
class DiracIterator
{
public:
DiracIterator(AudioSampleBuffer& b, int channel, bool strictMode_):
ptr(b.getReadPointer(channel)),
strictMode(strictMode_),
numSamples(b.getNumSamples())
{
}
Result scan()
{
int lastDiracIndex = -1;
int currentIndex = 0;
while (--numSamples >= 0)
{
const float value = *ptr++;
const bool isOne = strictMode ? (value == 1.0f) : (value > 0.01f);
const bool isMinusOne = strictMode ? (value == -11.0f) : (value < -0.01f);
if (isMinusOne)
{
if (lastDiracIndex != -1)
{
return Result::fail("Negative dirac at non-start");
}
data.firstIsNegative = true;
if(currentIndex != 0)
data.sampleDistances.add(currentIndex);
lastDiracIndex = currentIndex;
}
else if (isOne)
{
data.sampleDistances.add(currentIndex - lastDiracIndex);
lastDiracIndex = currentIndex;
}
else if (strictMode)
{
return Result::fail("Intermediate value found: " + String(value, 3) + " at " + String(currentIndex));
}
currentIndex++;
}
return Result::ok();
}
struct Data
{
Result matchesStartAndEnd(int start, int end) const
{
if (sampleDistances.getFirst() != start)
return Result::fail("Start doesn't match. Expected: " + String(start) + ", actual: " + String(sampleDistances.getFirst()));
if (sampleDistances.getLast() != end)
return Result::fail("End doesn't match. Expected: " + String(end) + ", actual: " + String(sampleDistances.getLast()));
return Result::ok();
};
Result isWithinRange(Range<int> r) const
{
for (int i = 0; i < sampleDistances.size(); i++)
{
auto v = sampleDistances[i];
if (v < r.getStart() || v > r.getEnd())
{
return Result::fail("Outside of range: " + String(v) + " at Sample index " + String(i));
}
}
return Result::ok();
}
Array<int> sampleDistances;
bool firstIsNegative = false;
};
const Data& getData() const
{
return data;
}
void dump(UnitTest* test)
{
String d;
d << "Dirac dump:\n";
int row = 0;
for (const auto& da : data.sampleDistances)
{
d << da << ", ";
row++;
if (row >= 8)
{
d << "\n";
row = 0;
}
}
test->logMessage(d);
}
private:
const float* ptr;
bool strictMode;
int numSamples;
Data data;
};
static void copyToClipboard(BackendProcessor* bp)
{
BackendCommandTarget::Actions::exportFileAsSnippet(bp);
}
template <class ProcessorType> static ProcessorType* get(BackendProcessor* bp)
{
return ProcessorHelpers::getFirstProcessorWithType<ProcessorType>(bp->getMainSynthChain());
}
template <class ProcessorType> static void reset(BackendProcessor* bp)
{
auto p = get<ProcessorType>(bp);
auto numParameters = p->getNumParameters();
for (int i = 0; i < numParameters; i++)
{
p->setAttribute(i, p->getDefaultValue(i), dontSendNotification);
}
}
template <class ProcessorType> static ProcessorType* addVoiceModulatorToOptionalGroup(BackendProcessor* bp, int chainToInsert)
{
bool isGroup = ProcessorHelpers::is<ModulatorSynthGroup>(bp->getMainSynthChain()->getHandler()->getProcessor(0));
if (isGroup)
return addVoiceModulator<ModulatorSynthGroup, ProcessorType>(bp, chainToInsert);
else
return addVoiceModulator<NoiseSynth, ProcessorType>(bp, chainToInsert);
}
static void setLfoToDefaultSquare(LfoModulator* lfo)
{
lfo->setAttribute(LfoModulator::TempoSync, true, dontSendNotification);
lfo->setAttribute(LfoModulator::WaveFormType, LfoModulator::Square, dontSendNotification);
lfo->setAttribute(LfoModulator::Frequency, TempoSyncer::Eighth, dontSendNotification);
lfo->setAttribute(LfoModulator::FadeIn, 0.0f, dontSendNotification);
lfo->setAttribute(LfoModulator::SmoothingTime, 0.0f, dontSendNotification);
}
template <class ParentType, class ProcessorType> static ProcessorType* addVoiceModulator(BackendProcessor* bp, int chainToInsert)
{
auto modChain = dynamic_cast<ModulatorChain*>(get<ParentType>(bp)->getChildProcessor(chainToInsert));
Random r;
auto id = String(r.nextInt());
auto newMod = new ProcessorType(bp, id, NUM_POLYPHONIC_VOICES, modChain->getMode());
modChain->getHandler()->add(newMod, nullptr);
return newMod;
}
static ModulatorSynth* getMainSynth(BackendProcessor* bp, bool useGroup)
{
if (useGroup)
{
return dynamic_cast<ModulatorSynth*>(ProcessorHelpers::getFirstProcessorWithType<ModulatorSynthGroup>(bp->getMainSynthChain()));
}
else
{
return dynamic_cast<ModulatorSynth*>(ProcessorHelpers::getFirstProcessorWithType<NoiseSynth>(bp->getMainSynthChain()));
}
}
static void addGlobalContainer(BackendProcessor* bp, bool useGroup)
{
auto mainSynth = Helpers::getMainSynth(bp, useGroup);
auto container = new GlobalModulatorContainer(bp, "Container", NUM_POLYPHONIC_VOICES);
bp->getMainSynthChain()->getHandler()->add(container, mainSynth);
}
template <class ProcessorType> static ProcessorType* addTimeModulatorToOptionalGroup(BackendProcessor* bp, int chainToInsert)
{
bool isGroup = ProcessorHelpers::is<ModulatorSynthGroup>(bp->getMainSynthChain()->getHandler()->getProcessor(0));
if (isGroup)
return addTimeModulator<ModulatorSynthGroup, ProcessorType>(bp, chainToInsert);
else
return addTimeModulator<NoiseSynth, ProcessorType>(bp, chainToInsert);
}
template <class ParentType, class ProcessorType> static ProcessorType* addTimeModulator(BackendProcessor* bp, int chainToInsert)
{
auto modChain = dynamic_cast<ModulatorChain*>(get<ParentType>(bp)->getChildProcessor(chainToInsert));
Random r;
auto id = String(r.nextInt());
auto newMod = new ProcessorType(bp, id, modChain->getMode());
modChain->getHandler()->add(newMod, nullptr);
return newMod;
}
template <class ProcessorType> static ProcessorType* addVoiceEffectToOptionalGroup(BackendProcessor* bp)
{
bool isGroup = ProcessorHelpers::is<ModulatorSynthGroup>(bp->getMainSynthChain()->getHandler()->getProcessor(0));
if (isGroup)
return addVoiceEffect<ModulatorSynthGroup, ProcessorType>(bp);
else
return addVoiceEffect<NoiseSynth, ProcessorType>(bp);
}
template <class ParentType, class ProcessorType> static ProcessorType* addVoiceEffect(BackendProcessor* bp)
{
auto fxChain = dynamic_cast<EffectProcessorChain*>(get<ParentType>(bp)->getChildProcessor(ModulatorSynth::EffectChain));
Random r;
auto id = String(r.nextInt());
auto newEffect = new ProcessorType(bp, id, NUM_POLYPHONIC_VOICES);
fxChain->getHandler()->add(newEffect, nullptr);
return newEffect;
}
template <class ProcessorType> static void setAttribute(BackendProcessor* bp, int index, float value)
{
auto p = get<ProcessorType>(bp);
p->setAttribute(index, value, dontSendNotification);
}
struct TestData
{
float getSample(int sampleIndex) const
{
return audioBuffer.getSample(0, sampleIndex);
}
float getSample(int channelIndex, int sampleIndex) const
{
return audioBuffer.getSample(channelIndex, sampleIndex);
}
bool operator==(const TestData& other) const
{
if (audioBuffer.getNumSamples() != other.audioBuffer.getNumSamples())
return false;
int size = audioBuffer.getNumSamples();
float error = 0.0f;
for (int i = 0; i < size; i++)
{
error = jmax(error, fabsf(getSample(0, i) - other.getSample(0, i)));
error = jmax(error, fabsf(getSample(1, i) - other.getSample(1, i)));
}
const float errorDb = Decibels::gainToDecibels(error);
if (errorDb > -80.0f)
return false;
return true;
}
Result matches(const TestData& otherData, UnitTest* test, float errorLevelDecibels)
{
if (audioBuffer.getNumSamples() != otherData.audioBuffer.getNumSamples())
return Result::fail("Size mismatch");
int size = audioBuffer.getNumSamples();
float maxError = -100.0f;
for (int i = 0; i < size; i++)
{
auto otherL = otherData.getSample(0, i);
auto otherR = otherData.getSample(1, i);
maxError = jmax<float>(maxError, getError(getSample(0, i), otherL));
maxError = jmax<float>(maxError, getError(getSample(1, i), otherR));
auto rl = isWithinErrorRange(i, otherL, 0, errorLevelDecibels);
auto rr = isWithinErrorRange(i, otherR, 1, errorLevelDecibels);
if (rl.failed())
{
test->logMessage("Error at sample " + String(i));
dump(audioBuffer, "dumpExpected.wav");
dump(otherData.audioBuffer, "dumpActual.wav");
return rl;
}
if (rr.failed())
{
test->logMessage("Error at sample " + String(i));
dump(audioBuffer, "dumpExpected.wav");
dump(otherData.audioBuffer, "dumpActual.wav");
return rr;
}
}
test->logMessage("Max error: " + String(maxError, 1) + " dB");
return Result::ok();
}
static float getError(float firstSample, float secondSample)
{
auto diff = fabsf(firstSample - secondSample);
auto error = Decibels::gainToDecibels(diff);
return error;
}
Result isWithinErrorRange(int sampleIndex, float expected, int channelIndex = 0, float errorInDecibels=-60.0f) const
{
auto actual = audioBuffer.getSample(channelIndex, sampleIndex);
auto error = getError(expected, actual);
if (error > errorInDecibels)
{
return Result::fail("Error: " + String(error, 1) + " dB");
}
return Result::ok();
}
MidiBuffer midiBuffer;
AudioSampleBuffer audioBuffer;
};
static BackendProcessor* createWithOptionalGroup(NoiseSynth::TestSignal signalType, bool useGroup)
{
if (useGroup)
return createAndInitialiseProcessorWithGroup(signalType);
else
return createAndInitialiseProcessor(signalType);
}
static BackendProcessor* createAndInitialiseProcessorWithGroup(NoiseSynth::TestSignal signalType)
{
ScopedPointer<BackendProcessor> bp = new BackendProcessor(nullptr, nullptr);
ScopedPointer<ModulatorSynthGroup> gr = new ModulatorSynthGroup(bp, "Group", NUM_POLYPHONIC_VOICES);
ScopedPointer<NoiseSynth> noiseSynth = new NoiseSynth(bp, "TestProcessor", NUM_POLYPHONIC_VOICES);
noiseSynth->setAttribute(ModulatorSynth::Parameters::Gain, 1.0f, dontSendNotification);
noiseSynth->setTestSignal(signalType);
gr->getHandler()->add(noiseSynth.release(), nullptr);
gr->addProcessorsWhenEmpty();
gr->setAttribute(ModulatorSynth::Parameters::Gain, 1.0f, dontSendNotification);
bp->getMainSynthChain()->getHandler()->add(gr.release(), nullptr);
return bp.release();
}
static BackendProcessor* createAndInitialiseProcessor(NoiseSynth::TestSignal signalType)
{
ScopedPointer<BackendProcessor> bp = new BackendProcessor(nullptr, nullptr);
ScopedPointer<NoiseSynth> noiseSynth = new NoiseSynth(bp, "TestProcessor", NUM_POLYPHONIC_VOICES);
noiseSynth->addProcessorsWhenEmpty();
noiseSynth->setAttribute(ModulatorSynth::Parameters::Gain, 1.0f, dontSendNotification);
noiseSynth->setTestSignal(signalType);
bp->getMainSynthChain()->getHandler()->add(noiseSynth.release(), nullptr);
return bp.release();
}
static TestData createTestDataWithOneSecondNote(int startOffset = 0, int stopOffset=-1)
{
TestData d;
d.audioBuffer.setSize(2, sampleRate * 2);
d.audioBuffer.clear();
d.midiBuffer.addEvent(MidiMessage::noteOn(1, 64, 1.0f), startOffset);
if (stopOffset == -1)
stopOffset = roundDoubleToInt(sampleRate*0.7);
d.midiBuffer.addEvent(MidiMessage::noteOff(1, 64), stopOffset);
return d;
}
static void process(BackendProcessor* bp, TestData& data, int blockSize, int numToProcess=-1)
{
bp->prepareToPlay((double)sampleRate, blockSize);
resumeProcessing(bp, data, blockSize, numToProcess, 0);
}
static void resumeProcessing(BackendProcessor* bp, TestData& data, int blockSize, int numToProcess, int sampleOffset)
{
int numSamplesTotal = numToProcess > 0 ? numToProcess : data.audioBuffer.getNumSamples();
numSamplesTotal = jmin<int>(numSamplesTotal, data.audioBuffer.getNumSamples()-sampleOffset);
int offset = sampleOffset;
while (numSamplesTotal > 0)
{
int numThisTime = jmin<int>(numSamplesTotal, blockSize);
auto l = data.audioBuffer.getWritePointer(0, offset);
auto r = data.audioBuffer.getWritePointer(1, offset);
float* d[2] = { l, r };
AudioSampleBuffer subAudio(d, 2, numThisTime);
MidiBuffer subMidi;
subMidi.addEvents(data.midiBuffer, offset, numThisTime, -offset);
bp->processBlock(subAudio, subMidi);
numSamplesTotal -= numThisTime;
offset += numThisTime;
}
}
static void dump(const AudioSampleBuffer& b, const String& fileName)
{
hlac::CompressionHelpers::dump(b, fileName);
}
};
};
static ModulationTests modulationTests;
class CustomContainerTest : public UnitTest
{
public:
struct DummyStruct
{
DummyStruct(int index_) :
index(index_)
{};
DummyStruct() :
index(0)
{}
int index;
};
struct DummyStruct2
{
DummyStruct2(int a1, int a2, int a3, int a4) :
a({ a1, a2, a3, a4 })
{
}
DummyStruct2() :
a({ 0, 0, 0, 0 })
{}
int getSum() const
{
int sum = 0;
for (auto a_ : a)
sum += a_;
return sum;
}
private:
std::vector<int> a;
};
CustomContainerTest() :
UnitTest("Testing custom containers")
{
}
void runTest() override
{
testingUnorderedStack();
testingLockFreeQueue();
testBlockDivider<32>(64, 32, 1);
testBlockDivider<32>(96, 0, 0);
testBlockDivider<32>(256, 4, 32);
testBlockDivider<16>(17, 4, 1);
testBlockDivider<64>(64, 4, 1);
testBlockDivider<16>(53, 12, 1);
testBlockDivider<32>(512, 13, 8);
testBlockDividedRamping<32>(512, 0, 0);
testBlockDividedRamping<32>(512, 4, 32);
testBlockDividedRamping<32>(512, 17, 8);
testBlockDividedRamping<32>(256, 18, 8);
testBlockDividedRamping<32>(74, 16, 1);
}
private:
template <int RampLength> void testBlockDividedRamping(int averageBlockSize, int maxVariationFactor, int variationSize)
{
beginTest("Testing Rampers with length " + String(RampLength) + ", average block size " + String(averageBlockSize) + " and variation " + String(maxVariationFactor) + "*" + String(variationSize));
Random r;
const int totalLength = averageBlockSize * r.nextInt({ 8, 20 });
int numSamples = totalLength;
ModulatorChain::ModChainWithBuffer::Buffer b;
b.setMaxSize(totalLength);
auto data = b.scratchBuffer;
BlockDivider<RampLength> blockDivider;
float value = 2.0f;
float delta = 1.0f / (float)numSamples;
int numProcessed = 0;
BlockDividerStatistics::resetStatistics();
while (numSamples > 0)
{
int thisBlockSize = averageBlockSize;
if (maxVariationFactor > 0)
{
thisBlockSize -= r.nextInt({ 0, maxVariationFactor }) *variationSize;
}
thisBlockSize = jlimit<int>(0, numSamples, thisBlockSize);
const int numThisBlockConst = thisBlockSize;
// Reset it here to get rid of rounding errors...
value = 2.0f + numProcessed / (float)totalLength;
while (thisBlockSize > 0)
{
bool newBlock;
int blockSize = blockDivider.cutBlock(thisBlockSize, newBlock, data);
if (blockSize == 0)
{
AlignedSSERamper<RampLength> ramper(data);
ramper.ramp(value, delta);
value += delta * (float)RampLength;
data += RampLength;
numProcessed += RampLength;
}
else
{
FallbackRamper ramper(data, blockSize);
value = ramper.ramp(value, delta);
data += blockSize;
numProcessed += blockSize;
}
}
numSamples -= numThisBlockConst;
}
expectEquals<int>(numProcessed, totalLength, "NumProcessed");
int alignedCallPercentage = BlockDividerStatistics::getAlignedCallPercentage();
if (averageBlockSize % RampLength == 0 && (variationSize % RampLength == 0))
{
expect(alignedCallPercentage == 100, "All calls must be aligned");
}
else
{
logMessage("Aligned call percentage: " + String(alignedCallPercentage) + "%");
}
auto check = b.scratchBuffer;
for (int i = 0; i < totalLength; i++)
{
float expected = 2.0f + (float)i / (float)totalLength;
float thisValue = check[i];
float delta2 = Decibels::gainToDecibels(fabsf(expected - thisValue));
expect(delta2 < -96.0f, "Value at " + String(i) + "Expected" + String(expected) + ", Actual: " + String(thisValue));
};
}
template <int RampLength> void testBlockDivider(int averageBlockSize, int maxVariationFactor, int variationSize)
{
beginTest("Testing Block Divider with average block size " + String(averageBlockSize) + " and variation " + String(maxVariationFactor) + "*" + String(variationSize));
try
{
using SSEType = dsp::SIMDRegister<float>;
Random r;
int numBlocks = r.nextInt({ 8, 32 });
int totalLength = averageBlockSize * numBlocks;
ModulatorChain::ModChainWithBuffer::Buffer totalData;
totalData.setMaxSize(totalLength);
ModulatorChain::ModChainWithBuffer::Buffer blockData;
blockData.setMaxSize(averageBlockSize);
auto data = blockData.scratchBuffer;
FloatVectorOperations::fill(data, 1.0f, averageBlockSize);
auto startData = totalData.scratchBuffer;
int startLength = totalLength;
FloatVectorOperations::fill(startData, 0.5f, totalLength);
int counter = 0;
BlockDivider<RampLength> divider;
int numProcessed = 0;
int blockOffset = 0;
BlockDividerStatistics::resetStatistics();
while (totalLength > 0)
{
int thisBlockSize = averageBlockSize;
if (maxVariationFactor > 0)
thisBlockSize = averageBlockSize - r.nextInt({ 0, maxVariationFactor }) * variationSize;
else
thisBlockSize = averageBlockSize;
thisBlockSize = jmin<int>(thisBlockSize, totalLength);
data = blockData.scratchBuffer;
FloatVectorOperations::fill(data, 0.5, thisBlockSize);
counter = thisBlockSize;
while (counter > 0)
{
bool newBlock;
int subBlockSize = divider.cutBlock(counter, newBlock, data);
if (subBlockSize == 0)
{
expect(SSEType::isSIMDAligned(data), "Pointer alignment");
FloatVectorOperations::fill(data, 0.0f, RampLength);
data[0] = 1.0f;
numProcessed += RampLength;
data += RampLength;
}
else
{
FloatVectorOperations::fill(data, 0.0f, subBlockSize);
if (newBlock)
data[0] = 1.0f;
data += subBlockSize;
numProcessed += subBlockSize;
}
}
totalLength -= thisBlockSize;
FloatVectorOperations::copy(startData + blockOffset, blockData.scratchBuffer, thisBlockSize);
blockOffset += thisBlockSize;
}
expectEquals<int>(numProcessed, startLength, "NumProcessed");
for (int i = 0; i < startLength; i++)
{
const float expected = i % RampLength == 0 ? 1.0f : 0.0f;
expectEquals<float>(startData[i], expected, "Position: " + String(i));
}
int alignedCallPercentage = BlockDividerStatistics::getAlignedCallPercentage();
if (averageBlockSize % RampLength == 0 && (variationSize % RampLength == 0))
{
expect(alignedCallPercentage == 100, "All calls must be aligned");
}
else
{
logMessage("Aligned call percentage: " + String(alignedCallPercentage) + "%");
}
blockData.clear();
totalData.clear();
}
catch (String& m)
{
ignoreUnused(m);
DBG(m);
jassertfalse;
}
}
void testingUnorderedStack()
{
beginTest("Testing Unordered Stack: basic functions with ints");
UnorderedStack<int> intStack;
intStack.insert(1);
intStack.insert(2);
intStack.insert(3);
expectEquals<int>(intStack.size(), 3, "Size after insertion");
intStack.remove(2);
expectEquals<int>(intStack.size(), 2, "Size after deletion");
intStack.insert(4);
expectEquals<int>(intStack[0], 1, "First Element");
expectEquals<int>(intStack[1], 3, "Second Element");
expectEquals<int>(intStack[2], 4, "Third Element");
expectEquals<int>(intStack[3], 0, "Default Element");
expect(intStack.contains(4), "Contains int 1");
expect(!intStack.contains(5), "Contains int 1");
const float data[5] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
beginTest("Testing Unordered Stack: functions with float pointer");
UnorderedStack<const float*> fpStack;
expect(fpStack[0] == nullptr, "Null pointer");
fpStack.insert(data);
fpStack.insert(data + 1);
fpStack.insert(data + 2);
fpStack.insert(data + 3);
fpStack.insert(data + 4);
expectEquals<int>(fpStack.size(), 5);
expect(fpStack[5] == nullptr, "Null pointer 2");
expectEquals<float>(*fpStack[0], data[0], "Float pointer elements");
expectEquals<float>(*fpStack[1], data[1], "Float pointer elements");
expectEquals<float>(*fpStack[2], data[2], "Float pointer elements");
expectEquals<float>(*fpStack[3], data[3], "Float pointer elements");
expectEquals<float>(*fpStack[4], data[4], "Float pointer elements");
expect(fpStack.contains(data + 2), "Contains float* 1");
float d2 = 2.0f;
expect(!fpStack.contains(&d2), "Contains not float 2");
expect(!fpStack.contains(nullptr), "No null");
fpStack.remove(data + 2);
fpStack.insert(data + 2);
expectEquals<float>(*fpStack[0], data[0], "Float pointer elements after shuffle 1");
expectEquals<float>(*fpStack[1], data[1], "Float pointer elements after shuffle 2");
expectEquals<float>(*fpStack[2], data[4], "Float pointer elements after shuffle 3");
expectEquals<float>(*fpStack[3], data[3], "Float pointer elements after shuffle 4");
expectEquals<float>(*fpStack[4], data[2], "Float pointer elements after shuffle 5");
beginTest("Testing Unordered Stack: with dummy struct");
OwnedArray<DummyStruct> elements;
UnorderedStack<DummyStruct*> elementStack;
for (int i = 0; i < UNORDERED_STACK_SIZE; i++)
{
elements.add(new DummyStruct(i));
}
Random r;
for (int i = 0; i < 1000; i++)
{
const int indexToInsert = r.nextInt(Range<int>(0, elements.size() - 1));
auto ds = elements[indexToInsert];
if (!elements.contains(ds))
{
elementStack.insert(ds);
}
else
{
elementStack.remove(ds);
}
}
for (int i = 0; i < elementStack.size(); i++)
{
expect(elementStack[i] != nullptr);
}
for (int i = elementStack.size(); i < UNORDERED_STACK_SIZE; i++)
{
expect(elementStack[i] == nullptr);
}
}
void testingLockFreeQueue()
{
testLockFreeQueueWithInt();
testLockFreeQueueWithDummyStruct();
testLockFreeQueueWithLambda();
}
void testLockFreeQueueWithInt()
{
beginTest("Testing Lockfree Queue with ints");
LockfreeQueue<int> q(1024);
expect(q.push(1), "Push first element");
expect(q.push(2), "Push second element");
expect(q.push(3), "Push third element");
expectEquals(q.size(), 3, "Size");
int result;
expect(q.pop(result), "Pop First Element");
expectEquals<int>(result, 1, "first element value");
expect(q.pop(result), "Pop Second Element");
expectEquals<int>(result, 2, "second element value");
expect(q.pop(result), "Pop Third Element");
expectEquals<int>(result, 3, "third element value");
expect(q.isEmpty(), "Queue is empty");
expect(q.pop(result) == false, "Return false when empty");
q.push(1);
q.push(2);
q.push(3);
int sum = 0;
LockfreeQueue<int>::ElementFunction makeSum = [&sum](int& i)->bool { sum += i; return i != 0; };
expect(q.callForEveryElementInQueue(makeSum), "Call function for element");
expect(q.isEmpty(), "Empty after call");
expectEquals<int>(sum, 6, "Function call result");
};
void testLockFreeQueueWithDummyStruct()
{
beginTest("Testing Lockfree Queue with dummy struct");
LockfreeQueue<DummyStruct2> q2(3);
expect(q2.push(DummyStruct2(1, 2, 3, 4)), "Pushing first dummy struct");
expect(q2.push(DummyStruct2(2, 3, 4, 5)), "Pushing second dummy struct");
expect(q2.push(DummyStruct2(3, 4, 5, 6)), "Pushing third dummy struct");
expect(q2.push(DummyStruct2(4, 5, 6, 7)) == false, "Pushing forth dummy struct");
expect(q2.push(DummyStruct2(4, 5, 6, 7)) == false, "Pushing fifth dummy struct");
DummyStruct2 result;
expect(q2.pop(result), "Pop first element");
expectEquals<int>(result.getSum(), 1 + 2 + 3 + 4, "Sum of first element");
int sum = 0;
LockfreeQueue<DummyStruct2>::ElementFunction makeSum = [&sum](DummyStruct2& s)->bool{ sum += s.getSum(); return true; };
const int expectedSum = 2 + 3 + 4 + 5 + 3 + 4 + 5 + 6;
q2.callForEveryElementInQueue(makeSum);
expect(q2.isEmpty(), "Queue is empty");
expectEquals<int>(sum, expectedSum, "Accumulate function calls");
}
void testLockFreeQueueWithLambda()
{
beginTest("Testing Lockfree Queue with lambda");
using TestFunction = std::function<bool()>;
LockfreeQueue<TestFunction> q(100);
int sum = 0;
TestFunction addTwo = [&sum]() { sum += 2; return true; };
LockfreeQueue<TestFunction>::ElementFunction call = [](TestFunction& f) {f(); return true; };
call(addTwo);
call(addTwo);
call(addTwo);
expectEquals<int>(sum, 6, "lambda is working");
sum = 0;
q.push([&sum]() {sum += 1; return true; });
q.push([&sum]() {sum += 2; return true; });
q.push([&sum]() {sum += 3; return true; });
q.callForEveryElementInQueue(call);
expect(q.isEmpty(), "Queue empty after calling");
expectEquals<int>(sum, 6, "Result after calling");
sum = 0;
q.push([&sum]() {sum += 2; return true; });
q.push([&sum]() {sum += 3; return true; });
q.push([&sum]() {sum += 4; return true; });
expect(q.callEveryElementInQueue(), "Direct call");
expectEquals<int>(sum, 9, "Result after direct call");
}
};
static CustomContainerTest unorderedStackTest;
#endif
| 27.51386 | 197 | 0.706327 | [
"vector"
] |
909a5557790b34c49498f4fc53fa6485601f952a | 3,495 | cpp | C++ | Source/introscreen.cpp | DarkAvanger/DreamTeam | e0074bdabc479ff8dfeb66e684386d5a86690dc8 | [
"MIT"
] | 3 | 2021-02-15T09:09:59.000Z | 2021-03-15T19:38:44.000Z | Source/introscreen.cpp | DarkAvanger/DreamTeam | e0074bdabc479ff8dfeb66e684386d5a86690dc8 | [
"MIT"
] | null | null | null | Source/introscreen.cpp | DarkAvanger/DreamTeam | e0074bdabc479ff8dfeb66e684386d5a86690dc8 | [
"MIT"
] | 3 | 2021-03-15T19:52:12.000Z | 2022-01-17T22:29:23.000Z | #include "SceneIntro.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModuleAudio.h"
#include "ModuleInput.h"
#include "ModuleFadeToBlack.h"
#include "ModuleFonts.h"
#include "ModulePlayer.h"
#include "introscreen.h"
#include <iostream>
ScreenIntro::ScreenIntro(bool startEnabled) : Module(startEnabled)
{
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.PushBack({ 250, 200, 20, 20 });
black.loop = false;
black.speed = 0.05f;
}
ScreenIntro::~ScreenIntro()
{
}
// Load assets
bool ScreenIntro::Start()
{
LOG("Loading background assets");
bool ret = true;
bgTexture = App->textures->Load("Assets/Sprites/LOGO.png");
bgTexture1 = App->textures->Load("Assets/Sprites/UPC.png");
bgTexture2 = App->textures->Load("Assets/Sprites/CITM.png");
bgTexture3 = App->textures->Load("Assets/Sprites/minilogo.png");
App->render->camera.x = 0;
App->render->camera.y = 0;
char lookupTable[] = { "! @,_./0123456789$;< ?abcdefghijklmnopqrstuvwxyz" };
titleFont = App->fonts->Load("Assets/Fonts/rtype_font.png", lookupTable, 1);
namesFont = App->fonts->Load("Assets/Fonts/rtype_font3.png", lookupTable, 2);
return ret;
App->render->camera.x = 0;
App->render->camera.y = 0;
return ret;
}
Update_Status ScreenIntro::Update()
{
GamePad& pad = App->input->pads[0];
black.Update();
if (black.HasFinished())
{
App->fade->FadeToBlack(this, (Module*)App->sceneIntro, 90);
}
else if (App->input->keys[SDL_SCANCODE_SPACE] == Key_State::KEY_DOWN || pad.a)
{
App->fade->FadeToBlack(this, (Module*)App->sceneIntro, 90);
}
return Update_Status::UPDATE_CONTINUE;
}
// Update: draw background
Update_Status ScreenIntro::PostUpdate()
{
App->render->Blit(bgTexture, 0, 0, NULL);
App->render->Blit(bgTexture1, 240 , SCREEN_HEIGHT / 2 + 60, NULL);
App->render->Blit(bgTexture2, 20, SCREEN_HEIGHT / 2 + 60, NULL);
App->render->Blit(bgTexture3, 142, 0, NULL);
App->fonts->BlitText(SCREEN_WIDTH / 2 - 30, SCREEN_HEIGHT / 2 - 100, titleFont, "project 1 ");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 164, SCREEN_HEIGHT / 2 - 85, namesFont, "we are recreating the game super soukoban");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 40, SCREEN_HEIGHT / 2 - 50, titleFont, " teachers");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 60, SCREEN_HEIGHT / 2 - 35, namesFont, "ramon santamaria");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 45, SCREEN_HEIGHT / 2 - 20, namesFont, "jesus alonso");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 76, SCREEN_HEIGHT / 2 + 5, titleFont, "upc universitat citm");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 128, SCREEN_HEIGHT / 2 + 20, namesFont, "video game design and development");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 66, SCREEN_HEIGHT / 2 + 45, titleFont, "dreamteam members");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 34, SCREEN_HEIGHT / 2 + 60, namesFont, "hang xue");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 46, SCREEN_HEIGHT / 2 + 75, namesFont, "sofia liles");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 51, SCREEN_HEIGHT / 2 + 90, namesFont, "angel consola");
App->fonts->BlitText(SCREEN_WIDTH / 2 - 49, SCREEN_HEIGHT / 2 + 105, namesFont, "marta llurba");
return Update_Status::UPDATE_CONTINUE;
} | 33.285714 | 126 | 0.688126 | [
"render"
] |
909cab1031025772e1a29d58da37d1df57820967 | 750 | cpp | C++ | Cplus/NumberofWaystoDivideaLongCorridor.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/NumberofWaystoDivideaLongCorridor.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | null | null | null | Cplus/NumberofWaystoDivideaLongCorridor.cpp | Jum1023/leetcode | d8248aa84452cb1ea768d9b05ecd72a6746c0016 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
using namespace std;
class Solution
{
public:
int numberOfWays(string corridor)
{
int N = corridor.length();
vector<long long> dp(N + 1), sum(N + 1); //累加的结果
dp[0] = 1;
vector<int> preseat(N);
int pre = -1;
for (int i = 0; i < N; ++i)
{
preseat[i] = pre;
if (corridor[i] == 'S')
pre = i;
}
for (int i = 0; i < N; ++i)
{
sum[i + 1] = sum[i] + dp[i];
pre = preseat[i];
if (pre == -1)
continue;
if (corridor[i] == 'P')
pre = preseat[pre];
if (pre == -1)
continue;
int p = preseat[pre];
if (p == -1)
dp[i + 1] = 1;
else
dp[i + 1] = (sum[pre + 1] - sum[p + 1] + MOD) % MOD;
}
return dp[N];
}
private:
static const int MOD = 1e9 + 7;
}; | 17.857143 | 56 | 0.501333 | [
"vector"
] |
90a05b30f8642455106a20753c2d84f46a35acc6 | 4,361 | cpp | C++ | src/modules/memory/memory_transmogrify.cpp | dmortondev/openperf | dc142aa9bddcd578fd3491275cf36c016209df2e | [
"Apache-2.0"
] | null | null | null | src/modules/memory/memory_transmogrify.cpp | dmortondev/openperf | dc142aa9bddcd578fd3491275cf36c016209df2e | [
"Apache-2.0"
] | null | null | null | src/modules/memory/memory_transmogrify.cpp | dmortondev/openperf | dc142aa9bddcd578fd3491275cf36c016209df2e | [
"Apache-2.0"
] | null | null | null | #include <iomanip>
#include "memory/api.hpp"
#include "memory/generator/config.hpp"
#include "memory/generator/coordinator.hpp"
#include "swagger/v1/model/MemoryGenerator.h"
#include "swagger/v1/model/MemoryGeneratorResult.h"
namespace openperf::memory::api {
static std::shared_ptr<swagger::v1::model::MemoryGeneratorConfig>
to_swagger(const generator::config& config)
{
auto dst = std::make_shared<swagger::v1::model::MemoryGeneratorConfig>();
dst->setBufferSize(config.buffer_size);
dst->setReadsPerSec(
static_cast<int64_t>(std::trunc(config.read.io_rate.count())));
dst->setReadSize(config.read.io_size);
dst->setReadThreads(config.read.io_threads);
dst->setWritesPerSec(
static_cast<int64_t>(std::trunc(config.write.io_rate.count())));
dst->setWriteSize(config.write.io_size);
dst->setWriteThreads(config.write.io_threads);
dst->setPattern(to_string(config.read.io_pattern));
return (dst);
}
mem_generator_ptr to_swagger(std::string_view id,
const generator::coordinator& gen)
{
auto dst = std::make_unique<swagger::v1::model::MemoryGenerator>();
dst->setId(std::string(id));
dst->setConfig(to_swagger(gen.config()));
dst->setRunning(gen.active());
dst->setInitPercentComplete(100);
return (dst);
}
template <typename Clock>
std::string to_rfc3339(std::chrono::time_point<Clock> from)
{
using namespace std::chrono_literals;
static constexpr auto ns_per_sec = std::chrono::nanoseconds(1s).count();
auto total_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
from.time_since_epoch())
.count();
time_t sec = total_ns / ns_per_sec;
auto ns = total_ns % ns_per_sec;
std::stringstream os;
os << std::put_time(gmtime(&sec), "%FT%T") << "." << std::setfill('0')
<< std::setw(9) << ns << "Z";
return (os.str());
}
template <typename Duration>
std::chrono::nanoseconds to_nanoseconds(const Duration& duration)
{
return (std::chrono::duration_cast<std::chrono::nanoseconds>(duration));
}
template <typename Clock>
static std::shared_ptr<swagger::v1::model::MemoryGeneratorStats>
to_swagger(const generator::io_stats<Clock>& stats)
{
auto dst = std::make_shared<swagger::v1::model::MemoryGeneratorStats>();
dst->setOpsTarget(stats.ops_target);
dst->setOpsActual(stats.ops_actual);
dst->setBytesTarget(stats.bytes_target);
dst->setBytesActual(stats.bytes_actual);
dst->setLatencyTotal(to_nanoseconds(stats.latency).count());
return (dst);
}
mem_generator_result_ptr
to_swagger(std::string_view generator_id,
std::string_view result_id,
const std::shared_ptr<generator::result>& result)
{
auto dst = std::make_unique<swagger::v1::model::MemoryGeneratorResult>();
dst->setId(std::string(result_id));
dst->setGeneratorId(std::string(generator_id));
/* Result is active iff coordinator and server both have pointers to it */
dst->setActive(result.use_count() > 1);
auto stats = generator::sum_stats(result->shards());
dst->setTimestampFirst(to_rfc3339(stats.time_.first));
dst->setTimestampLast(to_rfc3339(stats.time_.last));
dst->setRead(to_swagger(stats.read));
dst->setWrite(to_swagger(stats.write));
dst->setDynamicResults(std::make_shared<swagger::v1::model::DynamicResults>(
to_swagger(result->dynamic())));
return (dst);
}
generator::config
from_swagger(const swagger::v1::model::MemoryGeneratorConfig& config)
{
auto dst = generator::config{
.buffer_size = static_cast<uint64_t>(config.getBufferSize()),
.read =
{
.io_rate = generator::ops_per_sec{config.getReadsPerSec()},
.io_size = static_cast<unsigned>(config.getReadSize()),
.io_threads = static_cast<unsigned>(config.getReadThreads()),
.io_pattern = to_pattern_type(config.getPattern()),
},
.write = {
.io_rate = generator::ops_per_sec{config.getWritesPerSec()},
.io_size = static_cast<unsigned>(config.getWriteSize()),
.io_threads = static_cast<unsigned>(config.getWriteThreads()),
.io_pattern = to_pattern_type(config.getPattern()),
}};
return (dst);
}
} // namespace openperf::memory::api
| 33.806202 | 80 | 0.67645 | [
"model"
] |
90abc00d0d2752d02a5d382f01e1eba8227c798c | 7,583 | cpp | C++ | test/opt/optimizer_test.cpp | dgkoch/SPIRV-Tools | f3acb955c20395f76b4f592631016d297ca34fe5 | [
"Apache-2.0"
] | 9 | 2016-05-25T12:25:50.000Z | 2020-11-30T13:40:13.000Z | test/opt/optimizer_test.cpp | dgkoch/SPIRV-Tools | f3acb955c20395f76b4f592631016d297ca34fe5 | [
"Apache-2.0"
] | 7 | 2019-08-23T17:54:13.000Z | 2020-02-01T06:59:52.000Z | test/opt/optimizer_test.cpp | dgkoch/SPIRV-Tools | f3acb955c20395f76b4f592631016d297ca34fe5 | [
"Apache-2.0"
] | 9 | 2018-10-31T03:07:11.000Z | 2021-08-06T08:53:21.000Z | // Copyright (c) 2017 Google 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.
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "spirv-tools/libspirv.hpp"
#include "spirv-tools/optimizer.hpp"
#include "test/opt/pass_fixture.h"
namespace spvtools {
namespace opt {
namespace {
using ::testing::Eq;
// Return a string that contains the minimum instructions needed to form
// a valid module. Other instructions can be appended to this string.
std::string Header() {
return R"(OpCapability Shader
OpCapability Linkage
OpMemoryModel Logical GLSL450
)";
}
TEST(Optimizer, CanRunNullPassWithDistinctInputOutputVectors) {
SpirvTools tools(SPV_ENV_UNIVERSAL_1_0);
std::vector<uint32_t> binary_in;
tools.Assemble(Header() + "OpName %foo \"foo\"\n%foo = OpTypeVoid",
&binary_in);
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
opt.RegisterPass(CreateNullPass());
std::vector<uint32_t> binary_out;
opt.Run(binary_in.data(), binary_in.size(), &binary_out);
std::string disassembly;
tools.Disassemble(binary_out.data(), binary_out.size(), &disassembly);
EXPECT_THAT(disassembly,
Eq(Header() + "OpName %foo \"foo\"\n%foo = OpTypeVoid\n"));
}
TEST(Optimizer, CanRunTransformingPassWithDistinctInputOutputVectors) {
SpirvTools tools(SPV_ENV_UNIVERSAL_1_0);
std::vector<uint32_t> binary_in;
tools.Assemble(Header() + "OpName %foo \"foo\"\n%foo = OpTypeVoid",
&binary_in);
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
opt.RegisterPass(CreateStripDebugInfoPass());
std::vector<uint32_t> binary_out;
opt.Run(binary_in.data(), binary_in.size(), &binary_out);
std::string disassembly;
tools.Disassemble(binary_out.data(), binary_out.size(), &disassembly);
EXPECT_THAT(disassembly, Eq(Header() + "%void = OpTypeVoid\n"));
}
TEST(Optimizer, CanRunNullPassWithAliasedVectors) {
SpirvTools tools(SPV_ENV_UNIVERSAL_1_0);
std::vector<uint32_t> binary;
tools.Assemble("OpName %foo \"foo\"\n%foo = OpTypeVoid", &binary);
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
opt.RegisterPass(CreateNullPass());
opt.Run(binary.data(), binary.size(), &binary); // This is the key.
std::string disassembly;
tools.Disassemble(binary.data(), binary.size(), &disassembly);
EXPECT_THAT(disassembly, Eq("OpName %foo \"foo\"\n%foo = OpTypeVoid\n"));
}
TEST(Optimizer, CanRunNullPassWithAliasedVectorDataButDifferentSize) {
SpirvTools tools(SPV_ENV_UNIVERSAL_1_0);
std::vector<uint32_t> binary;
tools.Assemble(Header() + "OpName %foo \"foo\"\n%foo = OpTypeVoid", &binary);
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
opt.RegisterPass(CreateNullPass());
auto orig_size = binary.size();
// Now change the size. Add a word that will be ignored
// by the optimizer.
binary.push_back(42);
EXPECT_THAT(orig_size + 1, Eq(binary.size()));
opt.Run(binary.data(), orig_size, &binary); // This is the key.
// The binary vector should have been rewritten.
EXPECT_THAT(binary.size(), Eq(orig_size));
std::string disassembly;
tools.Disassemble(binary.data(), binary.size(), &disassembly);
EXPECT_THAT(disassembly,
Eq(Header() + "OpName %foo \"foo\"\n%foo = OpTypeVoid\n"));
}
TEST(Optimizer, CanRunTransformingPassWithAliasedVectors) {
SpirvTools tools(SPV_ENV_UNIVERSAL_1_0);
std::vector<uint32_t> binary;
tools.Assemble(Header() + "OpName %foo \"foo\"\n%foo = OpTypeVoid", &binary);
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
opt.RegisterPass(CreateStripDebugInfoPass());
opt.Run(binary.data(), binary.size(), &binary); // This is the key
std::string disassembly;
tools.Disassemble(binary.data(), binary.size(), &disassembly);
EXPECT_THAT(disassembly, Eq(Header() + "%void = OpTypeVoid\n"));
}
TEST(Optimizer, CanValidateFlags) {
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
EXPECT_FALSE(opt.FlagHasValidForm("bad-flag"));
EXPECT_TRUE(opt.FlagHasValidForm("-O"));
EXPECT_TRUE(opt.FlagHasValidForm("-Os"));
EXPECT_FALSE(opt.FlagHasValidForm("-O2"));
EXPECT_TRUE(opt.FlagHasValidForm("--this_flag"));
}
TEST(Optimizer, CanRegisterPassesFromFlags) {
SpirvTools tools(SPV_ENV_UNIVERSAL_1_0);
Optimizer opt(SPV_ENV_UNIVERSAL_1_0);
spv_message_level_t msg_level;
const char* msg_fname;
spv_position_t msg_position;
const char* msg;
auto examine_message = [&msg_level, &msg_fname, &msg_position, &msg](
spv_message_level_t ml, const char* f,
const spv_position_t& p, const char* m) {
msg_level = ml;
msg_fname = f;
msg_position = p;
msg = m;
};
opt.SetMessageConsumer(examine_message);
std::vector<std::string> pass_flags = {
"--strip-debug",
"--strip-reflect",
"--set-spec-const-default-value=23:42 21:12",
"--if-conversion",
"--freeze-spec-const",
"--inline-entry-points-exhaustive",
"--inline-entry-points-opaque",
"--convert-local-access-chains",
"--eliminate-dead-code-aggressive",
"--eliminate-insert-extract",
"--eliminate-local-single-block",
"--eliminate-local-single-store",
"--merge-blocks",
"--merge-return",
"--eliminate-dead-branches",
"--eliminate-dead-functions",
"--eliminate-local-multi-store",
"--eliminate-common-uniform",
"--eliminate-dead-const",
"--eliminate-dead-inserts",
"--eliminate-dead-variables",
"--fold-spec-const-op-composite",
"--loop-unswitch",
"--scalar-replacement=300",
"--scalar-replacement",
"--strength-reduction",
"--unify-const",
"--flatten-decorations",
"--compact-ids",
"--cfg-cleanup",
"--local-redundancy-elimination",
"--loop-invariant-code-motion",
"--reduce-load-size",
"--redundancy-elimination",
"--private-to-local",
"--remove-duplicates",
"--workaround-1209",
"--replace-invalid-opcode",
"--simplify-instructions",
"--ssa-rewrite",
"--copy-propagate-arrays",
"--loop-fission=20",
"--loop-fusion=2",
"--loop-unroll",
"--vector-dce",
"--loop-unroll-partial=3",
"--loop-peeling",
"--ccp",
"-O",
"-Os",
"--legalize-hlsl"};
EXPECT_TRUE(opt.RegisterPassesFromFlags(pass_flags));
// Test some invalid flags.
EXPECT_FALSE(opt.RegisterPassFromFlag("-O2"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
EXPECT_FALSE(opt.RegisterPassFromFlag("-loop-unroll"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
EXPECT_FALSE(opt.RegisterPassFromFlag("--set-spec-const-default-value"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
EXPECT_FALSE(opt.RegisterPassFromFlag("--scalar-replacement=s"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
EXPECT_FALSE(opt.RegisterPassFromFlag("--loop-fission=-4"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
EXPECT_FALSE(opt.RegisterPassFromFlag("--loop-fusion=xx"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
EXPECT_FALSE(opt.RegisterPassFromFlag("--loop-unroll-partial"));
EXPECT_EQ(msg_level, SPV_MSG_ERROR);
}
} // namespace
} // namespace opt
} // namespace spvtools
| 33.258772 | 79 | 0.687723 | [
"vector"
] |
90ac9e8d5facc76503a0b811690160d14b137163 | 21,002 | cpp | C++ | csl/cslbase/newstub.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | csl/cslbase/newstub.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | csl/cslbase/newstub.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | // newstub.cpp Copyright A C Norman 2020
//
// The object of this code is to be able to launch one of several binaries
// that are places in a directory adjacent to it. The one it picks
// should suit the context within which this program is run - 32 or 64 bit,
// Cygwin or native Windows.
/**************************************************************************
* Copyright (C) 2020, Codemist Ltd. A C Norman *
* *
* 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 relevant *
* copyright notice, this list of conditions and the following *
* disclaimer. *
* * Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials provided *
* with the distribution. *
* *
* THIS 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 OWNERS 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. *
*************************************************************************/
// $Id: newstub.cpp 5432 2020-10-15 20:40:59Z arthurcnorman $
// This should be compiled with one of the following symbols predefined:
// FAT32 isatty32 w32 cyg32
// FAT64 isatty64 w64 cyg64
// FAT3264 isatty32 isatty64 w32 w64 cyg32 cyg64
// FATWIN win32 win64
#include <cstdio>
#include <cstdint>
#include <cinttypes>
#include <cstring>
#include <windows.h>
#include <tchar.h>
#include <io.h>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <zlib.h>
#if defined FAT32
// A fat 32 bit binary can be run under either native windows or
// 32-bit cygwin. Since it is a linked as a console mode application
// it is not suitable for launching by double-clicking. This is
// going to be usefully smaller than the FAT3264 binary, but whether the
// space saving makes the extra complication of having this one available
// is yet to be determined!
#define NUMBER_OF_MODULES 3
#define MODULE_ISATTY32 0
#define MODULE_WIN32 1
#define MODULE_CYG32 2
#elif defined FAT64
// A fat 64 bit binary can be run under either native windows or
// 64-bit cygwin. Since it is a linked as a console mode application
// it is not suitable for launching by double-clicking. This is
// going to be usefully smaller than the FAT3264 binary, but whether the
// space saving makes the extra complication of having this one available
// is yet to be determined!
#define NUMBER_OF_MODULES 3
#define MODULE_ISATTY64 0
#define MODULE_WIN64 1
#define MODULE_CYG64 2
#elif defined FAT3264
// A fat 64 bit binary is the full works, supporting either 32 or 64-bit
// usage either under native windows or either 32 or 64-bit cygwin, To
// cope with all of this makes if the biggest of all the binaries established
// here.
#define NUMBER_OF_MODULES 6
#define MODULE_ISATTY32 0
#define MODULE_ISATTY64 1
#define MODULE_WIN32 2
#define MODULE_WIN64 3
#define MODULE_CYG32 4
#define MODULE_CYG64 5
#elif defined FATWIN
// A fat windows binary is linked as a windows application and as such
// is not useful for launching from a console or cygwin - but it is good for
// double-clicking on. The version here will take advantage of 64-bit
// windows if run in that context.
#define NUMBER_OF_MODULES 2
#define MODULE_WIN32 0
#define MODULE_WIN64 1
#else
#error Unknown version of stub code
#endif
#ifndef FAT32
// FAT32 only support 32-bit versions (windows or cygwin) so does
// not need this.
// The next function is as shown at
// msdn.microsoft.com/en-us/library/windows/desktop/ms684139%28v=vs.85%29.aspx
// as the proper way to detect when the current 32-bit program is in fact
// running under Wow64 (ie with a 64-bit version of Windows beneath its feet).
typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process;
BOOL IsWow64()
{ BOOL bIsWow64 = FALSE;
// IsWow64Process is not available on all supported versions of Windows.
// Use GetModuleHandle to get a handle to the DLL that contains the function
// and GetProcAddress to get a pointer to the function if available. Well
// probably these days it is always available on operating systems that matter,
// but the hack here is fairly simple and local so to be kind to the
// historical world I will preserve it for a while!
fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
GetModuleHandle(TEXT("kernel32")),"IsWow64Process");
if(nullptr != fnIsWow64Process)
{ if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
{ //handle error - well heer I just return "no"
return FALSE;
}
}
return bIsWow64;
}
#endif // FAT32
static int64_t read8(std::FILE *f)
{ int64_t r = 0;
int i;
for (i=0; i<8; i++)
{ int w = std::getc(f) & 0xff;
r |= ((int64_t)w) << (8*i);
}
return r;
}
static char pPath[MAX_PATH];
static int64_t address[NUMBER_OF_MODULES];
static int64_t length[NUMBER_OF_MODULES];
//
// Run the program stored with this code and kept as a resource with
// the specified index.
//
#define ERROR_UNABLE_TO_OPEN_SELF 81
#define ERROR_BAD_LEADER 82
#define ERROR_BAD_TRAILER 83
#define ERROR_NO_MEMORY 84
#define ERROR_PROCESS_INFO 85
#define ERROR_CREATEPROCESS 86
#define ERROR_UNABLE_TO_WRITE 87
#define ERROR_NO_TEMP_FILE 88
int RunResource(int index, int forcegui, const char *modulename)
{ std::FILE *src, *dest;
int i;
uint64_t hdr;
#ifdef DEBUG
std::printf("RunResource %s: %d %d\n", modulename, index, forcegui);
std::fflush(stdout);
#endif
GetModuleFileName(nullptr, pPath, sizeof(pPath));
#ifdef DEBUG
std::printf("my name is %s\n", pPath);
std::fflush(stdout);
#endif
char *lastsep = std::strrchr(pPath, '\\');
std::sprintf(lastsep, "\\reduce.dir\\%s", modulename);
#ifdef DEBUG
std::printf("Code to run %s\n", pPath);
std::fflush(stdout);
#endif
const char *cmd = GetCommandLine();
char *cmd1 = reinterpret_cast<char *>(std)::malloc(std::strlen(
cmd) + 12);
if (cmd1 == nullptr)
{ std::printf("No memory for new command line\n");
std::fflush(stdout);
return ERROR_NO_MEMORY;
}
std::strcpy(cmd1, cmd);
// Now a rather horrible mess. I will have several versions of Reduce
// created here
// reduce.exe the general one
// reduce32.exe only supports 32-bit systems
// winreduce.exe for double-clicking - does not support cygwin
// [winreduce32.exe] double-clickable and 32-bit only
// The last of these does not go through this packing process.
// To cope with all of those the code inside Reduce will strin "win" from
// the front of an application and "32" from the end before using it
// to decide where to look for an image file. That way all the above
// will be able to use a single file "reduce.img". Further it will be
// essential that this name be picked up from argv[0] not from the
// name of the file that the application was actually launches from since
// the latter is the weird temporary file I just created.
// [Hmm - the naming conventions here need review...]
if (forcegui) std::strcat(cmd1, " --gui");
STARTUPINFO peStartUpInformation;
PROCESS_INFORMATION peProcessInformation;
std::memset(&peStartUpInformation, 0, sizeof(STARTUPINFO));
peStartUpInformation.cb = sizeof(STARTUPINFO);
std::memset(&peProcessInformation, 0, sizeof(PROCESS_INFORMATION));
#ifdef DEBUG
std::printf("Launch <%s> cmd line <%s>\n", pPath, cmd1);
std::fflush(stdout);
#endif
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
// _set_abort_behavior(0,_WRITE_ABORT_MSG | _CALL_REPORTFAULT);
if (CreateProcessA(pPath, // appname
cmd1, // command line
nullptr, // process attributes
nullptr, // thread attributes
1, // inherits handles
0, // allow it to run now
nullptr, // environment
nullptr, // current directory
&peStartUpInformation,
&peProcessInformation))
{ WaitForSingleObject(peProcessInformation.hProcess, INFINITE);
DWORD rc;
if (GetExitCodeProcess(peProcessInformation.hProcess, &rc) == 0)
rc = ERROR_PROCESS_INFO; // Getting the return code failed!
#ifdef DEBUG
std::printf("CreateProcess happened, rc reported as %d = %#x\n", rc,
rc);
#endif
std::fflush(stdout);
CloseHandle(peProcessInformation.hProcess);
CloseHandle(peProcessInformation.hThread);
return rc;
}
else
{
#ifdef DEBUG
std::printf("CreateProcess failed\n"); std::fflush(stdout);
DWORD dw = GetLastError();
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,
0,
nullptr);
std::printf("CreateProcess failed (%d): %s\n", dw, lpMsgBuf);
std::fflush(stdout);
#endif
return ERROR_CREATEPROCESS;
}
}
static const char *dll32[] =
{
#include "dll32.cpp"
nullptr
};
static const char *dll64[] =
{
#include "dll64.cpp"
nullptr
};
#include <windows.h>
#include <cstdio>
void dllcheck(const char **table)
{ int i, messaged = 0;
for (i=0; table[i]!=nullptr; i++)
{ HMODULE h = LoadLibraryEx(table[i], nullptr,
DONT_RESOLVE_DLL_REFERENCES);
if (h == nullptr)
{ if (!messaged)
{ std::printf("\nCygwin needs at least %s", table[i]);
messaged = 3;
}
else if (messaged >= 5)
{ std::printf(",\n %s", table[1]);
messaged = 1;
}
else
{ std::printf(", %s", table[i]);
messaged++;
}
}
else FreeLibrary(h);
}
if (messaged)
{ std::printf("\n");
std::printf("Please run cygwin setup and install packages that will\n");
std::printf("provide these. Then try again.\n\n");
std::fflush(stdout);
}
}
int main(int argc, char* argv[])
{
// The logic here starts by collecting information as to whether I am being
// run in a context where things have access to a console.
// This will NOT be the case if the code is run from mintty (the current
// cygwin terminal), a cygwin X terminal or via ssh into a cygwin version
// of sshd. However if either input or output is connected to a disc file
// I will act the same way that I would have if there had been direct
// contact to a Windows console since in that case the run is (probably)
// non-interactive and so terminal handling is not an issue.
// Furthermore the command-line option "--", (which is used here to redirect
// the standard output) is detected and is similarly viewed as a signature
// of non-interactive use.
//
// What this is really about is deciding if there is a risk that I need to
// use the Cygwin console API.
//
// There are times in this code where I may try to launch other programs
// in ways that could potentially pop up unwanted and ugly error boxes. I
// try to disable that here.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
int possibly_under_cygwin = 1, rc;
//
// I will start by detecting a number of cases where I will NOT want to
// use the cygwin version of the code. So
// (a) If I am attached to a regular Windows console then I am certainly
// not under a cygwin mintty style console (or linked in over ssh),
// and I am very liable to have a Windows display available. So there is
// no point in using cygwin even if it is available.
// (b) If the user has put "-- file" on the command line then that redirects
// the output to a file. In that case again there is no point in trying
// to use cygwin console management and I feel happier defaulting to
// use of the native windows version.
// (c) If either stdin or stdout is attached to a "disk" file then as in case
// (b) I am not interactive enough to need cygwin console handling. Note
// that if I was under mintty (etc) stdin and stdout would appear to
// be attached to pipes rather than to a disk file.
//
// However if a command line flag "--cygwin" is provided I will make that
// force use of Cygwin. That use-case is required for people to use the
// "cuba" package on Windows because the Cuba-4.1 library is not available
// for and will not build for native Windows. If "--cygwin" is specified
// the code will only even attempt to run a GUI if DISPLAY is set, and in
// that case it will expect an X-windows server to be available for use.
CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE h0 = GetStdHandle(STD_INPUT_HANDLE);
HANDLE h1 = GetStdHandle(STD_OUTPUT_HANDLE);
int t0 = GetFileType(h0),
t1 = GetFileType(h1);
int gcsbi = GetConsoleScreenBufferInfo(h1, &csbi);
int force_cygwin = 0, dashdash = 0, i;
for (i=1; i<argc; i++)
{ if (std::strcmp(argv[i], "--") == 0) dashdash = 1;
else if (std::strcmp(argv[i], "--cygwin") == 0) force_cygwin = 1;
}
if (!force_cygwin &&
(gcsbi || // console available: can use Windows API
dashdash || // "--" seen: no console API needed
t0==FILE_TYPE_DISK || // stdin or stdout disk: no console API needed
t1==FILE_TYPE_DISK)) possibly_under_cygwin = 0;
//
// This stub runs as 32-bit code, but if it is on a 64-bit version of
// windows it will be running under "wow64". Checking for that should allow
// me to know if there is any prospect of running a 64-bit version of the
// application - and if I can then I should!
//
#ifdef FAT32
// I find it easier to have these variables present even when they are
// then not used. I rather expect that the C compiler will optimise away
// any potential code clumsiness.
int wow64 = 0;
#else // FAT32
int wow64 = IsWow64();
#ifdef DEBUG
// While debugging this code a "--32" on the command line disables 64 bit use.
// The only need for that that I can really see is when checking the code
// to verify that it works. But if somebody found a situation where it was
// valuable I could reinstate and publicise it.
for (i=1; i<argc; i++)
{ if (std::strcmp(argv[i], "--32") == 0)
{ wow64 = 0;
}
}
#endif // DEBUG
#endif // FAT32
int forcegui = 0;
#ifndef FATWIN
// The FATWIN case does not support cygwin at all...
if (possibly_under_cygwin)
{ int cygwin32 = 0;
// Here I want to execute cygwin_isatty.exe (and/or cygwin64_isatty.exe).
// There can not merely have their code incorporated here directly
// because they are cygwin programs and so their startup is rather
// different from this native windows code. I had at one stage tried
// loading the cygwin dlls by hand to start simulating the cygwin startup
// but I failed to make that work!
//
// The logic here is that cygwin_isatty checks if stdin and stdout (as seen in
// a cygwin context) are direct from the terminal. It appears hard to
// tell if this would be the case without running cygwin code. It will also
// test if cygwin is availlable at all (in that the helper program launched
// here will fail utterly if not - and that can sort out whether 32 or
// 64-bit cygwin is available).
// If stdin and stdout are attached to the tty and if also the environment
// variables DISPLAY and SSH_HOST are unset and the user did not put
// "--nogui" on the command line then even though I am under a cygwin console
// it looks as if I might run a windows GUI. I force that by adding "--gui"
// to the command line and run a windows (rather than cygwin) version.
// If stdin and stdout where attached to the tty otherwise I will use cygwin.
// If DISPLAY is set and "--nogui" is not present it will launch an X11
// windowed GUI, otherwise it will run in console mode.
// Finally either stdin or stdout has been redirected in the cygwin world,
// and since I will in effect be in batch mode I can drop back and use the
// windows binaries.
//
int rc = -1;
#if defined FAT64 || defined FAT3264
if (wow64) rc = RunResource(MODULE_ISATTY64, 0, "isatty64");
#endif // FAT64
#ifndef FAT64
if (rc != 0)
{ rc = RunResource(MODULE_ISATTY32, 0, "isatty32");
#if defined FAT3264
if (rc == 0) cygwin32 = 1;
#endif // FAT3264
}
#endif // FAT64
// If one of stdin or stdout is not connected to a cygwin console there is
// no point in trying to use cygwin at all. That is unless the user is
// explicitly forcing things. If the user specified "--cygwin" and does
// not launch from a context where cygwin1.dll and so on are available
// they need to expect failure.
if (!force_cygwin && rc != 0) possibly_under_cygwin = 0;
// If DISPLAY and SSH_ENV are both null then I will look at the command
// line options... "--cygwin" trumps most other options.
else if (std::getenv("DISPLAY") == nullptr &&
std::getenv("SSH_HOST") == nullptr &&
!force_cygwin)
{ int nogui = 0;
// ... I look for "--nogui" (or the abbreviations "-w" or "-w-") ...
for (i=1; i<argc; i++)
{ if (std::strcmp(argv[i], "--nogui") == 0 ||
std::strcmp(argv[i], "-w") == 0 ||
std::strcmp(argv[i], "-w-") == 0)
{ nogui = 1;
break;
}
}
// If there was NOT a "--nogui" then I will run a native windows
// version.
if (nogui == 0)
{ possibly_under_cygwin = 0;
forcegui = 1;
}
// Otherwise if I found cygwin32 rather than cygwin64 I must use that version.
else if (cygwin32) wow64 = 0;
}
// Here DISPLAY or SSH_HOST was set so I just have to choose which cygwin
// version to use.
else if (cygwin32) wow64 = 0;
}
#else
possibly_under_cygwin = 0;
#endif // FATWIN
#ifdef DEBUG
std::printf("Analysis yields wow64=%d cygwin=%d forcegui=%d\n",
wow64, possibly_under_cygwin, forcegui);
#endif
//
// Now I will run the version of Reduce that I have picked. All the #ifdef
// stuff is to allow for smaller binaries that support only a subset of the
// cases.
//
switch ((wow64<<4) | possibly_under_cygwin)
{
#ifndef FAT64
case 0x00:
return RunResource(MODULE_WIN32, forcegui, "win32");
#endif
#ifndef FAT32
case 0x10:
return RunResource(MODULE_WIN64, forcegui, "win64");
#endif
#ifndef FATWIN
#ifndef FAT64
case 0x01:
rc = RunResource(MODULE_CYG32, forcegui, "cyg32");
if (rc != 0)
{ dllcheck(dll32);
}
return rc;
#endif
#ifndef FAT32
case 0x11:
rc = RunResource(MODULE_CYG64, forcegui, "cyg64");
if (rc != 0)
{ dllcheck(dll64);
}
return rc;
#endif // FAT32
#endif // FATWIN
default:
return 1;
}
}
// End of newstub.cpp
| 38.820702 | 80 | 0.633083 | [
"object"
] |
90af45d9d12a338ea32f00808cf7c65dcbf6e2cb | 998 | cpp | C++ | day6/day6.cpp | cristicretu/advent_of_code2020 | 456969f98bd6df56800301a006fbd6971957914e | [
"MIT"
] | 1 | 2022-01-27T17:09:33.000Z | 2022-01-27T17:09:33.000Z | day6/day6.cpp | cristicretu/advent_of_code2020 | 456969f98bd6df56800301a006fbd6971957914e | [
"MIT"
] | null | null | null | day6/day6.cpp | cristicretu/advent_of_code2020 | 456969f98bd6df56800301a006fbd6971957914e | [
"MIT"
] | null | null | null |
/**
* author: etohirse
* created: 16.12.2020 13:47:57
**/
#include <fstream>
#include <unordered_set>
#include <vector>
std::ifstream fin("input.in");
std::ofstream fout("input.out");
int solve1(std::string s) {
std::unordered_set<char> as;
for (char d : s) as.insert(d);
return as.size() - 1;
}
int solve2(std::string s, int cnt) {
int fv[200] = {0};
for (char d : s) fv[int(d)] += 1;
int ans(0), cc(0);
for (char d : s) {
if (d != '/') {
if (fv[int(d)] == cnt) ans++;
} else {
cc++;
if (cc == 2) return ans;
}
}
}
int main() {
std::string s, curr = "";
int ans(0), ans1(0), count(0);
while (getline(fin, s)) {
if (s.size() != 0) {
curr = curr + '/' + s;
count++;
} else {
ans += solve1(curr);
curr += '/';
ans1 += solve2(curr, count);
count = 0;
curr = "";
}
}
if (curr != "") {
ans += solve1(curr);
ans1 += solve2(curr, count);
}
fout << ans1;
return 0;
}
| 17.821429 | 36 | 0.48497 | [
"vector"
] |
90af7f6737c73b349f1002f941fa5688e63c90d4 | 11,660 | cpp | C++ | test.cpp | kotton21/PotScanner | d6206fe8d27e8077d49b62aa72940bf91a2d43d0 | [
"MIT"
] | 2 | 2018-02-21T19:25:46.000Z | 2019-04-02T18:23:00.000Z | test.cpp | kotton21/PotScanner | d6206fe8d27e8077d49b62aa72940bf91a2d43d0 | [
"MIT"
] | null | null | null | test.cpp | kotton21/PotScanner | d6206fe8d27e8077d49b62aa72940bf91a2d43d0 | [
"MIT"
] | null | null | null | /*
* test.cpp
*
* Created on: Jan 2, 2017
* Author: karl
*/
#include <cv.h>
#include <highgui.h>
using namespace cv;
//#include <stdio>
//#include <dirent.h>
#include <cstdlib>
#include <cmath>
#include <ctgmath>
#include <math.h> /* sin */
#define PI 3.14159265
using std::cout;
using std::endl;
//points in images (x, y)
class ImagePoint : public Point {
public:
ImagePoint(int x, int y) {
this->x = x;
this->y = y;
}
ImagePoint(const ImagePoint& obj) : ImagePoint(obj.x, obj.y) { }
};
//points in theta, phi, z.
class AnglePoint {
public:
AnglePoint(float theta, float phi, float z)
: theta(theta), phi(phi), z(z)
{ }
float theta;
float phi;
float z;
};
//Converted to 3d
class LinearEqn {
public:
float m;
float b;
float z;
LinearEqn(float m, float b, float z)
: m(m), b(b), z(z) { } // simple constructor
LinearEqn(const LinearEqn &eqn)
: m(eqn.m), b(eqn.b), z(eqn.z) { } // copy constructor
~LinearEqn() { } // destructor
float y(float x) {
return m*x + b;
}
// Ignores potential z-height errors..
Point3f Intersection(LinearEqn eqn) {
float x = (eqn.b - this->b) / (this->m - eqn.m);
float y = this->m*x + this->b;
return Point3f(x,y,z);
}
void Rotate(const float phiRad) {
float mp = this->m + phiRad;
float xp = -this->b*sin(phiRad);
float yp = this->b*cos(phiRad);
float bp = yp-mp*xp;
this->m = mp;
this->b = bp;
}
};
// this accounts to creating a type in order to handle a single variable
// wouldn't a vector of vectors work just fine?
//class AnglePointMap: Mat {
//public:
// AnglePointMap(int height, int numAngles) : Mat(height, numAngles, CV_32FC3) {}
// void set(int y, int x, AnglePoint pt) {
//
// }
// AnglePoint get(int y, int x) {
//
// }
//};
using AnglePointMap = vector<vector<AnglePoint>>;
//a 2d map of any type. must provide own functionality for resizing
template<typename T>class VectorMap {
public:
vector<vector<T>> vmap;
int height;
int width;
VectorMap(int height, int width, T defaultFill) : height(height), width(width) {
vmap.reserve(height);
for (int h=0; h<height; ++h){
vmap.push_back( vector<T>(width, defaultFill));
}
}
// VectorMap(&VectorMap obj) : VectorMap(obj.height, obj.width, ) { }
void set(const int y, const int x, T& pt) {
vmap.at(y).at(x) = pt;
}
T get(const int y, const int x) const {
return vmap.at(y).at(x);
}
// void doFunc(VectorMap<Point2f>& toMap, void (*func)(VectorMap&, VectorMap&, int, int) ) { //B //
// for (int h=0; h < height; ++h) {
// for (int w=0; w < width; ++w) {
// func(*this,toMap,h,w); //
// }
// }
// }
};
//void funcDoIntersections(VectorMap<LinearEqn>& from, VectorMap<Point2f>& to, int h, int w) { // to
// LinearEqn curr = from.get(h,w);
// LinearEqn next = from.get(h,(w+1)%from.width);
//
// Point2f intersection = curr.Intersection(next);
// to.set(h,w,intersection);
//}
void DoIntersection(VectorMap<LinearEqn>& from, VectorMap<Point3f>& to) {
LinearEqn curr (0,0,0);
LinearEqn next (0,0,0);
for (int h=0; h < from.height; ++h) {
for (int w=0; w < from.width; ++w) {
curr = from.get(h,w);
next = from.get(h,(w+1)%from.width);
Point3f intersection = curr.Intersection(next);
to.set(h,w,intersection);
}
}
}
void DoMidpoints(VectorMap<Point3f>& from, VectorMap<Point3f>& to) {
Point3f curr (0,0,0);
Point3f next (0,0,0);
for (int h=0; h < from.height; ++h) {
for (int w=0; w < from.width; ++w) {
curr = from.get(h,w);
next = from.get(h,(w+1)%from.width);
Point3f midpoint = Point3f( (curr.x + next.x)/2,
(curr.y + next.y)/2,
(curr.z + next.z)/2);
to.set(h,w,midpoint);
}
}
}
void dispImage(Mat image) {
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image", image );
waitKey(0);
}
void dispEdge(const vector<ImagePoint> edges, Mat img, const int centerCol = 0) {
cout << "edges: " << edges.size() << endl;
for(auto vert: edges) {
circle(img, vert, 3, Scalar(0,0,255), 2);
}
if (centerCol > 0) {
for (int r = 0; r<img.rows; ++r) {
img.at<Vec3b>(r,centerCol) = Vec3b(0,0,255);
}
}
dispImage(img);
}
vector<ImagePoint> detectEdges(const Mat hsv, const int NUMVERTSTEPS, const int CENTERCOL) {
//Mat detectEdges(Mat hsv) {
vector<ImagePoint> edges;
edges.reserve(NUMVERTSTEPS);
int pixelstep = hsv.rows / NUMVERTSTEPS;
// int edges[hsv.rows/10] = {};
//Mat edges (1, hsv.rows/10, CV_16UC2, 0);
int r = 0, i = 0;
while (r < hsv.rows) {
bool found = false;
//for (int c=0; c < hsv.cols; c++) {
// don't look any farther than center column
for (int c=0; c < CENTERCOL; c++) {
//hue from 205-265, saturation > 50%, value > 30% ?
Vec3b pt = hsv.at<Vec3b>(r,c);
//why the hell is the hue value so small? It never goes above 17.
if (int(pt.val[0]) > 100 && int(pt.val[0]) < 135 &&
int(pt.val[1]) > 125 &&
int(pt.val[2]) > 100) {
//save point
ImagePoint vert (CENTERCOL - c,r);
edges.push_back(vert);
//edges.at<Point>(i) = vert;
//skip to next row
found = true;
break;
}
}
if (!found) { edges.push_back(ImagePoint(0,r)); }
i = i + 1;
r = r + pixelstep;
}
return edges;
}
//Certainly not optimized for speed lolz
//also, this is only valid for orthographic views.
vector<Point3f> getCartesion(vector<Point> points, int theta, int centerCol) {
vector<Point3f> polar; // r, theta, z representation
for (auto point: points) {
Point3f ppt (abs(centerCol - point.x), theta, point.y);
polar.push_back(ppt);
}
vector<Point3f> cartesian; // x, y, z representation
for (auto point: polar) {
Point3f ppt (point.x * cos(point.y * PI / 180.),
point.x * sin(point.y * PI / 180.),
point.z);
polar.push_back(ppt);
}
return cartesian;
}
vector<AnglePoint> getThetas(const vector<ImagePoint> edges, const float focalDist, const float phi) {
vector<AnglePoint> thetas;
thetas.reserve(edges.size());
for (auto edge: edges) {
float theta = atan(edge.x/focalDist);
thetas.push_back(AnglePoint(theta, phi, edge.y));
}
return thetas;
}
//class OrthoFrameGetter {
//public:
//
//};
//vector<string> filenames(const char* dir) {
// DIR *dirp;
// int len = strlen(dir);
// dirp = opendir(".");
// while ((dp = readdir(dirp)) != NULL)
// if (dp->d_namlen == len && !strcmp(dp->d_name, dir)) {
// (void)closedir(dirp);
// return FOUND;
// }
// (void)closedir(dirp);
// return NOT_FOUND;
//}
//generates two triangle verts and indices for each square.
//essentially translates the 2d Vertex matrix into a 1D matrix + index values.
void OrientRadialTrisVerts(VectorMap<Point3f>& pts, Vector<Point3f>& verts, Vector<Point3i>& tris) {
// Point3f pt1 (0,0,0);
// Point3f pt2 (0,0,0);
// Point3f pt3 (0,0,0);
// Point3f pt4 (0,0,0);
//add each point to verts for each itteration.
for (int h=0; h < pts.height; ++h) {
for (int w=0; w < pts.width; ++w) {
verts.push_back(pts.get(h,w));
}
}
//height levels first...
for (int h=0; h < pts.height-1; ++h) {
for (int w=0; w < pts.width; ++w) {
// pt1 = pts.get(h,w); //top left
// pt2 = pts.get(h,(w+1)%pts.width); //top right, width wraps around object
// pt3 = pts.get(h+1,w); //bottom left
// pt4 = pts.get(h+1,(w+1)%pts.width); //bottom right, width wraps around object
int i1 = (h*pts.height)+w; //top left
int i2 = (h*pts.height)+((w+1)%pts.width); //top right, width wraps around object
int i3 = ((h+1)*pts.height)+w; //bottom left
int i4 = ((h+1)*pts.height)+((w+1)%pts.width); //bottom right, width wraps around object
//add 3 verts for each triangle
tris.push_back(Point3i(i1,i3,i2));
tris.push_back(Point3i(i2,i3,i4));
}
}
}
#include <iostream>
#include <fstream>
#include <ctime>
using std::ofstream;
void WriteVerts(Vector<Point3f>& verts, ofstream& out, float s) {
for (auto vert: verts) {
out << "v " << vert.x*s << " " << vert.y*s << " " << vert.z*s << "\n";
}
}
void WriteTris(Vector<Point3i>& tris, ofstream& out) {
for (auto tri: tris) {
out << "f " << tri.x << " " << tri.y << " " << tri.z << "\n";
}
}
int write (string filename, string desc, Vector<Point3f>& verts, Vector<Point3i>& tris, float s) {
ofstream myfile;
myfile.open (filename);
//write header:
time_t t = time(0);
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< endl;
myfile << "Filename: " << filename << "\n";
myfile << "Date: " << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday << "\n";
myfile << "Description: " << desc << "\n\n";
//write tris and verts
WriteVerts(verts,myfile,s);
myfile << "\n";
WriteTris(tris,myfile);
myfile.close();
return 0;
}
int main( int argc, char** argv ) {
vector<string> filenames = {"0.jpg", "30.jpg", "60.jpg",
"90.jpg", "120.jpg", "150.jpg",
"240.jpg", "270.jpg", "300.jpg", "330.jpg"};
Mat image;
//image = imread( argv[1], 1 );
Rect roi (1000,1000,500,500); //user input
int CENTERCOL = 417; //user input or determined by machine architecture
int NUMANGLES = filenames.size();
int NUMVERTSTEPS = 10;
float FOCALDIST = 2000;
AnglePointMap apMap; //used because I don't know how big this is??
apMap.reserve(NUMANGLES);
float phi = 0;
for (unsigned int i = 0; i < filenames.size(); ++i) {
// Region of Interest
image = imread( "pics/"+filenames[i], 1 );
Mat image_roi(image, Rect(2500, 500, 800, 600)); // x0, y0, w, h
Mat hsv;
cvtColor(image_roi, hsv, CV_BGR2HSV);
//Mat edges = detectEdges(hsv);
vector<ImagePoint> edges = detectEdges(hsv, NUMVERTSTEPS, CENTERCOL);
vector<AnglePoint> anglePoints;
anglePoints = getThetas(edges, FOCALDIST, phi);
phi = phi + 30.0;
apMap.push_back(anglePoints);
//dispEdge(edges, image_roi, CENTERCOL);
}
//VectorMap<ImagePoint> edgesMap (NUMVERTSTEPS, NUMANGLES, ImagePoint(0,0));
//cout << "NumVertSteps: " << NUMVERTSTEPS << " " << apMap.size() << endl;
//cout << "NUMANGLES: " << NUMANGLES << " " << apMap.at(0).size() << endl;
//now have a 2d vector of AnglePoints. Build the map.
//VectorMap considers the texture as rolled off. Need to transpose the AnglePoints.
//This is starting to look an awfull lot like i'm just writing a linear algebra library.
VectorMap<LinearEqn> eqns (NUMVERTSTEPS, NUMANGLES, LinearEqn(0,0,0));
for (int h=0; h<NUMVERTSTEPS; ++h) {
for (int w=0; w<NUMANGLES; ++w) {
AnglePoint pt = apMap.at(w).at(h);
float m = tan(pt.theta);
float b = m*FOCALDIST;
LinearEqn thiseqn (m,b,pt.z);
//rotate the equation about the origin...
//actually rotate the points, then build the equation.
thiseqn.Rotate(pt.phi * PI / 180);
eqns.set(h, w, thiseqn);
}
}
// where is the angle phi incorporated??
//Now have a map of linear equations.. no obvious float range problems so far.
//Build Intersection Points? Can I do this in the existing map?
//Give LinearEqn knowledge of its adjacent item?
VectorMap<Point3f> intersections (NUMVERTSTEPS, NUMANGLES, Point3f(0,0,0));;
//Beqns.doFunc(intersections, &funcDoIntersections); //;, intersections
DoIntersection(eqns, intersections);
VectorMap<Point3f> midpoints (NUMVERTSTEPS, NUMANGLES, Point3f(0,0,0));;
DoMidpoints(intersections, midpoints);
//compute
Vector<Point3f> verts;
Vector<Point3i> tris;
OrientRadialTrisVerts(midpoints, verts, tris);
//write to file
write ("out.obj", "test cylinders", verts, tris, 1./300.);
// dispEdge(edges, image_roi, centerCol);
// Mat clipped;
// inRange(hsv, Scalar(100, 100, 100), Scalar(135,255,255), clipped);
//
// dispImage(clipped);
return 0;
}
| 25.682819 | 102 | 0.626329 | [
"object",
"vector",
"3d"
] |
90b1fa460212687ffb252979eaac3d8f56ffaeab | 4,810 | cc | C++ | quisp/modules/Application/Application_test.cc | TSarkar99/quisp | 1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da | [
"BSD-3-Clause"
] | null | null | null | quisp/modules/Application/Application_test.cc | TSarkar99/quisp | 1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da | [
"BSD-3-Clause"
] | null | null | null | quisp/modules/Application/Application_test.cc | TSarkar99/quisp | 1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da | [
"BSD-3-Clause"
] | null | null | null | #include "Application.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <omnetpp.h>
#include <test_utils/TestUtils.h>
#include "classical_messages_m.h"
namespace {
using namespace omnetpp;
using namespace quisp::utils;
using namespace quisp::modules;
using namespace quisp_test;
class Strategy : public quisp_test::TestComponentProviderStrategy {
public:
Strategy(TestQNode *_qnode) : parent_qnode(_qnode) {}
cModule *getQNode() override { return parent_qnode; }
private:
TestQNode *parent_qnode;
};
class AppTestTarget : public quisp::modules::Application {
public:
using quisp::modules::Application::getParentModule;
using quisp::modules::Application::initialize;
using quisp::modules::Application::par;
cGate *gate(const char *gatename, int index = -1) override {
if (strcmp(gatename, "toRouter") != 0) {
throw cRuntimeError("unknown gate called");
}
return toRouterGate;
};
explicit AppTestTarget(TestQNode *parent_qnode) : Application(), toRouterGate(new TestGate(this, "toRouter")) {
this->provider.setStrategy(std::make_unique<Strategy>(parent_qnode));
setComponentType(new TestModuleType("test qnode"));
}
virtual ~AppTestTarget() { EVCB.gateDeleted(toRouterGate); }
std::vector<int> getOtherEndNodeAdresses() { return this->other_end_node_addresses; }
int getAddress() { return this->my_address; }
TestGate *toRouterGate;
};
TEST(AppTest, InitSimple) {
auto *sim = prepareSimulation();
auto *mock_qnode = new TestQNode{123};
auto *app = new AppTestTarget{mock_qnode};
setParBool(app, "EndToEndConnection", true);
setParInt(app, "NumberOfResources", 5);
setParInt(app, "num_measure", 1);
setParInt(app, "TrafficPattern", 0);
setParInt(app, "distant_measure_count", 100);
setParInt(app, "LoneInitiatorAddress", 0);
sim->registerComponent(app);
app->callInitialize();
ASSERT_EQ(app->getAddress(), mock_qnode->address);
ASSERT_EQ(app->getOtherEndNodeAdresses().size(), 0);
}
TEST(AppTest, Init_OneConnection_NoSender) {
auto *sim = prepareSimulation();
auto *mock_qnode = new TestQNode{123};
auto *app = new AppTestTarget{mock_qnode};
setParBool(app, "EndToEndConnection", true);
setParInt(app, "NumberOfResources", 5);
setParInt(app, "num_measure", 1);
setParInt(app, "TrafficPattern", 1);
setParInt(app, "distant_measure_count", 100);
setParInt(app, "LoneInitiatorAddress", 0);
sim->registerComponent(app);
app->callInitialize();
ASSERT_EQ(app->getAddress(), mock_qnode->address);
ASSERT_EQ(app->getOtherEndNodeAdresses().size(), 0);
}
TEST(AppTest, Init_OneConnection_Sender) {
auto *sim = prepareSimulation();
auto *mock_qnode = new TestQNode{123};
auto *app = new AppTestTarget{mock_qnode};
setParBool(app, "EndToEndConnection", true);
setParInt(app, "NumberOfResources", 5);
setParInt(app, "num_measure", 1);
setParInt(app, "TrafficPattern", 1);
setParInt(app, "distant_measure_count", 100);
setParInt(app, "LoneInitiatorAddress", mock_qnode->address);
sim->registerComponent(app);
auto *mock_qnode2 = new TestQNode{456};
app->callInitialize();
ASSERT_EQ(app->getAddress(), mock_qnode->address);
ASSERT_EQ(app->getOtherEndNodeAdresses().size(), 1);
sim->run();
// assert app sent one message to "toRouter" gate
ASSERT_EQ(app->toRouterGate->messages.size(), 1);
auto *msg = app->toRouterGate->messages.at(0);
ASSERT_NE(msg, nullptr);
auto *pkt = dynamic_cast<ConnectionSetupRequest *>(msg);
ASSERT_EQ(pkt->getActual_srcAddr(), 123);
ASSERT_EQ(pkt->getActual_destAddr(), mock_qnode2->address);
ASSERT_EQ(pkt->getSrcAddr(), 123);
ASSERT_EQ(pkt->getDestAddr(), 123);
ASSERT_EQ(pkt->getNumber_of_required_Bellpairs(), 5);
}
TEST(AppTest, Init_OneConnection_Sender_TrafficPattern2) {
auto *sim = prepareSimulation();
auto *mock_qnode = new TestQNode{123};
auto *mock_qnode2 = new TestQNode{456};
auto *app = new AppTestTarget{mock_qnode};
setParBool(app, "EndToEndConnection", true);
setParInt(app, "NumberOfResources", 5);
setParInt(app, "num_measure", 1);
setParInt(app, "TrafficPattern", 2);
setParInt(app, "distant_measure_count", 100);
setParInt(app, "LoneInitiatorAddress", 123);
sim->registerComponent(app);
app->callInitialize();
ASSERT_EQ(app->getAddress(), 123);
ASSERT_EQ(app->getOtherEndNodeAdresses().size(), 1);
sim->run();
ASSERT_EQ(app->toRouterGate->messages.size(), 1);
auto *msg = app->toRouterGate->messages.at(0);
ASSERT_NE(msg, nullptr);
auto *pkt = dynamic_cast<ConnectionSetupRequest *>(msg);
ASSERT_EQ(pkt->getActual_srcAddr(), 123);
ASSERT_EQ(pkt->getActual_destAddr(), mock_qnode2->address);
ASSERT_EQ(pkt->getSrcAddr(), 123);
ASSERT_EQ(pkt->getDestAddr(), 123);
ASSERT_EQ(pkt->getNumber_of_required_Bellpairs(), 5);
}
} // namespace
| 32.721088 | 113 | 0.725572 | [
"vector"
] |
ff9c8e9edc0ff335b7f523c5f74273bfb6664c30 | 3,330 | cpp | C++ | source/omni/ui/entity_toggle_widget.cpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | 33 | 2015-03-21T04:12:45.000Z | 2021-04-18T21:44:33.000Z | source/omni/ui/entity_toggle_widget.cpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | null | null | null | source/omni/ui/entity_toggle_widget.cpp | daniel-kun/omni | ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18 | [
"MIT"
] | 2 | 2016-03-05T12:57:05.000Z | 2017-09-12T10:11:52.000Z | #include <omni/ui/entity_toggle_widget.hpp>
#include <omni/ui/entity_widget_provider_base.hpp>
omni::ui::entity_toggle_widget::entity_toggle_widget (omni::core::context & context, entity_widget_provider_base & provider, QWidget * parent) :
entity_base_widget (parent),
_c (context),
_provider (provider),
_toggleAction ("Test", this),
_layout (this),
_entity (),
_viewWidget (),
_editWidget ()
{
_toggleAction.setShortcut (QKeySequence (Qt::Key_Return));
_toggleAction.setShortcutContext (Qt::WidgetWithChildrenShortcut);
addAction (& _toggleAction);
connect (& _toggleAction, SIGNAL(triggered()), SLOT (toggleViewMode()));
toggleViewMode ();
setAutoFillBackground (true);
setFocusPolicy (Qt::StrongFocus);
}
std::shared_ptr <omni::core::model::entity> omni::ui::entity_toggle_widget::getEntity ()
{
if (_viewWidget) {
return _viewWidget->getEntity ();
} else if (_editWidget) {
return _editWidget->getEntity ();
} else {
return std::shared_ptr <omni::core::model::entity> ();
}
}
void omni::ui::entity_toggle_widget::setEntity (std::shared_ptr <omni::core::model::entity> entity)
{
if (_viewWidget) {
_viewWidget->setEntity (entity);
} else if (_editWidget) {
_editWidget->setEntity (entity);
}
}
void omni::ui::entity_toggle_widget::focusInEvent (QFocusEvent * event)
{
QWidget::focusInEvent (event);
QPalette pal;
pal.setBrush (QPalette::Background, Qt::red);
setPalette (pal);
}
void omni::ui::entity_toggle_widget::focusOutEvent (QFocusEvent * event)
{
QWidget::focusOutEvent (event);
QPalette pal;
setPalette (pal);
}
omni::ui::entity_toggle_widget::Mode omni::ui::entity_toggle_widget::currentViewMode ()
{
if (_viewWidget) {
return Mode::m_view;
} else {
return Mode::m_edit;
}
}
omni::ui::entity_toggle_widget::Mode omni::ui::entity_toggle_widget::toggleViewMode ()
{
if (_viewWidget) {
// Go into edit mode:
bool hadFocus = hasFocus () || _viewWidget->hasFocus ();
_editWidget = _provider.createEditWidget (this, _c, *_viewWidget);
_layout.addWidget (_editWidget.get ());
_viewWidget.reset ();
if (hadFocus) {
_editWidget->setFocus (Qt::TabFocusReason);
}
setFocusProxy (_editWidget.get ());
return Mode::m_edit;
} else {
// Accept input, go into view mode:
bool hadFocus;
if (_editWidget) {
hadFocus = hasFocus () || _editWidget->hasFocus ();
} else {
hadFocus = hasFocus ();
}
_viewWidget = _provider.createViewWidget (this, _c, _editWidget.get ());
_editWidget.reset ();
_layout.addWidget (_viewWidget.get ());
setFocusProxy (nullptr);
if (hadFocus) {
setFocus (Qt::TabFocusReason);
}
return Mode::m_view;
}
}
void omni::ui::entity_toggle_widget::keyPressEvent (QKeyEvent * /*event*/)
{
/*
if (! _editProvider.keyPressEvent (event)) {
QWidget::keyPressEvent (event);
}
*/
}
/*
bool omni::forge::literal_edit_provider::keyPressEvent (QKeyEvent * event)
{
if (std::isalnum (event->key (), std::locale (""))) {
return true;
} else {
return false;
}
}
*/
| 27.983193 | 144 | 0.632432 | [
"model"
] |
ff9fafe8b9ecd6dd7075ddf6622a0a914e347317 | 3,402 | hpp | C++ | src/third_party/VisionWorks-1.6-Demos/nvxio/src/NVX/Render/StubRenderImpl.hpp | reveriel/cuda_scheduling_examiner_mirror | 16d2404c0dc8d72f7a13e4a167d3db4c86128a26 | [
"BSD-2-Clause-FreeBSD"
] | 39 | 2017-05-23T00:27:50.000Z | 2022-02-16T07:56:07.000Z | src/third_party/VisionWorks-1.6-Demos/nvxio/src/NVX/Render/StubRenderImpl.hpp | reveriel/cuda_scheduling_examiner_mirror | 16d2404c0dc8d72f7a13e4a167d3db4c86128a26 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2019-10-22T13:47:39.000Z | 2020-04-03T16:09:04.000Z | src/third_party/VisionWorks-1.6-Demos/nvxio/src/NVX/Render/StubRenderImpl.hpp | reveriel/cuda_scheduling_examiner_mirror | 16d2404c0dc8d72f7a13e4a167d3db4c86128a26 | [
"BSD-2-Clause-FreeBSD"
] | 14 | 2017-09-11T19:59:19.000Z | 2021-02-03T10:00:22.000Z | /*
# Copyright (c) 2014-2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef STUBRENDERIMPL_HPP
#define STUBRENDERIMPL_HPP
#include "Render/RenderImpl.hpp"
namespace nvidiaio
{
class StubRenderImpl :
public Render
{
public:
StubRenderImpl():
Render(nvxio::Render::UNKNOWN_RENDER, "Stub"),
windowWidth(), windowHeight()
{
}
virtual bool open(const std::string& title, uint32_t width, uint32_t height, nvxcu_df_image_e /*format*/)
{
windowHeight = height;
windowWidth = width;
windowTitle = title;
return true;
}
virtual void setOnKeyboardEventCallback(OnKeyboardEventCallback, void *) { }
virtual void setOnMouseEventCallback(OnMouseEventCallback, void *) { }
virtual void putImage(const image_t &) { }
virtual void putTextViewport(const std::string&, const TextBoxStyle &) { }
virtual void putFeatures(const array_t &, const FeatureStyle &) { }
virtual void putFeatures(const array_t &, const array_t &) { }
virtual void putLines(const array_t &, const LineStyle &) { }
virtual void putConvexPolygon(const array_t &, const LineStyle &) { }
virtual void putMotionField(const image_t &, const MotionFieldStyle&){}
virtual void putObjectLocation(const nvxcu_rectangle_t &, const DetectedObjectStyle &) { }
virtual void putCircles(const array_t &, const CircleStyle &) { }
virtual void putArrows(const array_t &, const array_t &, const LineStyle &) { }
virtual bool flush() { return true; }
virtual void close() { }
virtual uint32_t getViewportWidth() const
{
return windowWidth;
}
virtual uint32_t getViewportHeight() const
{
return windowHeight;
}
virtual ~StubRenderImpl()
{
}
protected:
uint32_t windowWidth;
uint32_t windowHeight;
std::string windowTitle;
};
} // namespace nvidiaio
#endif // STUBRENDERIMPL_HPP
| 35.810526 | 109 | 0.725456 | [
"render"
] |
ffb2d0029096803e279fa6bbabaa700300b49173 | 9,786 | cpp | C++ | Code/Engine/RendererVulkan/Resources/Implementation/TextureVulkan.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/Engine/RendererVulkan/Resources/Implementation/TextureVulkan.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/Engine/RendererVulkan/Resources/Implementation/TextureVulkan.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #include <RendererVulkanPCH.h>
#include <RendererVulkan/Device/DeviceVulkan.h>
#include <RendererVulkan/Resources/TextureVulkan.h>
ezGALTextureVulkan::ezGALTextureVulkan(const ezGALTextureCreationDescription& Description)
: ezGALTexture(Description)
, m_image(nullptr)
, m_memory(nullptr)
, m_memoryOffset(0)
, m_memorySize(0)
, m_pExisitingNativeObject(nullptr)
{
// TODO existing native object in descriptor?
}
ezGALTextureVulkan::~ezGALTextureVulkan() {}
EZ_DEFINE_AS_POD_TYPE(D3D11_SUBRESOURCE_DATA);
ezResult ezGALTextureVulkan::InitPlatform(ezGALDevice* pDevice, ezArrayPtr<ezGALSystemMemoryDescription> pInitialData)
{
ezGALDeviceVulkan* pVulkanDevice = static_cast<ezGALDeviceVulkan*>(pDevice);
if (m_Description.m_pExisitingNativeObject != nullptr)
{
/// \todo Validation if interface of corresponding texture object exists
m_image = static_cast<VkImage>(m_Description.m_pExisitingNativeObject);
if (!m_Description.m_ResourceAccess.IsImmutable() || m_Description.m_ResourceAccess.m_bReadBack)
{
ezResult res = CreateStagingBuffer(pVulkanDevice);
if (res == EZ_FAILURE)
{
m_image = nullptr;
return res;
}
}
return EZ_SUCCESS;
}
vk::ImageCreateInfo createInfo = {};
createInfo.flags |= vk::ImageCreateFlagBits::eMutableFormat;
createInfo.format = pVulkanDevice->GetFormatLookupTable().GetFormatInfo(m_Description.m_Format).m_eStorage;
createInfo.initialLayout = vk::ImageLayout::eGeneral; // TODO optimize;
createInfo.pQueueFamilyIndices = pVulkanDevice->GetQueueFamilyIndices().GetPtr();
createInfo.queueFamilyIndexCount = pVulkanDevice->GetQueueFamilyIndices().GetCount();
createInfo.sharingMode = vk::SharingMode::eExclusive;
createInfo.tiling = vk::ImageTiling::eOptimal; // TODO CPU readback might require linear tiling
createInfo.usage |= vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst; // TODO immutable resources
// TODO are these correctly populated or do they contain meaningless values depending on
// the texture type indicated?
createInfo.extent.width = m_Description.m_uiWidth;
createInfo.extent.height = m_Description.m_uiHeight;
createInfo.extent.depth = m_Description.m_uiDepth;
createInfo.mipLevels = m_Description.m_uiMipLevelCount;
createInfo.samples = static_cast<vk::SampleCountFlagBits>(m_Description.m_SampleCount.GetValue());
if (m_Description.m_bAllowShaderResourceView)
createInfo.usage |= vk::ImageUsageFlagBits::eSampled;
if (m_Description.m_bAllowUAV)
createInfo.usage |= vk::ImageUsageFlagBits::eStorage;
if (createInfo.format == vk::Format::eUndefined)
{
ezLog::Error("No storage format available for given format: {0}", m_Description.m_Format);
return EZ_FAILURE;
}
if (m_Description.m_bCreateRenderTarget)
createInfo.usage |= ezGALResourceFormat::IsDepthFormat(m_Description.m_Format) ? vk::ImageUsageFlagBits::eDepthStencilAttachment : vk::ImageUsageFlagBits::eColorAttachment;
switch (m_Description.m_Type)
{
case ezGALTextureType::Texture2D:
case ezGALTextureType::TextureCube:
{
createInfo.arrayLayers = (m_Description.m_Type == ezGALTextureType::Texture2D ? m_Description.m_uiArraySize : (m_Description.m_uiArraySize * 6));
createInfo.imageType = vk::ImageType::e2D; // TODO I think Cube maps require the 3D type
//Tex2DDesc.CPUAccessFlags = 0; // We always use staging textures to update the data
//Tex2DDesc.Usage = m_Description.m_ResourceAccess.IsImmutable() ? D3D11_USAGE_IMMUTABLE : D3D11_USAGE_DEFAULT; // TODO Vulkan
// TODO Vulkan?
//if (m_Description.m_bAllowDynamicMipGeneration)
// Tex2DDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
if (m_Description.m_Type == ezGALTextureType::TextureCube)
createInfo.flags |= vk::ImageCreateFlagBits::eCubeCompatible;
// TODO initial data in Vulkan?
/*
ezHybridArray<D3D11_SUBRESOURCE_DATA, 16> InitialData;
if (!pInitialData.IsEmpty())
{
const ezUInt32 uiInitialDataCount =
(m_Description.m_uiMipLevelCount * (m_Description.m_Type == ezGALTextureType::Texture2D ? 1 : 6));
EZ_ASSERT_DEV(pInitialData.GetCount() == uiInitialDataCount,
"The array of initial data values is not equal to the amount of mip levels!");
InitialData.SetCountUninitialized(uiInitialDataCount);
for (ezUInt32 i = 0; i < uiInitialDataCount; i++)
{
InitialData[i].pSysMem = pInitialData[i].m_pData;
InitialData[i].SysMemPitch = pInitialData[i].m_uiRowPitch;
InitialData[i].SysMemSlicePitch = pInitialData[i].m_uiSlicePitch;
}
}*/
m_image = pVulkanDevice->GetVulkanDevice().createImage(createInfo);
if (!m_image)
{
return EZ_FAILURE;
}
}
break;
case ezGALTextureType::Texture3D:
{
createInfo.imageType = vk::ImageType::e3D;
// TODO Vulkan
//Tex3DDesc.CPUAccessFlags = 0; // We always use staging textures to update the data
//Tex3DDesc.Usage = m_Description.m_ResourceAccess.IsImmutable() ? D3D11_USAGE_IMMUTABLE : D3D11_USAGE_DEFAULT;
// TODO vulkan
//if (m_Description.m_bAllowDynamicMipGeneration)
// Tex3DDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
// TODO ????
//if (m_Description.m_Type == ezGALTextureType::TextureCube)
// Tex3DDesc.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE;
// TODO initialData
//ezHybridArray<D3D11_SUBRESOURCE_DATA, 16> InitialData;
//if (!pInitialData.IsEmpty())
//{
// const ezUInt32 uiInitialDataCount = m_Description.m_uiMipLevelCount;
// EZ_ASSERT_DEV(pInitialData.GetCount() == uiInitialDataCount,
// "The array of initial data values is not equal to the amount of mip levels!");
//
// InitialData.SetCountUninitialized(uiInitialDataCount);
//
// for (ezUInt32 i = 0; i < uiInitialDataCount; i++)
// {
// InitialData[i].pSysMem = pInitialData[i].m_pData;
// InitialData[i].SysMemPitch = pInitialData[i].m_uiRowPitch;
// InitialData[i].SysMemSlicePitch = pInitialData[i].m_uiSlicePitch;
// }
//}
}
break;
default:
EZ_ASSERT_NOT_IMPLEMENTED;
return EZ_FAILURE;
}
vk::MemoryPropertyFlags imageMemoryProperties = vk::MemoryPropertyFlagBits::eDeviceLocal;
vk::MemoryRequirements imageMemoryRequirements = pVulkanDevice->GetVulkanDevice().getImageMemoryRequirements(m_image);
vk::MemoryAllocateInfo memoryAllocateInfo = {};
memoryAllocateInfo.allocationSize = imageMemoryRequirements.size;
memoryAllocateInfo.memoryTypeIndex = pVulkanDevice->GetMemoryIndex(imageMemoryProperties, imageMemoryRequirements);
EZ_ASSERT_DEV(memoryAllocateInfo.memoryTypeIndex != -1, "No valid memory index found for image to allocate from!");
m_memory = pVulkanDevice->GetVulkanDevice().allocateMemory(memoryAllocateInfo); // TODO suballocations
if (!m_memory)
{
pVulkanDevice->GetVulkanDevice().destroyImage(m_image);
m_image = nullptr;
return EZ_FAILURE;
}
m_memorySize = imageMemoryRequirements.size; // TODO save the allocation size of the packed image data size here? (allocation size will almost always be larger)
m_memoryOffset = 0;
if (!m_Description.m_ResourceAccess.IsImmutable() || m_Description.m_ResourceAccess.m_bReadBack)
return CreateStagingBuffer(pVulkanDevice);
m_device = pVulkanDevice->GetVulkanDevice(); // TODO replace by something better
return EZ_SUCCESS;
}
ezResult ezGALTextureVulkan::DeInitPlatform(ezGALDevice* pDevice)
{
if (m_image && !m_pExisitingNativeObject)
{
ezGALDeviceVulkan* pVulkanDevice = static_cast<ezGALDeviceVulkan*>(pDevice);
pVulkanDevice->GetVulkanDevice().destroyImage(m_image);
pVulkanDevice->GetVulkanDevice().freeMemory(m_memory);
m_image = nullptr;
m_memory = nullptr;
m_memoryOffset = 0;
m_memorySize = 0;
}
if (m_pStagingBuffer)
{
m_pStagingBuffer = nullptr;
pDevice->DestroyBuffer(m_stagingBufferHandle);
}
return EZ_SUCCESS;
}
ezResult ezGALTextureVulkan::ReplaceExisitingNativeObject(void* pExisitingNativeObject)
{
EZ_ASSERT_DEV(m_pExisitingNativeObject != nullptr,
"Only textures created with an existing native object are allowed to call ReplaceExisitingNativeObject.");
EZ_ASSERT_DEV(pExisitingNativeObject != nullptr,
"New existing native object must exist.");
m_pExisitingNativeObject = pExisitingNativeObject;
return EZ_SUCCESS;
}
void ezGALTextureVulkan::SetDebugNamePlatform(const char* szName) const
{
ezUInt32 uiLength = ezStringUtils::GetStringElementCount(szName);
if (m_image)
{
vk::DebugMarkerObjectNameInfoEXT nameInfo = {};
nameInfo.object = (uint64_t)(VkImage)m_image;
nameInfo.objectType = vk::DebugReportObjectTypeEXT::eImage;
nameInfo.pObjectName = szName;
m_device.debugMarkerSetObjectNameEXT(nameInfo);
}
}
ezResult ezGALTextureVulkan::CreateStagingBuffer(ezGALDeviceVulkan* pDevice)
{
ezGALBufferCreationDescription bufferDescription;
bufferDescription.m_BufferType = ezGALBufferType::Generic;
bufferDescription.m_uiStructSize = 1;
bufferDescription.m_uiTotalSize = static_cast<ezUInt32>(m_memorySize);
m_stagingBufferHandle = pDevice->CreateBuffer(bufferDescription);
const ezGALBuffer* pStagingBuffer = pDevice->GetBuffer(m_stagingBufferHandle);
EZ_ASSERT_DEV(pStagingBuffer, "Expected valid buffer handle here!");
m_pStagingBuffer = static_cast<const ezGALBufferVulkan*>(pStagingBuffer);
return EZ_SUCCESS;
}
EZ_STATICLINK_FILE(RendererVulkan, RendererVulkan_Resources_Implementation_TextureVulkan);
| 38.376471 | 176 | 0.739935 | [
"object",
"3d"
] |
ffc481083c68f5ac36d0bca252d7adf011c79547 | 3,983 | cpp | C++ | software/tools/compiler/class.cpp | mfkiwl/ztachip | 21cc9f058e8b0eba59d0f2930d33cfde2bb4962d | [
"MIT"
] | 39 | 2020-11-04T01:40:30.000Z | 2022-01-28T10:01:52.000Z | software/tools/compiler/class.cpp | mfkiwl/ztachip | 21cc9f058e8b0eba59d0f2930d33cfde2bb4962d | [
"MIT"
] | null | null | null | software/tools/compiler/class.cpp | mfkiwl/ztachip | 21cc9f058e8b0eba59d0f2930d33cfde2bb4962d | [
"MIT"
] | 3 | 2020-12-27T00:29:45.000Z | 2021-01-21T16:47:24.000Z | //----------------------------------------------------------------------------
// Copyright [2014] [Ztachip Technologies 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.
//------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
#include <string.h>
#include <assert.h>
#include <stdarg.h>
#include <vector>
#include "zta.h"
#include "ast.h"
#include "class.h"
std::vector<cClass *> cClass::M_list;
cClass::cClass(char *_name,int _maxThreads)
{
m_name=_name;
m_maxThreads=_maxThreads;
}
cClass::~cClass()
{
}
int cClass::scan(cAstNode *_root)
{
cAstNode *node,*node2;
char *className;
int nthreads=16;
if(_root->getID()==eTOKEN_block_item_list)
{
node=(cAstNode *)_root->getChildList();
while(node)
{
cClass::scan(node);
node=(cAstNode *)node->getNext();
}
return 0;
}
node=(cAstNode *)_root->getChildList();
while(node)
{
if(node->getID()==eTOKEN_class_declaration)
{
node2=node->getChildList();
if(!node2)
error(node->m_lineNo,"Invalid class declaration");
switch(node2->getID())
{
case eTOKEN_NT1:
nthreads=1;
break;
case eTOKEN_NT2:
nthreads=2;
break;
case eTOKEN_NT4:
nthreads=4;
break;
case eTOKEN_NT8:
nthreads=8;
break;
case eTOKEN_NT16:
nthreads=16;
break;
default:
error(node->m_lineNo,"Invalid class declaration");
break;
}
// Got a class declaration
node2=(cAstNode *)node2->getNext();
if(!node2)
error(node->m_lineNo,"Invalid class declaration");
if(node2->getID()==eTOKEN_class_declaration_list)
{
node2=node2->getChildList();
while(node2)
{
if(node2->getID()==eTOKEN_IDENTIFIER)
{
// Class defined
className=CAST(cAstStringNode,node2)->getStringValue();
if(Find(className))
error(node->m_lineNo,"Class is already defined");
M_list.push_back(new cClass(className,nthreads));
}
else
error(node->m_lineNo,"Invalid class declaration");
node2=(cAstNode *)node2->getNext();
}
}
else if(node2->getID()==eTOKEN_IDENTIFIER)
{
// Class defined
className=CAST(cAstStringNode,node2)->getStringValue();
if(Find(className))
error(node->m_lineNo,"Class is already defined");
M_list.push_back(new cClass(className,nthreads));
}
else
error(node->m_lineNo,"Invalid class declaration");
}
node=(cAstNode *)node->getNext();
}
return 0;
}
cClass *cClass::Find(char *className)
{
int i;
char *p;
char temp[MAX_STRING_LEN];
if(strstr(className,"::"))
{
strcpy(temp,className);
p=strstr(temp,"::");
*p=0;
className=temp;
}
for(i=0;i < (int)M_list.size();i++)
{
if(strcmp(M_list[i]->m_name.c_str(),className)==0)
return M_list[i];
}
return 0;
}
| 27.659722 | 85 | 0.530254 | [
"vector"
] |
ffd6102d1b2e3c5bc36a06e4d90c47240a248af3 | 13,929 | cpp | C++ | src/service/tcp/server.cpp | sptrakesh/config-db | 583ef3a3b636b2d56283194ff2b183bac2a36f21 | [
"Apache-2.0"
] | null | null | null | src/service/tcp/server.cpp | sptrakesh/config-db | 583ef3a3b636b2d56283194ff2b183bac2a36f21 | [
"Apache-2.0"
] | null | null | null | src/service/tcp/server.cpp | sptrakesh/config-db | 583ef3a3b636b2d56283194ff2b183bac2a36f21 | [
"Apache-2.0"
] | null | null | null | //
// Created by Rakesh on 25/12/2021.
//
#include "server.h"
#include "signal/signal.h"
#include "../common/contextholder.h"
#include "../common/model/configuration.h"
#include "../common/model/request_generated.h"
#include "../common/model/response_generated.h"
#include "../lib/db/storage.h"
#include "../log/NanoLog.h"
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/redirect_error.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/use_awaitable.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/ip/tcp.hpp>
using SecureSocket = boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
namespace spt::configdb::tcp::coroutine
{
template <typename Socket>
boost::asio::awaitable<void> write( Socket& socket, const flatbuffers::FlatBufferBuilder& fb )
{
auto size = fb.GetSize();
std::vector<boost::asio::const_buffer> buffers;
buffers.reserve( 2 );
buffers.emplace_back( &size, sizeof(size) );
buffers.emplace_back( fb.GetBufferPointer(), size );
boost::system::error_code ec;
co_await boost::asio::async_write( socket, buffers,
boost::asio::redirect_error( boost::asio::use_awaitable, ec ) );
if ( ec ) LOG_WARN << "Error writing to socket. " << ec.message();
else LOG_DEBUG << "Finished writing buffer of size " << int(size) << " + " << int(sizeof(size)) << " bytes";
}
template <typename Socket>
boost::asio::awaitable<void> get( Socket& socket, const model::Request* request )
{
std::vector<std::string_view> keys;
for ( auto&& kv : *request->data() ) keys.emplace_back( kv->key()->string_view() );
auto value = db::get( keys );
auto fb = flatbuffers::FlatBufferBuilder{};
auto vec = std::vector<flatbuffers::Offset<model::KeyValueResult>>{};
if ( !value.empty() )
{
vec.reserve( value.size() );
for ( auto&& [k, v] : value )
{
if ( v )
{
auto vt = model::CreateValue( fb, fb.CreateString( *v ) );
vec.push_back( model::CreateKeyValueResult(
fb, fb.CreateString( k ), model::ValueVariant::Value, vt.Union() ) );
}
else
{
auto vt = model::CreateSuccess( fb, false );
vec.push_back( model::CreateKeyValueResult(
fb, fb.CreateString( k ), model::ValueVariant::Success, vt.Union() ) );
}
}
}
auto rv = model::CreateKeyValueResults( fb, fb.CreateVector( vec ) );
auto r = model::CreateResponse( fb, model::ResultVariant::KeyValueResults, rv.Union() );
fb.Finish( r );
co_await write( socket, fb );
}
template <typename Socket>
boost::asio::awaitable<void> list( Socket& socket, const model::Request* request )
{
std::vector<std::string_view> keys;
for ( auto&& kv : *request->data() ) keys.emplace_back( kv->key()->string_view() );
auto value = db::list( keys );
auto fb = flatbuffers::FlatBufferBuilder{};
auto vec = std::vector<flatbuffers::Offset<model::KeyValueResult>>{};
if ( !value.empty() )
{
vec.reserve( value.size() );
for ( auto&& [k, v] : value )
{
if ( v )
{
auto vt = model::CreateChildren( fb, fb.CreateVectorOfStrings( *v ) );
vec.push_back( model::CreateKeyValueResult(
fb, fb.CreateString( k ), model::ValueVariant::Children, vt.Union() ) );
}
else
{
auto vt = model::CreateSuccess( fb, false );
vec.push_back( model::CreateKeyValueResult(
fb, fb.CreateString( k ), model::ValueVariant::Success, vt.Union() ) );
}
}
}
auto rv = model::CreateKeyValueResults( fb, fb.CreateVector( vec ) );
auto r = model::CreateResponse( fb, model::ResultVariant::KeyValueResults, rv.Union() );
fb.Finish( r );
co_await write( socket, fb );
}
template <typename Socket>
boost::asio::awaitable<void> put( Socket& socket, const model::Request* request, const std::vector<uint8_t>& rbuf )
{
std::vector<model::RequestData> pairs;
for ( auto&& kv : *request->data() )
{
auto opts = model::RequestData::Options{
kv->options()->expiration_in_seconds(), kv->options()->if_not_exists() };
pairs.emplace_back( kv->key()->string_view(), kv->value()->string_view(), opts );
}
auto value = db::set( pairs );
auto fb = flatbuffers::FlatBufferBuilder{};
auto vt = model::CreateSuccess( fb, value );
auto r = model::CreateResponse( fb, model::ResultVariant::Success, vt.Union() );
fb.Finish( r );
if ( value && !model::Configuration::instance().peers.empty() )
{
LOG_DEBUG << "Notifying peers of set for " << int( pairs.size() ) << " keys";
signal::SignalMgr::instance().emit( std::make_shared<signal::SignalMgr::Bytes>( rbuf ) );
}
co_await write( socket, fb );
}
template <typename Socket>
boost::asio::awaitable<void> remove( Socket& socket, const model::Request* request, const std::vector<uint8_t>& rbuf )
{
std::vector<std::string_view> keys;
for ( auto&& kv : *request->data() ) keys.emplace_back( kv->key()->string_view() );
auto value = db::remove( keys );
auto fb = flatbuffers::FlatBufferBuilder{};
auto vt = model::CreateSuccess( fb, value );
auto r = model::CreateResponse( fb, model::ResultVariant::Success, vt.Union() );
fb.Finish( r );
if ( value && !model::Configuration::instance().peers.empty() )
{
LOG_DEBUG << "Notifying peers of remove for " << int( keys.size() ) << " keys";
signal::SignalMgr::instance().emit( std::make_shared<signal::SignalMgr::Bytes>( rbuf ) );
}
co_await write( socket, fb );
}
template <typename Socket>
boost::asio::awaitable<void> move( Socket& socket, const model::Request* request, const std::vector<uint8_t>& rbuf )
{
std::vector<model::RequestData> pairs;
for ( auto&& kv : *request->data() )
{
auto opts = model::RequestData::Options{
kv->options()->expiration_in_seconds(), kv->options()->if_not_exists() };
pairs.emplace_back( kv->key()->string_view(), kv->value()->string_view(), opts );
}
auto value = db::move( pairs );
auto fb = flatbuffers::FlatBufferBuilder{};
auto vt = model::CreateSuccess( fb, value );
auto r = model::CreateResponse( fb, model::ResultVariant::Success, vt.Union() );
fb.Finish( r );
if ( value && !model::Configuration::instance().peers.empty() )
{
LOG_DEBUG << "Notifying peers of move for " << int( pairs.size() ) << " keys";
signal::SignalMgr::instance().emit( std::make_shared<signal::SignalMgr::Bytes>( rbuf ) );
}
co_await write( socket, fb );
}
template <typename Socket>
boost::asio::awaitable<void> ttl( Socket& socket, const model::Request* request )
{
std::vector<std::string_view> keys;
for ( auto&& kv : *request->data() ) keys.emplace_back( kv->key()->string_view() );
auto value = db::ttl( keys );
auto fb = flatbuffers::FlatBufferBuilder{};
auto vec = std::vector<flatbuffers::Offset<model::KeyValueResult>>{};
if ( !value.empty() )
{
vec.reserve( value.size() );
for ( auto&& [k, v] : value )
{
auto vt = model::CreateValue( fb, fb.CreateString( std::to_string( v.count() ) ) );
vec.push_back( model::CreateKeyValueResult(
fb, fb.CreateString( k ), model::ValueVariant::Value, vt.Union() ) );
}
}
auto rv = model::CreateKeyValueResults( fb, fb.CreateVector( vec ) );
auto r = model::CreateResponse( fb, model::ResultVariant::KeyValueResults, rv.Union() );
fb.Finish( r );
co_await write( socket, fb );
}
template <typename Socket>
boost::asio::awaitable<void> process( Socket& socket, const model::Request* request, const std::vector<uint8_t>& rbuf )
{
switch ( request->action() )
{
case model::Action::Get:
co_await get( socket, request );
break;
case model::Action::List:
co_await list( socket, request );
break;
case model::Action::Put:
co_await put( socket, request, rbuf );
break;
case model::Action::Delete:
co_await remove( socket, request, rbuf );
break;
case model::Action::Move:
co_await move( socket, request, rbuf );
break;
case model::Action::TTL:
co_await ttl( socket, request );
break;
}
}
template <typename Socket>
boost::asio::awaitable<void> respond( Socket& socket )
{
using namespace std::string_view_literals;
static constexpr int bufSize = 128;
static constexpr auto maxBytes = 8 * 1024 * 1024;
uint8_t data[bufSize];
const auto documentSize = [&data]( std::size_t length )
{
if ( length < 5 ) return length;
const auto d = const_cast<uint8_t*>( data );
uint32_t len;
memcpy( &len, d, sizeof(len) );
return std::size_t( len + sizeof(len) );
};
const auto brokenPipe = []( const boost::system::error_code& ec )
{
static const std::string msg{ "Broken pipe" };
return boost::algorithm::starts_with( ec.message(), msg );
};
boost::system::error_code ec;
std::size_t osize = co_await socket.async_read_some( boost::asio::buffer( data ), boost::asio::use_awaitable );
const auto docSize = documentSize( osize );
// echo, noop, ping etc.
if ( docSize < 5 )
{
co_await boost::asio::async_write( socket, boost::asio::buffer( data, docSize ),
boost::asio::redirect_error( boost::asio::use_awaitable, ec ) );
if ( ec && !brokenPipe( ec ) )
{
LOG_WARN << "Error writing to socket. " << ec.message();
}
co_return;
}
std::vector<uint8_t> rbuf;
rbuf.reserve( docSize - sizeof(uint32_t) );
rbuf.insert( rbuf.end(), data + sizeof(uint32_t), data + osize );
if ( docSize <= bufSize )
{
auto request = model::GetRequest( data + sizeof(uint32_t) );
co_await process( socket, request, rbuf );
co_return;
}
auto read = osize;
LOG_DEBUG << "Read " << int(osize) << " bytes, total size " << int(docSize);
while ( docSize < maxBytes && read != docSize )
{
osize = co_await socket.async_read_some( boost::asio::buffer( data ), boost::asio::use_awaitable );
rbuf.insert( rbuf.end(), data, data + osize );
read += osize;
}
auto verifier = flatbuffers::Verifier( rbuf.data(), rbuf.size() );
auto ok = model::VerifyRequestBuffer( verifier );
if ( !ok )
{
LOG_WARN << "Invalid request buffer";
co_await boost::asio::async_write( socket, boost::asio::buffer( rbuf.data(), rbuf.size() ),
boost::asio::redirect_error( boost::asio::use_awaitable, ec ) );
if ( ec && !brokenPipe( ec ) ) LOG_WARN << "Error writing to socket. " << ec.message();
co_return;
}
auto request = model::GetRequest( rbuf.data() );
co_await process( socket, request, rbuf );
}
boost::asio::ssl::context createSSLContext()
{
auto& conf = model::Configuration::instance();
auto ctx = boost::asio::ssl::context( boost::asio::ssl::context::tlsv13_server );
ctx.set_options(
boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::single_dh_use );
ctx.load_verify_file( conf.ssl.caCertificate );
ctx.use_certificate_file( conf.ssl.certificate, boost::asio::ssl::context::pem );
ctx.use_private_key_file( conf.ssl.key, boost::asio::ssl::context::pem );
ctx.set_verify_mode( boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert );
return ctx;
}
boost::asio::awaitable<void> serveWithSSL( boost::asio::ip::tcp::socket s )
{
try
{
auto ctx = createSSLContext();
auto socket = SecureSocket{ std::move( s ), ctx };
boost::system::error_code ec;
co_await socket.async_handshake( boost::asio::ssl::stream_base::server,
boost::asio::redirect_error( boost::asio::use_awaitable, ec ) );
if ( ec )
{
LOG_WARN << "Handshake error. " << ec.message();
socket.next_layer().close( ec );
if ( ec ) LOG_WARN << "Error closing socket. " << ec.message();
co_return;
}
for (;;)
{
co_await respond( socket );
}
}
catch ( const std::exception& e )
{
static const auto eof{ "stream truncated" };
if ( !boost::algorithm::starts_with( e.what(), eof ) ) LOG_WARN << "Exception servicing request " << e.what();
}
}
boost::asio::awaitable<void> serve( boost::asio::ip::tcp::socket socket )
{
try
{
for (;;)
{
co_await respond( socket );
}
}
catch ( const std::exception& e )
{
static const auto eof{ "End of file" };
if ( !boost::algorithm::starts_with( e.what(), eof ) ) LOG_WARN << "Exception servicing request " << e.what();
}
}
boost::asio::awaitable<void> listener( int port, bool ssl )
{
auto executor = co_await boost::asio::this_coro::executor;
boost::asio::ip::tcp::acceptor acceptor( executor,
{ boost::asio::ip::tcp::v4(), static_cast<boost::asio::ip::port_type>( port ) } );
for (;;)
{
if ( ContextHolder::instance().ioc.stopped() ) break;
boost::asio::ip::tcp::socket socket = co_await acceptor.async_accept( boost::asio::use_awaitable );
if ( ssl )
{
boost::asio::co_spawn( executor, serveWithSSL( std::move(socket) ), boost::asio::detached );
}
else
{
boost::asio::co_spawn( executor, serve( std::move(socket) ), boost::asio::detached );
}
}
}
}
int spt::configdb::tcp::start( int port, bool ssl )
{
boost::asio::co_spawn( ContextHolder::instance().ioc, coroutine::listener( port, ssl ), boost::asio::detached );
LOG_INFO << "TCP service started on port " << port;
return 0;
}
| 33.973171 | 121 | 0.612822 | [
"vector",
"model"
] |
ffd774d893142baffbb7de7c2a0eb295f98459bd | 11,675 | cpp | C++ | src/mlpack/tests/to_string_test.cpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/tests/to_string_test.cpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/tests/to_string_test.cpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file to_string_test.cpp
* @author Ryan Birmingham
*
* Test of the toString functionality.
**/
#include <mlpack/core.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#include <mlpack/core/metrics/ip_metric.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <mlpack/core/metrics/mahalanobis_distance.hpp>
#include <mlpack/core/kernels/pspectrum_string_kernel.hpp>
#include <mlpack/core/kernels/example_kernel.hpp>
#include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp>
#include <mlpack/core/optimizers/lbfgs/lbfgs.hpp>
#include <mlpack/core/optimizers/sdp/lrsdp.hpp>
#include <mlpack/core/optimizers/sgd/sgd.hpp>
#include <mlpack/methods/nca/nca_softmax_error_function.hpp>
#include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_test_functions.hpp>
#include <mlpack/core/tree/ballbound.hpp>
#include <mlpack/core/tree/binary_space_tree.hpp>
#include <mlpack/core/tree/bounds.hpp>
#include <mlpack/core/tree/hrectbound.hpp>
#include <mlpack/core/tree/statistic.hpp>
#include <mlpack/methods/cf/cf.hpp>
#include <mlpack/methods/det/dtree.hpp>
#include <mlpack/methods/emst/dtb.hpp>
#include <mlpack/methods/fastmks/fastmks.hpp>
#include <mlpack/methods/gmm/gmm.hpp>
#include <mlpack/methods/hmm/hmm.hpp>
#include <mlpack/methods/kernel_pca/kernel_pca.hpp>
#include <mlpack/methods/kmeans/kmeans.hpp>
#include <mlpack/methods/lars/lars.hpp>
#include <mlpack/methods/linear_regression/linear_regression.hpp>
#include <mlpack/methods/local_coordinate_coding/lcc.hpp>
#include <mlpack/methods/logistic_regression/logistic_regression.hpp>
#include <mlpack/methods/lsh/lsh_search.hpp>
#include <mlpack/methods/neighbor_search/neighbor_search.hpp>
#include <mlpack/methods/amf/amf.hpp>
#include <mlpack/methods/nca/nca.hpp>
#include <mlpack/methods/pca/pca.hpp>
#include <mlpack/methods/radical/radical.hpp>
#include <mlpack/methods/range_search/range_search.hpp>
#include <mlpack/methods/rann/ra_search.hpp>
#include <mlpack/methods/sparse_coding/sparse_coding.hpp>
using namespace mlpack;
using namespace mlpack::kernel;
using namespace mlpack::distribution;
using namespace mlpack::metric;
using namespace mlpack::nca;
using namespace mlpack::bound;
using namespace mlpack::tree;
using namespace mlpack::neighbor;
//using namespace mlpack::optimization;
BOOST_AUTO_TEST_SUITE(ToStringTest);
std::ostringstream testOstream;
BOOST_AUTO_TEST_CASE(DiscreteDistributionString)
{
DiscreteDistribution d("0.4 0.5 0.1");
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(GaussianDistributionString)
{
GaussianDistribution d("0.1 0.3", "1.0 0.1; 0.1 1.0");
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(CosineDistanceString)
{
CosineDistance d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(EpanechnikovKernelString)
{
EpanechnikovKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(ExampleKernelString)
{
ExampleKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(GaussianKernelString)
{
GaussianKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(HyperbolicTangentKernelString)
{
HyperbolicTangentKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LaplacianKernelString)
{
LaplacianKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LinearKernelString)
{
LinearKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(PolynomialKernelString)
{
PolynomialKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(PSpectrumStringKernelString)
{
const std::vector<std::vector<std::string> > s;
const size_t t = 1;
PSpectrumStringKernel d(s, t);
Log::Debug << d;
testOstream << d;
std::string sttm = d.ToString();
BOOST_REQUIRE_NE(sttm, "");
}
BOOST_AUTO_TEST_CASE(SphericalKernelString)
{
SphericalKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(TriangularKernelString)
{
TriangularKernel d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(IPMetricString)
{
IPMetric<TriangularKernel> d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LMetricString)
{
LMetric<1> d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(MahalanobisDistanceString)
{
MahalanobisDistance<> d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(SGDString)
{
const arma::mat g(2, 2);
const arma::Col<size_t> v(2);
SoftmaxErrorFunction<> a(g, v);
mlpack::optimization::SGD<SoftmaxErrorFunction<> > d(a);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(L_BFGSString)
{
const arma::mat g(2, 2);
const arma::Col<size_t> v(2);
SoftmaxErrorFunction<> a(g, v);
mlpack::optimization::L_BFGS<SoftmaxErrorFunction<> > d(a);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(AugLagString)
{
mlpack::optimization::AugLagrangianTestFunction a;
mlpack::optimization::AugLagrangian<
mlpack::optimization::AugLagrangianTestFunction> d(a);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LRSDPString)
{
arma::mat c(40, 40);
c.randn();
const size_t b=3;
mlpack::optimization::LRSDP<mlpack::optimization::SDP<arma::sp_mat>> d(b,b,c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(BallBoundString)
{
BallBound<> d(3.5, "1.0 2.0");
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(BinSpaceString)
{
arma::mat q(2, 50);
q.randu();
KDTree<ManhattanDistance, EmptyStatistic, arma::mat> d(q);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(CoverTreeString)
{
arma::mat q(2, 50);
q.randu();
StandardCoverTree<EuclideanDistance, EmptyStatistic, arma::mat> d(q);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(CFString)
{
arma::mat c(3, 3);
c(0, 0) = 1;
c(1, 0) = 2;
c(2, 0) = 1.5;
c(0, 1) = 2;
c(1, 1) = 3;
c(2, 1) = 2.0;
c(0, 2) = 1;
c(1, 2) = 3;
c(2, 2) = 0.7;
mlpack::cf::CF<> d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(DetString)
{
arma::mat c(4, 4);
c.randn();
mlpack::det::DTree d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(EmstString)
{
arma::mat c(4, 4);
c.randu();
mlpack::emst::DualTreeBoruvka<> d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(FastMKSString)
{
arma::mat c(4, 4);
c.randn();
mlpack::fastmks::FastMKS<LinearKernel> d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(GMMString)
{
arma::mat c(400, 40);
c.randn();
mlpack::gmm::GMM<> d(5, 4);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(HMMString)
{
mlpack::hmm::HMM<> d(5, 4);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(KPCAString)
{
LinearKernel k;
mlpack::kpca::KernelPCA<LinearKernel> d(k, false);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(KMeansString)
{
mlpack::kmeans::KMeans<metric::ManhattanDistance> d(100);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LarsString)
{
mlpack::regression::LARS d(false);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LinRegString)
{
arma::mat c(40, 40);
arma::mat b(40, 1);
c.randn();
b.randn();
mlpack::regression::LinearRegression d(c, b);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LCCString)
{
arma::mat c(40,40);
const size_t b=3;
const double a=1;
c.randn();
mlpack::lcc::LocalCoordinateCoding<> d(c, b, a);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LogRegString)
{
arma::mat c(40, 40);
arma::Row<size_t> b(40);
c.randn();
b.randu();
mlpack::regression::LogisticRegression<> d(c, b);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(LSHString)
{
arma::mat c(40, 40);
const size_t b=3;
c.randn();
mlpack::neighbor::LSHSearch<NearestNeighborSort> d(c, b, b);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(NeighborString)
{
arma::mat c(40, 40);
c.randn();
mlpack::neighbor::NeighborSearch<> d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
/*
BOOST_AUTO_TEST_CASE(NMFString)
{
arma::mat c(40, 40);
c.randn();
mlpack::amf::AMF<> d;
Log::Debug << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
*/
BOOST_AUTO_TEST_CASE(NCAString)
{
arma::mat c(40, 40);
arma::Col<size_t> b(3);
c.randn();
mlpack::nca::NCA<> d(c, b);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(PCAString)
{
mlpack::pca::PCA d(true);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(RadicalString)
{
mlpack::radical::Radical d;
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(RangeSearchString)
{
arma::mat c(40, 40);
c.randn();
mlpack::range::RangeSearch<> d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(RannString)
{
arma::mat c(40, 40);
c.randn();
mlpack::neighbor::RASearch<> d(c);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_CASE(SparseCodingString)
{
arma::mat c(40, 40);
c.randn();
const size_t b=3;
double a=0.1;
mlpack::sparse_coding::SparseCoding<> d(c,b,a);
Log::Debug << d;
testOstream << d;
std::string s = d.ToString();
BOOST_REQUIRE_NE(s, "");
}
BOOST_AUTO_TEST_SUITE_END();
| 21.863296 | 82 | 0.677002 | [
"vector"
] |
ffda34de5c203efa0a2fb74f76c3783e608b8cb8 | 4,067 | cpp | C++ | deps/libgeos/geos/src/noding/snapround/HotPixelIndex.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 42 | 2021-03-26T17:34:52.000Z | 2022-03-18T14:15:31.000Z | deps/libgeos/geos/src/noding/snapround/HotPixelIndex.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 29 | 2021-06-03T14:24:01.000Z | 2022-03-23T15:43:58.000Z | deps/libgeos/geos/src/noding/snapround/HotPixelIndex.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 8 | 2021-05-14T19:26:37.000Z | 2022-03-21T13:44:42.000Z | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2020 Paul Ramsey <pramsey@cleverelephant.ca>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
*********************************************************************/
#include <geos/noding/snapround/HotPixelIndex.h>
#include <geos/index/kdtree/KdTree.h>
#include <geos/index/ItemVisitor.h>
#include <geos/geom/CoordinateSequence.h>
#include <random>
#include <algorithm> // for std::min and std::max
#include <cassert>
#include <memory>
using namespace geos::algorithm;
using namespace geos::geom;
using geos::index::kdtree::KdTree;
using geos::index::ItemVisitor;
namespace geos {
namespace noding { // geos.noding
namespace snapround { // geos.noding.snapround
/*public*/
HotPixelIndex::HotPixelIndex(const PrecisionModel* p_pm)
:
pm(p_pm),
scaleFactor(p_pm->getScale()),
index(new KdTree())
{
}
/*public*/
HotPixel*
HotPixelIndex::add(const Coordinate& p)
{
Coordinate pRound = round(p);
HotPixel* hp = find(pRound);
/**
* Hot Pixels which are added more than once
* must have more than one vertex in them
* and thus must be nodes.
*/
if (hp != nullptr) {
hp->setToNode();
return hp;
}
/**
* A pixel containing the point was not found, so create a new one.
* It is initially set to NOT be a node
* (but may become one later on).
*/
// Store the HotPixel in a std::deque to avoid individually
// allocating a pile of HotPixels on the heap and to
// get them freed automatically as the std::deque
// goes away when this HotPixelIndex is deleted.
hotPixelQue.emplace_back(pRound, scaleFactor);
// Pick up a pointer to the most recently added
// HotPixel.
hp = &(hotPixelQue.back());
index->insert(hp->getCoordinate(), (void*)hp);
return hp;
}
/*public*/
void
HotPixelIndex::add(const CoordinateSequence *pts)
{
/*
* Add the points to the tree in random order
* to avoid getting an unbalanced tree from
* spatially autocorrelated coordinates
*/
std::vector<std::size_t> idxs;
for (std::size_t i = 0, sz = pts->size(); i < sz; i++)
idxs.push_back(i);
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(idxs.begin(), idxs.end(), g);
for (auto i : idxs) {
add(pts->getAt(i));
}
}
/*public*/
void
HotPixelIndex::add(const std::vector<geom::Coordinate>& pts)
{
std::vector<std::size_t> idxs;
for (std::size_t i = 0, sz = pts.size(); i < sz; i++)
idxs.push_back(i);
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(idxs.begin(), idxs.end(), g);
for (auto i : idxs) {
add(pts[i]);
}
}
/*public*/
void
HotPixelIndex::addNodes(const CoordinateSequence *pts)
{
for (std::size_t i = 0, sz = pts->size(); i < sz; i++) {
HotPixel* hp = add(pts->getAt(i));
hp->setToNode();
}
}
/*public*/
void
HotPixelIndex::addNodes(const std::vector<geom::Coordinate>& pts)
{
for (auto pt: pts) {
HotPixel* hp = add(pt);
hp->setToNode();
}
}
/*private*/
HotPixel*
HotPixelIndex::find(const geom::Coordinate& pixelPt)
{
index::kdtree::KdNode *kdNode = index->query(pixelPt);
if (kdNode == nullptr) {
return nullptr;
}
return (HotPixel*)(kdNode->getData());
}
/*private*/
Coordinate
HotPixelIndex::round(const Coordinate& pt)
{
Coordinate p2 = pt;
pm->makePrecise(p2);
return p2;
}
/*public*/
void
HotPixelIndex::query(const Coordinate& p0, const Coordinate& p1, index::kdtree::KdNodeVisitor& visitor)
{
Envelope queryEnv(p0, p1);
queryEnv.expandBy(1.0 / scaleFactor);
index->query(queryEnv, visitor);
}
} // namespace geos.noding.snapround
} // namespace geos.noding
} // namespace geos
| 23.107955 | 103 | 0.61913 | [
"geometry",
"vector"
] |
ffdab31aba890b833e5d397d1ea9940c1cedd976 | 11,761 | cpp | C++ | project_code/of_v0.11.0_osx_release/apps/myApps/laserBomb/src/ofApp.cpp | Vamoss/devart-template | 3c276f5967c24365c04dd00ed36933cc19b6f8bb | [
"Apache-2.0"
] | null | null | null | project_code/of_v0.11.0_osx_release/apps/myApps/laserBomb/src/ofApp.cpp | Vamoss/devart-template | 3c276f5967c24365c04dd00ed36933cc19b6f8bb | [
"Apache-2.0"
] | null | null | null | project_code/of_v0.11.0_osx_release/apps/myApps/laserBomb/src/ofApp.cpp | Vamoss/devart-template | 3c276f5967c24365c04dd00ed36933cc19b6f8bb | [
"Apache-2.0"
] | null | null | null | #include "ofApp.h"
extern "C" {
#include "macGlutfix.h"
}
//--------------------------------------------------------------
void ofApp::setup(){
config::setup();
//UI
ofEnableAlphaBlending();
ofBackground(78);
logoX = 0;
logo.load("gui/images/logo.png");
fboPosition.y = 60;
m_menu = new menu();
m_menu->setup(&ildaFbo, &ildaFrame);
ofAddListener(m_menu->panelMode->onChange, this, &ofApp::onModeChange);
m_sidebar = new sidebar();
m_sidebar->setup(&ildaFbo, &ildaFrame);
string initalMode = "DRAW";
onModeChange(initalMode);
etherdream.setup();
etherdream.setPPS(20000);
ildaFbo.setup(512, 512);
doFboClear = true;
captureWidth = ofGetScreenWidth();
captureHeight = ofGetScreenHeight();
tex.allocate(captureWidth, captureHeight, GL_RGBA);
ildaFbo.params.draw.fbo = true;
ildaFbo.params.draw.fboAlpha = 255;
ildaFrame.params.output.transform.doFlipX = true;
ildaFrame.params.output.transform.doFlipY = true;
//webServer
server.start("httpdocs", config::receiverPort);
server.addHandler(this, "actions*");
layoutResize();
layoutResize();
brushThickness = 10;//50
}
//--------------------------------------------------------------
void ofApp::update(){
if(mode==DRAW){
brushThickness = m_sidebar->panelDraw->brushThicknessSlider->getScaledValue();
doDrawErase = m_sidebar->panelDraw->eraserToggle->getValue();
doFboClear = m_sidebar->panelDraw->clearButton->getValue();
}else if(mode==CAPTURE && (m_sidebar->panelCapture->buttonCapture->getValue() || m_sidebar->panelCapture->toggleAutoCapture->getValue())){
m_sidebar->panelCapture->m_cropper->update();
unsigned char * data;
ofRectangle tempRect;
if(m_sidebar->panelCapture->buttonCrop->getValue()){
tempRect.x = 0;
tempRect.y = 0;
tempRect.width = captureWidth;
tempRect.height = captureHeight;
}else{
tempRect.x = m_sidebar->panelCapture->m_cropper->x;
tempRect.y = m_sidebar->panelCapture->m_cropper->y;
tempRect.width = m_sidebar->panelCapture->m_cropper->width;
tempRect.height = m_sidebar->panelCapture->m_cropper->height;
}
data = pixelsBelowWindow(tempRect.x, tempRect.y, tempRect.width, tempRect.height);
/* if using macbook retina, set to true */
bool retina = true;
int pixelSize = retina ? 2 : 1;
// now, let's get the R and B data swapped, so that it's all OK:
for (int i = 0; i < pixelSize * pixelSize * tempRect.width * tempRect.height; i++){
unsigned char r1 = data[i*4]; // mem A
data[i*4] = data[i*4+1];
data[i*4+1] = data[i*4+2];
data[i*4+2] = data[i*4+3];
data[i*4+3] = r1;
}
if (data!= NULL) tex.loadData(data, tempRect.width*pixelSize, tempRect.height*pixelSize, GL_RGBA);
}else if(mode == RECEIVE){
processReceivedData();
}
m_menu->update();
m_sidebar->update();
}
//--------------------------------------------------------------
void ofApp::drawInFbo() {
ofPushStyle();
ildaFbo.begin();
if(doFboClear) {
doFboClear = false;
ofClear(0);
}
if(mode==DRAW && ofGetMousePressed() && mouseDownPos.x >= 0) {
ofPushMatrix();
ofScale(ildaFbo.getWidth(), ildaFbo.getHeight(), 1);
ofSetColor(doDrawErase ? 0 : 255);
ofSetLineWidth(brushThickness);
ofDrawLine(lastMouseDownPos, mouseDownPos);
ofDrawEllipse(mouseDownPos, brushThickness/2.0f/ildaFbo.getWidth(), brushThickness/2.0f/ildaFbo.getHeight());
ofPopMatrix();
}else if(mode==CAPTURE){
ofRectangle sourceRect;
if(m_sidebar->panelCapture->buttonCrop->getValue()){
sourceRect.x = 0;
sourceRect.y = 0;
sourceRect.width = captureWidth;
sourceRect.height = captureHeight;
}else{
sourceRect.x = m_sidebar->panelCapture->m_cropper->x;
sourceRect.y = m_sidebar->panelCapture->m_cropper->y;
sourceRect.width = m_sidebar->panelCapture->m_cropper->width;
sourceRect.height = m_sidebar->panelCapture->m_cropper->height;
}
captureDrawPosition.width=ildaFbo.getWidth();
captureDrawPosition.height=sourceRect.height*(ildaFbo.getWidth()/sourceRect.width);
if(captureDrawPosition.height>ildaFbo.getHeight()){
captureDrawPosition.height=ildaFbo.getHeight();
captureDrawPosition.width=sourceRect.width*ildaFbo.getHeight()/sourceRect.height;
}
captureDrawPosition.x = (ildaFbo.getWidth()-captureDrawPosition.width)/2;
captureDrawPosition.y = (ildaFbo.getHeight()-captureDrawPosition.height)/2;
m_sidebar->panelCapture->m_cropper->scale = (fboPosition.width/captureWidth)*(captureDrawPosition.width/ildaFbo.getWidth());
tex.draw(captureDrawPosition.x, captureDrawPosition.y, captureDrawPosition.width, captureDrawPosition.height);
}
ildaFbo.end();
ofPopStyle();
}
//--------------------------------------------------------------
void ofApp::draw() {
ofSetColor(255);
logo.draw(logoX,10);
// clear the current frame
ildaFrame.clear();
if(mode==DRAW || mode==CAPTURE){
drawInFbo(); // draw stuff into the ildaRenderTarget
ildaFbo.update(ildaFrame); // vectorize and update the ildaFrame
}else if(mode==RECEIVE){
ildaFrame.addPolys(receivedData);
}
ildaFrame.update();
etherdream.setPoints(ildaFrame);
ofPushMatrix();
ofTranslate(fboPosition.x, fboPosition.y);
ildaFbo.getGreyImage().draw(0, 0, fboPosition.width, fboPosition.height);
ofSetColor(0, 255, 0);
ildaFrame.draw(0, 0, fboPosition.width, fboPosition.height);
if(mode==CAPTURE){
if(m_sidebar->panelCapture->buttonCrop->getValue()){
ofPushMatrix();
cout << fboPosition.y << " " << captureDrawPosition.y << " " << fboPosition.height << " " << m_sidebar->panelCapture->m_cropper->scale << " " << fboScale << endl;
ofTranslate(captureDrawPosition.x*fboScale, captureDrawPosition.y*fboScale);
m_sidebar->panelCapture->m_cropper->draw();
ofPopMatrix();
}
}
ofPopMatrix();
if(mode==DRAW){
// draw cursor
ofPushStyle();
ofFill();
ofSetColor(doDrawErase ? 0 : 255, 128);
float r = brushThickness/2 * ofGetWidth() /2 / ildaFbo.getWidth();
ofDrawCircle(ofGetMouseX(), ofGetMouseY(), r);
ofNoFill();
ofSetColor(255, 128);
ofDrawCircle(ofGetMouseX(), ofGetMouseY(), r);
ofPopStyle();
}
m_menu->draw();
m_sidebar->draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key) {
case 'f': ofToggleFullscreen(); break;
case 'c': doFboClear ^= true; break;
case '-': if(brushThickness>1) brushThickness--; break;
case 't': printf("mouse inside: %i\n", ildaFrame.getPoly(0).inside(mouseDownPos.x, mouseDownPos.y)); break; // test
}
m_sidebar->panelCapture->m_cropper->keyPressed(key);
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
if(m_menu->isHit(x, y)) return;
if(mode==DRAW){
lastMouseDownPos = mouseDownPos;
mouseDownPos.x = ofMap(x, fboPosition.x, fboPosition.x+fboPosition.width, 0, 1);
mouseDownPos.y = ofMap(y, fboPosition.y, fboPosition.y+fboPosition.height, 0, 1);
}else if(mode==CAPTURE){
m_sidebar->panelCapture->m_cropper->mouseDragged(x-fboPosition.x-(captureDrawPosition.x*fboScale), y-fboPosition.y-(captureDrawPosition.y*fboScale), button);
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
if(m_menu->isHit(x, y)) return;
if(mode==DRAW){
mouseDownPos.x = ofMap(x, fboPosition.x, fboPosition.x+fboPosition.width, 0, 1);
mouseDownPos.y = ofMap(y, fboPosition.y, fboPosition.y+fboPosition.height, 0, 1);
lastMouseDownPos = mouseDownPos;
}else if(mode==CAPTURE){
m_sidebar->panelCapture->m_cropper->mousePressed(x-fboPosition.x-(captureDrawPosition.x*fboScale), y-fboPosition.y-(captureDrawPosition.y*fboScale), button);
}
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
layoutResize();
}
//--------------------------------------------------------------
void ofApp::layoutResize(){
int w = ofGetWidth();
int h = ofGetHeight();
fboPosition.height = h-60;
fboPosition.width = fboPosition.height;
fboScale = fboPosition.width/ildaFbo.getWidth();
int subPanelWidth = ofMap(ofGetWidth(), 800, 1920, 200, 400);
int finalWidth = 60 + fboPosition.width + subPanelWidth;
if(finalWidth>w){
fboPosition.width = w - 60 - subPanelWidth;
fboPosition.height = fboPosition.width;
finalWidth = 60 + fboPosition.width + subPanelWidth;
}
logoX = (w-finalWidth)/2;
m_menu->setX(logoX);
m_sidebar->setX(fboPosition.x+fboPosition.width);
fboPosition.x = logoX+60;
}
//--------------------------------------------------------------
void ofApp::onModeChange(string & name)
{
if(name=="DRAW"){
mode = DRAW;
}else if(name=="SCREEN CAPTURE"){
mode = CAPTURE;
}else if(name=="HTTP RECEIVER"){
mode = RECEIVE;
}
m_sidebar->panelDraw->gui1->setVisible(mode==DRAW);
m_sidebar->panelCapture->gui1->setVisible(mode==CAPTURE);
m_sidebar->panelReceive->gui1->setVisible(mode==RECEIVE);
}
//webServer
void ofApp::httpGet(string url) {
string colorString = getRequestParameter("color");
cout << colorString << endl;
httpResponse("Color value: " + colorString);
}
void ofApp::httpPost(string url, char *data, int dataLength) {
//cout << "url: " << url << endl;
//cout << "data: " << data << endl;
//cout << "dataLength: " << dataLength << endl;
dataReceived = string(data);
httpResponse("OK");
}
void ofApp::processReceivedData(){
if(dataReceived!=""){
try {
//protocol
//r,g,b,x,y,x,y,x,y,x,y_r,g,b,x,y,x,y,x,y_r,g,b,x,y,x,y,x,y
vector< string > groupValues = ofSplitString(dataReceived,"_");
receivedData.clear();
for(int j=0;j<groupValues.size();j++){
vector< string > values = ofSplitString(groupValues[j],",");
if(values.size()<5) continue;
ofxIlda::Poly poly = ofxIlda::Poly(ofColor(ofToInt(values[0]),ofToInt(values[1]),ofToInt(values[2])));
for(int i=3;i+1<values.size();i+=2){
float x=atof(values[i].c_str());
float y=atof(values[i+1].c_str());
poly.lineTo(x, y);
}
receivedData.push_back(poly);
}
m_sidebar->panelReceive->incomingDataCounter++;
m_sidebar->panelReceive->incomingDataCounterLabel->setLabel("Received: " + ofToString(m_sidebar->panelReceive->incomingDataCounter));
}
catch(...) {
cout << "error parsing received data" << endl;
}
dataReceived = "";
}
}
| 34.188953 | 178 | 0.572995 | [
"vector",
"transform"
] |
ffde8187ae563cd896ec1e15ce97b11767435a0d | 895 | cpp | C++ | Practicum/Homework3/Source files/MagicCard.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Practicum/Homework3/Source files/MagicCard.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Practicum/Homework3/Source files/MagicCard.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | /**
* Solution to homework assignment 3
* Object Oriented Programming Course
* Faculty of Mathematics and Informatics of Sofia University
* Summer semester 2020/2021
*
* @author Stefania Tsvetkova
* @idnumber 62573
* @task 1
* @compiler VC
*/
#include "MagicCard.hpp"
MagicCard::MagicCard()
{
this->type = this->DEFAULT_TYPE;
}
MagicCard::MagicCard(std::string name, std::string effect, Type type)
: Card(name, effect)
{
this->type = type;
}
Type MagicCard::GetType() const
{
return this->type;
}
std::string MagicCard::GetTypeAsString() const
{
switch (this->type)
{
case Type::buff:
return "buff";
case Type::spell:
return "spell";
case Type::trap:
return "trap";
case Type::unknown:
return "unknown";
}
}
std::ostream& operator<<(std::ostream& stream, MagicCard& card)
{
stream << card.name << '|' << card.effect << '|' << card.GetTypeAsString();
return stream;
}
| 17.211538 | 76 | 0.686034 | [
"object"
] |
ffe2588df6a5a961e68e837f387e13f9d11fc69f | 6,858 | cpp | C++ | csapex_core_plugins/src/tools/create_map_message_adapter.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_core_plugins/src/tools/create_map_message_adapter.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_core_plugins/src/tools/create_map_message_adapter.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z |
/// HEADER
#include "create_map_message_adapter.h"
/// PROJECT
#include <csapex/model/node_facade_impl.h>
#include <csapex_core_plugins/parameter_dialog.h>
/// PROJECT
#include <csapex/command/add_connection.h>
#include <csapex/command/command_factory.h>
#include <csapex/command/meta.h>
#include <csapex/model/graph_facade.h>
#include <csapex/model/node_handle.h>
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/param/range_parameter.h>
#include <csapex/utility/uuid_provider.h>
#include <csapex/view/designer/graph_view.h>
#include <csapex/view/node/box.h>
#include <csapex/view/utility/register_node_adapter.h>
/// SYSTEM
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QProgressBar>
#include <QPushButton>
#include <iostream>
using namespace csapex;
CSAPEX_REGISTER_LOCAL_NODE_ADAPTER(CreateMapMessageAdapter, csapex::CreateMapMessage)
CreateMapMessageAdapter::CreateMapMessageAdapter(NodeFacadeImplementationPtr worker, NodeBox* parent, std::weak_ptr<CreateMapMessage> node) : DefaultNodeAdapter(worker, parent), wrapped_base_(node)
{
QObject::connect(&widget_picker_, SIGNAL(widgetPicked()), this, SLOT(widgetPicked()));
auto n = wrapped_base_.lock();
}
CreateMapMessageAdapter::~CreateMapMessageAdapter()
{
}
void CreateMapMessageAdapter::setupUi(QBoxLayout* layout)
{
DefaultNodeAdapter::setupUi(layout);
QPushButton* btn_add_param = new QPushButton("Create Parameter");
layout->addWidget(btn_add_param);
QObject::connect(btn_add_param, SIGNAL(clicked()), this, SLOT(createParameter()));
QPushButton* btn_pick_param = new QPushButton("Pick Parameter");
layout->addWidget(btn_pick_param);
QObject::connect(btn_pick_param, SIGNAL(clicked()), this, SLOT(pickParameter()));
QPushButton* btn_remove_param = new QPushButton("Remove Parameters");
layout->addWidget(btn_remove_param);
QObject::connect(btn_remove_param, SIGNAL(clicked()), this, SLOT(removeParameters()));
}
void CreateMapMessageAdapter::parameterAdded(param::ParameterPtr param)
{
}
void CreateMapMessageAdapter::widgetPicked()
{
auto node = wrapped_base_.lock();
if (!node) {
return;
}
QWidget* widget = widget_picker_.getWidget();
if (widget) {
if (widget != nullptr) {
std::cerr << "picked widget " << widget->metaObject()->className() << std::endl;
}
QVariant var = widget->property("parameter");
if (!var.isNull()) {
csapex::param::Parameter* connected_parameter = static_cast<csapex::param::Parameter*>(var.value<void*>());
if (connected_parameter != nullptr) {
node->ainfo << "picked parameter " << connected_parameter->name() << " with UUID " << connected_parameter->getUUID() << std::endl;
std::string label = connected_parameter->name();
Input* i = node->createVariadicInput(makeEmpty<connection_types::AnyMessage>(), label, false);
UUID input = i->getUUID();
UUID output = UUIDProvider::makeDerivedUUID_forced(connected_parameter->getUUID().parentUUID(), std::string("out_") + connected_parameter->name());
if (!connected_parameter->isInteractive()) {
connected_parameter->setInteractive(true);
}
GraphFacade* facade = parent_->getGraphView()->getGraphFacade();
if (!facade->isConnected(input, output)) {
AUUID parent_uuid = facade->getAbsoluteUUID();
executeCommand(std::make_shared<command::AddConnection>(parent_uuid, output, input, false));
} else {
node->getNodeHandle()->setError("the selected parameter is already connected.");
}
} else {
node->getNodeHandle()->setWarning("No Parameter selected.");
}
} else {
node->getNodeHandle()->setWarning("The widget has no parameter property.");
}
} else {
node->getNodeHandle()->setWarning("No widget selected.");
}
}
QDialog* CreateMapMessageAdapter::makeTypeDialog()
{
QVBoxLayout* layout = new QVBoxLayout;
QFormLayout* form = new QFormLayout;
QComboBox* type = new QComboBox;
type->addItem("int");
type->addItem("double");
form->addRow("Type", type);
QObject::connect(type, SIGNAL(currentIndexChanged(QString)), this, SLOT(setNextParameterType(QString)));
next_type_ = type->currentText().toStdString();
layout->addLayout(form);
QDialogButtonBox* buttons = new QDialogButtonBox;
buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
layout->addWidget(buttons);
QDialog* dialog = new QDialog;
dialog->setWindowTitle("Create Parameter");
dialog->setLayout(layout);
dialog->setModal(true);
QObject::connect(buttons, SIGNAL(accepted()), dialog, SLOT(accept()));
QObject::connect(buttons, SIGNAL(rejected()), dialog, SLOT(reject()));
return dialog;
}
void CreateMapMessageAdapter::setNextParameterType(const QString& type)
{
next_type_ = type.toStdString();
}
void CreateMapMessageAdapter::pickParameter()
{
auto designer = parent_->getGraphView()->designerScene();
if (designer) {
widget_picker_.startPicking(designer);
}
}
void CreateMapMessageAdapter::createParameter()
{
std::cerr << "parmeters currently unused" << std::endl;
auto node = wrapped_base_.lock();
if (!node) {
return;
}
QDialog* type_dialog = makeTypeDialog();
if (type_dialog->exec() == QDialog::Accepted) {
ParameterDialog diag(next_type_);
if (diag.exec() == QDialog::Accepted) {
csapex::param::Parameter::Ptr param = diag.getParameter();
node->addPersistentParameter(param);
parameterAdded(param);
node->reset();
}
}
}
void CreateMapMessageAdapter::removeParameters()
{
auto node = wrapped_base_.lock();
if (!node) {
return;
}
GraphFacade* facade = parent_->getGraphView()->getGraphFacade();
command::Meta::Ptr cmd(new command::Meta(facade->getAbsoluteUUID(), "remove parameter", true));
NodeHandle* nh = node->getNodeHandle();
CommandFactory factory(facade);
for (param::ParameterPtr p : node->getPersistentParameters()) {
if (OutputPtr out = nh->getParameterOutput(p->name()).lock()) {
cmd->add(factory.removeAllConnectionsCmd(out));
}
if (InputPtr in = nh->getParameterInput(p->name()).lock()) {
cmd->add(factory.removeAllConnectionsCmd(in));
}
}
executeCommand(cmd);
node->removePersistentParameters();
}
/// MOC
#include "moc_create_map_message_adapter.cpp"
| 32.046729 | 197 | 0.669583 | [
"model"
] |
ffe587618cc1cc2633af48d003addf7f5e6f6508 | 1,733 | cpp | C++ | solved/0-b/bi-shoe-and-phi-shoe/bishoe.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/0-b/bi-shoe-and-phi-shoe/bishoe.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/0-b/bi-shoe-and-phi-shoe/bishoe.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
typedef long long i64;
typedef unsigned int u32;
typedef vector<int> IV;
typedef IV::const_iterator IVci;
#define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); v++)
// I/O
#define BUF 65536
struct Reader {
char buf[BUF]; char b; int bi, bz;
Reader() { bi=bz=0; read(); }
void read() {
if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); }
b = bz ? buf[bi++] : 0; }
void skip() { while (b > 0 && b <= 32) read(); }
u32 next_u32() {
u32 v = 0; for (skip(); b > 32; read()) v = v*10 + b-48; return v; }
};
// Number Theory
#define IsComp(n) (_c[n>>6]&(1<<((n>>1)&31)))
#define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31))
namespace Num
{
const int MAX = 1000003; // includes one prime over 10^6
const int LMT = 1001; // sqrt(MAX)
int _c[(MAX>>6)+1];
IV primes;
void primeSieve() {
for (int i = 3; i <= LMT; i += 2)
if (!IsComp(i)) for (int j = i*i; j <= MAX; j+=i+i) SetComp(j);
primes.push_back(2);
for (int i=3; i <= MAX; i+=2) if (!IsComp(i)) primes.push_back(i);
}
}
using namespace Num;
int main()
{
primeSieve();
Reader rr;
int T = rr.next_u32();
int ncase = 1;
while (T--) {
int n = rr.next_u32();
IV ns;
while (n--) {
int x = rr.next_u32();
ns.push_back(x);
}
sort(ns.begin(), ns.end());
i64 xukha = 0;
IVci p = primes.begin();
cFor (IV, num, ns) {
while (*num >= *p) p++;
xukha += *p;
}
printf("Case %d: %lld Xukha\n", ncase++, xukha);
}
return 0;
}
| 22.506494 | 76 | 0.493364 | [
"vector"
] |
ffe615c69a058c545560f55761a7330204602b10 | 16,898 | hpp | C++ | applications/SolidMechanicsApplication/custom_conditions/boundary_condition.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/SolidMechanicsApplication/custom_conditions/boundary_condition.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/SolidMechanicsApplication/custom_conditions/boundary_condition.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | //
// Project Name: KratosSolidMechanicsApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: August 2017 $
// Revision: $Revision: 0.0 $
//
//
#if !defined(KRATOS_BOUNDARY_CONDITION_H_INCLUDED)
#define KRATOS_BOUNDARY_CONDITION_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/checks.h"
#include "includes/condition.h"
#include "custom_utilities/solid_mechanics_math_utilities.hpp"
#include "utilities/beam_math_utilities.hpp"
#include "custom_utilities/element_utilities.hpp"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// General Boundary Condition base type for 3D and 2D geometries.
/**
* Implements a General definitions for a boundary neumann or mixed condition.
* This works for arbitrary geometries in 3D and 2D (base class)
*/
class KRATOS_API(SOLID_MECHANICS_APPLICATION) BoundaryCondition
: public Condition
{
public:
///@name Type Definitions
///@{
typedef Variable<array_1d<double,3>> VariableVectorType;
typedef Variable<double> VariableScalarType;
///Type for size
typedef GeometryData::SizeType SizeType;
// Counted pointer of BoundaryCondition
KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION( BoundaryCondition );
///@}
protected:
/**
* Flags related to the element computation
*/
KRATOS_DEFINE_LOCAL_FLAG( COMPUTE_RHS_VECTOR );
KRATOS_DEFINE_LOCAL_FLAG( COMPUTE_LHS_MATRIX );
/**
* Parameters to be used in the Condition as they are.
*/
struct ConditionVariables
{
private:
//variables including all integration points
const GeometryType::ShapeFunctionsGradientsType* pDN_De;
const Matrix* pNcontainer;
public:
//for axisymmetric use only
double CurrentRadius;
double ReferenceRadius;
//general variables
double GeometrySize;
double Jacobian;
Vector N;
Matrix DN_De;
Matrix DeltaPosition;
//external boundary values
double ExternalScalarValue;
Vector ExternalVectorValue;
//boundary characteristics
Vector Normal;
Vector Tangent1;
Vector Tangent2;
//variables including all integration points
GeometryType::JacobiansType j;
GeometryType::JacobiansType J;
/**
* sets the value of a specified pointer variable
*/
void SetShapeFunctionsGradients(const GeometryType::ShapeFunctionsGradientsType &rDN_De)
{
pDN_De=&rDN_De;
};
void SetShapeFunctions(const Matrix& rNcontainer)
{
pNcontainer=&rNcontainer;
};
/**
* returns the value of a specified pointer variable
*/
const GeometryType::ShapeFunctionsGradientsType& GetShapeFunctionsGradients()
{
return *pDN_De;
};
const Matrix& GetShapeFunctions()
{
return *pNcontainer;
};
void Initialize( const unsigned int& dimension,
const unsigned int& local_dimension,
const unsigned int& number_of_nodes )
{
//doubles
//radius
CurrentRadius = 0;
ReferenceRadius = 0;
//jacobians
GeometrySize = 1;
Jacobian = 1;
//external boundary values
ExternalScalarValue = 0;
ExternalVectorValue.resize(dimension,false);
noalias(ExternalVectorValue) = ZeroVector(dimension);
//vectors
N.resize(number_of_nodes,false);
Normal.resize(dimension,false);
Tangent1.resize(dimension,false);
Tangent2.resize(dimension,false);
noalias(N) = ZeroVector(number_of_nodes);
noalias(Normal) = ZeroVector(dimension);
noalias(Tangent1) = ZeroVector(dimension);
noalias(Tangent2) = ZeroVector(dimension);
//matrices
DN_De.resize(number_of_nodes, local_dimension,false);
noalias(DN_De) = ZeroMatrix(number_of_nodes, local_dimension);
DeltaPosition.resize(number_of_nodes, dimension,false);
noalias(DeltaPosition) = ZeroMatrix(number_of_nodes, dimension);
//others
J.resize(1,false);
j.resize(1,false);
J[0].resize(dimension,dimension,false);
j[0].resize(dimension,dimension,false);
noalias(J[0]) = ZeroMatrix(dimension,dimension);
noalias(j[0]) = ZeroMatrix(dimension,dimension);
//pointers
pDN_De = NULL;
pNcontainer = NULL;
}
};
/**
* This struct is used in the component wise calculation only
* is defined here and is used to declare a member variable in the component wise condition
* private pointers can only be accessed by means of set and get functions
* this allows to set and not copy the local system variables
*/
struct LocalSystemComponents
{
private:
//for calculation local system with compacted LHS and RHS
MatrixType *mpLeftHandSideMatrix;
VectorType *mpRightHandSideVector;
public:
//calculation flags
Flags CalculationFlags;
/**
* sets the value of a specified pointer variable
*/
void SetLeftHandSideMatrix( MatrixType& rLeftHandSideMatrix ) { mpLeftHandSideMatrix = &rLeftHandSideMatrix; };
void SetRightHandSideVector( VectorType& rRightHandSideVector ) { mpRightHandSideVector = &rRightHandSideVector; };
/**
* returns the value of a specified pointer variable
*/
MatrixType& GetLeftHandSideMatrix() { return *mpLeftHandSideMatrix; };
VectorType& GetRightHandSideVector() { return *mpRightHandSideVector; };
};
public:
///@name Life Cycle
///@{
/// Empty constructor needed for serialization
BoundaryCondition();
/// Default constructor.
BoundaryCondition( IndexType NewId, GeometryType::Pointer pGeometry );
BoundaryCondition( IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties );
/// Copy constructor
BoundaryCondition( BoundaryCondition const& rOther);
/// Destructor
~BoundaryCondition() override;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* creates a new condition pointer
* @param NewId: the ID of the new condition
* @param ThisNodes: the nodes of the new condition
* @param pProperties: the properties assigned to the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Create(IndexType NewId,
NodesArrayType const& ThisNodes,
PropertiesType::Pointer pProperties ) const override;
/**
* clones the selected condition variables, creating a new one
* @param NewId: the ID of the new condition
* @param ThisNodes: the nodes of the new condition
* @param pProperties: the properties assigned to the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Clone(IndexType NewId,
NodesArrayType const& ThisNodes) const override;
//************* STARTING - ENDING METHODS
/**
* Called at the beginning of each solution step
*/
void Initialize(const ProcessInfo& rCurrentProcessInfo) override;
/**
* Called at the beginning of each solution step
*/
void InitializeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override;
/**
* Called at the beginning of each iteration
*/
void InitializeNonLinearIteration(const ProcessInfo& rCurrentProcessInfo) override;
//************* GETTING METHODS
/**
* Sets on rConditionDofList the degrees of freedom of the considered element geometry
*/
void GetDofList(DofsVectorType& rConditionDofList,
const ProcessInfo& rCurrentProcessInfo ) const override;
/**
* Sets on rResult the ID's of the element degrees of freedom
*/
void EquationIdVector(EquationIdVectorType& rResult,
const ProcessInfo& rCurrentProcessInfo ) const override;
/**
* Sets on rValues the nodal displacements
*/
void GetValuesVector(Vector& rValues,
int Step = 0 ) const override;
/**
* Sets on rValues the nodal velocities
*/
void GetFirstDerivativesVector(Vector& rValues,
int Step = 0 ) const override;
/**
* Sets on rValues the nodal accelerations
*/
void GetSecondDerivativesVector(Vector& rValues,
int Step = 0 ) const override;
//************* COMPUTING METHODS
/**
* this is called during the assembling process in order
* to calculate all condition contributions to the global system
* matrix and the right hand side
* @param rLeftHandSideMatrix: the condition left hand side matrix
* @param rRightHandSideVector: the condition right hand side
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateLocalSystem(MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this is called during the assembling process in order
* to calculate the condition right hand side vector only
* @param rRightHandSideVector: the condition right hand side vector
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateRightHandSide(VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this is called during the assembling process in order
* to calculate the condition left hand side matrix only
* @param rLeftHandSideMatrix: the condition left hand side matrix
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateLeftHandSide(MatrixType& rLeftHandSideMatrix,
const ProcessInfo& rCurrentProcessInfo) override;
/**
* this is called during the assembling process in order
* to calculate the condition mass matrix
* @param rMassMatrix: the condition mass matrix
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateMassMatrix(MatrixType& rMassMatrix,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this is called during the assembling process in order
* to calculate the condition damping matrix
* @param rDampingMatrix: the condition damping matrix
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateDampingMatrix(MatrixType& rDampingMatrix,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this function is designed to make the element to assemble an rRHS vector
* identified by a variable rRHSVariable by assembling it to the nodes on the variable
* rDestinationVariable.
* @param rRHSVector: input variable containing the RHS vector to be assembled
* @param rRHSVariable: variable describing the type of the RHS vector to be assembled
* @param rDestinationVariable: variable in the database to which the rRHSvector will be assembled
* @param rCurrentProcessInfo: the current process info instance
*/
void AddExplicitContribution(const VectorType& rRHS,
const Variable<VectorType>& rRHSVariable,
const Variable<array_1d<double,3> >& rDestinationVariable,
const ProcessInfo& rCurrentProcessInfo) override;
/**
* Calculate a double Variable
*/
void CalculateOnIntegrationPoints(const Variable<double>& rVariable,
std::vector<double>& rOutput,
const ProcessInfo& rCurrentProcessInfo) override;
//************************************************************************************
//************************************************************************************
/**
* This function provides the place to perform checks on the completeness of the input.
* It is designed to be called only once (or anyway, not often) typically at the beginning
* of the calculations, so to verify that nothing is missing from the input
* or that no common error is found.
* @param rCurrentProcessInfo
*/
int Check( const ProcessInfo& rCurrentProcessInfo ) const override;
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
/**
* Currently selected integration methods
*/
IntegrationMethod mThisIntegrationMethod;
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* Initialize Explicit Contributions
*/
void InitializeExplicitContributions();
/**
* Check dof for a vector variable
*/
virtual bool HasVariableDof(VariableVectorType& rVariable) const;
/**
* Check dof for a double variable
*/
virtual bool HasVariableDof(VariableScalarType& rVariable) const;
/**
* Get condition size from the dofs
*/
virtual unsigned int GetDofsSize() const;
/**
* Initialize System Matrices
*/
virtual void InitializeSystemMatrices(MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
Flags& rCalculationFlags);
/**
* Initialize General Variables
*/
virtual void InitializeConditionVariables(ConditionVariables& rVariables,
const ProcessInfo& rCurrentProcessInfo);
/**
* Calculate Condition Kinematics
*/
virtual void CalculateKinematics(ConditionVariables& rVariables,
const double& rPointNumber);
/**
* Calculates the condition contributions
*/
virtual void CalculateConditionSystem(LocalSystemComponents& rLocalSystem,
const ProcessInfo& rCurrentProcessInfo);
/**
* Calculation and addition of the matrices of the LHS
*/
virtual void CalculateAndAddLHS(LocalSystemComponents& rLocalSystem,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation and addition of the vectors of the RHS
*/
virtual void CalculateAndAddRHS(LocalSystemComponents& rLocalSystem,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation of the Load Stiffness Matrix which usually is subtracted to the global stiffness matrix
*/
virtual void CalculateAndAddKuug(MatrixType& rLeftHandSideMatrix,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation of the External Forces Vector for a force or pressure vector
*/
virtual void CalculateAndAddExternalForces(Vector& rRightHandSideVector,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation of the External Forces Vector for a force or pressure vector
*/
virtual double& CalculateAndAddExternalEnergy(double& rEnergy,
ConditionVariables& rVariables,
double& rIntegrationWeight,
const ProcessInfo& rCurrentProcessInfo);
/**
* Get Node Movements for energy computation
*/
void GetNodalDeltaMovements(Vector& rValues, const int& rNode);
/**
* Get Current Value, buffer 0 with FastGetSolutionStepValue
*/
Vector& GetNodalCurrentValue(const Variable<array_1d<double,3> >&rVariable, Vector& rValue, const unsigned int& rNode);
/**
* Get Previous Value, buffer 1 with FastGetSolutionStepValue
*/
Vector& GetNodalPreviousValue(const Variable<array_1d<double,3> >&rVariable, Vector& rValue, const unsigned int& rNode);
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Serialization
///@{
friend class Serializer;
void save(Serializer& rSerializer) const override;
void load(Serializer& rSerializer) override;
}; // class BoundaryCondition.
} // namespace Kratos.
#endif // KRATOS_BOUNDARY_CONDITION_H_INCLUDED defined
| 27.884488 | 124 | 0.650846 | [
"geometry",
"vector",
"3d"
] |
ffea4e64e3ce050b02007f09aecb2bd110e28e96 | 4,451 | hpp | C++ | include/GlobalNamespace/StaticJumpOffsetYProvider.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/StaticJumpOffsetYProvider.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/StaticJumpOffsetYProvider.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: IJumpOffsetYProvider
#include "GlobalNamespace/IJumpOffsetYProvider.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: StaticJumpOffsetYProvider
class StaticJumpOffsetYProvider;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::StaticJumpOffsetYProvider);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::StaticJumpOffsetYProvider*, "", "StaticJumpOffsetYProvider");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: StaticJumpOffsetYProvider
// [TokenAttribute] Offset: FFFFFFFF
class StaticJumpOffsetYProvider : public ::Il2CppObject/*, public ::GlobalNamespace::IJumpOffsetYProvider*/ {
public:
// Nested type: ::GlobalNamespace::StaticJumpOffsetYProvider::InitData
class InitData;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// [InjectAttribute] Offset: 0x124FED0
// private readonly StaticJumpOffsetYProvider/InitData _initData
// Size: 0x8
// Offset: 0x10
::GlobalNamespace::StaticJumpOffsetYProvider::InitData* initData;
// Field size check
static_assert(sizeof(::GlobalNamespace::StaticJumpOffsetYProvider::InitData*) == 0x8);
public:
// Creating interface conversion operator: operator ::GlobalNamespace::IJumpOffsetYProvider
operator ::GlobalNamespace::IJumpOffsetYProvider() noexcept {
return *reinterpret_cast<::GlobalNamespace::IJumpOffsetYProvider*>(this);
}
// Creating conversion operator: operator ::GlobalNamespace::StaticJumpOffsetYProvider::InitData*
constexpr operator ::GlobalNamespace::StaticJumpOffsetYProvider::InitData*() const noexcept {
return initData;
}
// Get instance field reference: private readonly StaticJumpOffsetYProvider/InitData _initData
::GlobalNamespace::StaticJumpOffsetYProvider::InitData*& dyn__initData();
// public System.Single get_jumpOffsetY()
// Offset: 0x1335E20
float get_jumpOffsetY();
// public System.Void .ctor()
// Offset: 0x1335E3C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static StaticJumpOffsetYProvider* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::StaticJumpOffsetYProvider::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<StaticJumpOffsetYProvider*, creationType>()));
}
}; // StaticJumpOffsetYProvider
#pragma pack(pop)
static check_size<sizeof(StaticJumpOffsetYProvider), 16 + sizeof(::GlobalNamespace::StaticJumpOffsetYProvider::InitData*)> __GlobalNamespace_StaticJumpOffsetYProviderSizeCheck;
static_assert(sizeof(StaticJumpOffsetYProvider) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::StaticJumpOffsetYProvider::get_jumpOffsetY
// Il2CppName: get_jumpOffsetY
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::StaticJumpOffsetYProvider::*)()>(&GlobalNamespace::StaticJumpOffsetYProvider::get_jumpOffsetY)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StaticJumpOffsetYProvider*), "get_jumpOffsetY", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StaticJumpOffsetYProvider::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 46.852632 | 190 | 0.757807 | [
"object",
"vector"
] |
ffece58616545a61ed97fd30ba3ee0b57ef42f55 | 559 | cc | C++ | ch03/ex3_44.cc | meishaoming/cpp_primer_5th_answer | 482d60e37e8bf69c0ae83e7e98d955f76dfbffe0 | [
"MIT"
] | null | null | null | ch03/ex3_44.cc | meishaoming/cpp_primer_5th_answer | 482d60e37e8bf69c0ae83e7e98d955f76dfbffe0 | [
"MIT"
] | null | null | null | ch03/ex3_44.cc | meishaoming/cpp_primer_5th_answer | 482d60e37e8bf69c0ae83e7e98d955f76dfbffe0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
using int_array = int[4];
int main() {
int ia[3][4] = {
{ 0, 1, 2, 3, },
{ 4, 5, 6, 7, },
{ 8, 9, 10, 11, },
};
for (int_array &row : ia) {
for (int &col : row) {
cout << col << ' ';
}
cout << endl;
}
cout << "---------" << endl;
for (int_array *p = ia; p != ia + 3; ++p) {
for (int *q = *p; q != *p + 4; ++q) {
cout << *q << ' ';
}
cout << endl;
}
cout << "---------" << endl;
return 0;
}
| 15.971429 | 45 | 0.413238 | [
"vector"
] |
fff204f3b0c5057d1cacbc8a0ffa5c55c991a27d | 19,812 | cpp | C++ | src/xconnection.cpp | uzsolt/herbstluftwm | 49b6dcad50452d79783576236df2ce670672c10a | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/xconnection.cpp | uzsolt/herbstluftwm | 49b6dcad50452d79783576236df2ce670672c10a | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/xconnection.cpp | uzsolt/herbstluftwm | 49b6dcad50452d79783576236df2ce670672c10a | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "xconnection.h"
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/Xutil.h>
#include <climits>
#include <iostream>
#include "globals.h"
using std::endl;
using std::make_pair;
using std::pair;
using std::string;
using std::vector;
bool XConnection::exitOnError_ = false;
void XConnection::setExitOnError(bool exitOnError)
{
exitOnError_ = exitOnError;
}
XConnection::XConnection(Display* disp)
: m_display(disp) {
m_screen = DefaultScreen(m_display);
m_screen_width = DisplayWidth(m_display, m_screen);
m_screen_height = DisplayHeight(m_display, m_screen);
m_root = RootWindow(m_display, m_screen);
utf8StringAtom_ = XInternAtom(m_display, "UTF8_STRING", False);
}
XConnection::~XConnection() {
HSDebug("Closing display\n");
XCloseDisplay(m_display);
}
XConnection* XConnection::connect(string display_name) {
const char* display_str = (display_name != "") ? display_name.c_str() : nullptr;
Display* d = XOpenDisplay(display_str);
if (d == nullptr) {
std::cerr << "herbstluftwm: XOpenDisplay() failed" << endl;
exit(EXIT_FAILURE);
}
return new XConnection(d);
}
static bool g_other_wm_running = false;
// from dwm.c
/* Startup Error handler to check if another window manager
* is already running. */
static int xerrorstart(Display*, XErrorEvent*) {
g_other_wm_running = true;
return -1;
}
static int (*g_xerrorxlib)(Display *, XErrorEvent *);
// from dwm.c
/* There's no way to check accesses to destroyed windows, thus those cases are
* ignored (especially on UnmapNotify's). Other types of errors call Xlibs
* default error handler, which may call exit. */
int XConnection::xerror(Display *dpy, XErrorEvent *ee) {
if(ee->error_code == BadWindow
|| ee->error_code == BadGC
|| ee->error_code == BadPixmap
|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable)) {
return 0;
}
char errorCodeString[100] = "unknown";
XGetErrorText(dpy, ee->error_code, errorCodeString, 100);
const char* requestCodeString = XConnection::requestCodeToString(ee->request_code);
if (!requestCodeString) {
requestCodeString = "unknown";
}
fprintf(stderr, "herbstluftwm: fatal error\n"
" resource id: 0x%lx\n"
" request code: %d \"%s\" (minor code: %d)\n"
" error code: %d \"%s\"\n"
" serial number: %ld\n",
ee->resourceid,
ee->request_code,
requestCodeString,
ee->minor_code,
ee->error_code,
errorCodeString,
ee->serial);
if (ee->error_code == BadDrawable) {
HSDebug("Warning: ignoring X_BadDrawable\n");
return 0;
}
if (exitOnError_) {
return g_xerrorxlib(dpy, ee); // may call exit()
}
// otherwise, just ignore this error and try to proceed.
return 0;
}
// from dwm.c
bool XConnection::checkotherwm() {
g_other_wm_running = False;
g_xerrorxlib = XSetErrorHandler(xerrorstart);
/* this causes an error if some other window manager is running */
XSelectInput(m_display, DefaultRootWindow(m_display), SubstructureRedirectMask);
XSync(m_display, False);
if(g_other_wm_running) {
return true;
} else {
XSetErrorHandler(XConnection::xerror);
XSync(m_display, False);
return false;
}
}
Rectangle XConnection::windowSize(Window window) {
unsigned int border, depth;
int x, y;
unsigned int w, h;
XGetGeometry(m_display, window, &m_root, &x, &y, &w, &h, &border, &depth);
// treat wanted coordinates as floating coords
return { x, y, (int)w, (int)h };
}
Atom XConnection::atom(const char* atom_name) {
return XInternAtom(m_display, atom_name, False);
}
string XConnection::atomName(Atom atomIdentifier) {
char* name = XGetAtomName(m_display, atomIdentifier);
string res = name;
XFree(name);
return res;
}
//! The pid of a window or -1 if the pid is not set
int XConnection::windowPid(Window window) {
// TODO: move to Ewmh
auto res = getWindowPropertyCardinal(window, atom("_NET_WM_PID"));
if (!res.has_value() || res.value().size() == 0) {
return -1;
} else {
return res.value()[0];
}
}
//! wrapper around XGetClassHint returning the window's instance and class name
pair<string, string> XConnection::getClassHint(Window window) {
XClassHint hint;
if (0 == XGetClassHint(m_display, window, &hint)) {
return {"", ""};
}
pair<string,string> result = {
hint.res_name ? hint.res_name : "",
hint.res_class ? hint.res_class : ""
};
if (hint.res_name) XFree(hint.res_name);
if (hint.res_class) XFree(hint.res_class);
return result;
}
//! from https://stackoverflow.com/a/39884120/4400896
static std::string iso_8859_1_to_utf8(const char* source) {
string strOut;
for (int i = 0; source[i] != '\0'; i++) {
uint8_t ch = source[i];
if (ch < 0x80) {
strOut.push_back(ch);
}
else {
strOut.push_back(0xc0 | ch >> 6);
strOut.push_back(0x80 | (ch & 0x3f));
}
}
return strOut;
}
std::experimental::optional<string> XConnection::getWindowProperty(Window window, Atom atom) {
string result;
char** list = nullptr;
int n = 0;
XTextProperty prop;
if (0 == XGetTextProperty(m_display, window, &prop, atom)) {
return std::experimental::optional<string>();
}
// convert text property to a gstring
if (prop.encoding == XA_STRING) {
// a XA_STRING is always encoded in ISO 8859-1
result = iso_8859_1_to_utf8(reinterpret_cast<char *>(prop.value));
} else if (prop.encoding == utf8StringAtom_) {
result = reinterpret_cast<char *>(prop.value);
} else {
if (XmbTextPropertyToTextList(m_display, &prop, &list, &n) >= Success
&& n > 0 && *list)
{
result = *list;
XFreeStringList(list);
}
}
XFree(prop.value);
return result;
}
//! implement XChangeProperty for type=ATOM('UTF8_STRING')
void XConnection::setPropertyString(Window w, Atom property, string value) {
// according to the XChangeProperty-specification:
// if format = 8, then the data must be a char array.
XChangeProperty(m_display, w, property,
utf8StringAtom_, 8, PropModeReplace,
(unsigned char*)value.c_str(), value.size());
}
//! implement XSetTextProperty for an array of utf8-strings
void XConnection::setPropertyString(Window w, Atom property, const vector<string>& value)
{
vector<const char*> value_c_str;
value_c_str.reserve(value.size());
for (const auto& s : value) {
value_c_str.push_back(s.c_str());
}
XTextProperty text_prop;
Xutf8TextListToTextProperty(
m_display, (char**) value_c_str.data(), value_c_str.size(),
XUTF8StringStyle, &text_prop);
XSetTextProperty(m_display, w, &text_prop, property);
XFree(text_prop.value);
}
//! implement XChangeProperty for type=XA_WINDOW
void XConnection::setPropertyWindow(Window w, Atom property, const vector<Window>& value) {
// according to the XChangeProperty-specification:
// if format = 32, then the data must be a long array.
XChangeProperty(m_display, w, property,
XA_WINDOW, 32, PropModeReplace,
(unsigned char*)(value.data()), value.size());
}
//! implement XChangeProperty for type=XA_CARDINAL
void XConnection::setPropertyCardinal(Window w, Atom property, const vector<long>& value) {
// according to the XChangeProperty-specification:
// if format = 32, then the data must be a long array.
XChangeProperty(m_display, w, property,
XA_CARDINAL, 32, PropModeReplace,
(unsigned char*)(value.data()), value.size());
}
std::experimental::optional<Window> XConnection::getTransientForHint(Window win)
{
Window master;
if (XGetTransientForHint(m_display, win, &master) != 0) {
return master;
}
return {};
}
/** a sincere wrapper around XGetWindowProperty():
* get a window property of format 32. If the property does not exist
* or is not of format 32, the return type is None (and the vector is empty).
* otherwise the content of the property together with its type is returned.
*/
template<typename T> pair<Atom,vector<T>>
getWindowProperty32(Display* display, Window window, Atom property)
{
Atom actual_type;
int format;
unsigned long bytes_left;
unsigned long* items_return;
unsigned long count;
int status = XGetWindowProperty(display, window,
property, 0, ULONG_MAX, False, AnyPropertyType,
&actual_type, &format, &count, &bytes_left,
(unsigned char**)&items_return);
if (Success != status || actual_type == None || format == 0) {
return make_pair(None, vector<T>());
}
if (format != 32) {
// if the property could be read, but is of the wrong format
XFree(items_return);
return make_pair(None, vector<T>());
}
vector<T> result;
result.reserve(count);
for (int i = 0; i < count; i++) {
result.push_back(items_return[i]);
}
XFree(items_return);
return make_pair(actual_type, result);
}
std::experimental::optional<vector<long>>
XConnection::getWindowPropertyCardinal(Window window, Atom property)
{
auto res = getWindowProperty32<long>(m_display, window, property);
if (res.first != XA_CARDINAL) {
return {};
}
return res.second;
}
std::experimental::optional<vector<Atom>>
XConnection::getWindowPropertyAtom(Window window, Atom property)
{
auto res = getWindowProperty32<Atom>(m_display, window, property);
if (res.first != XA_ATOM) {
return {};
}
return res.second;
}
std::experimental::optional<vector<Window>>
XConnection::getWindowPropertyWindow(Window window, Atom property)
{
auto res = getWindowProperty32<Window>(m_display, window, property);
if (res.first != XA_WINDOW) {
return {};
}
return res.second;
}
std::experimental::optional<vector<string>>
XConnection::getWindowPropertyTextList(Window window, Atom property)
{
XTextProperty text_prop;
if (!XGetTextProperty(m_display, window, &text_prop, property)) {
return {};
}
char** list_return;
int count;
if (Success != Xutf8TextPropertyToTextList(m_display, &text_prop, &list_return, &count)) {
XFree(text_prop.value);
return {};
}
vector<string> arguments;
for (int i = 0; i < count; i++) {
arguments.push_back(list_return[i]);
}
XFreeStringList(list_return);
XFree(text_prop.value);
return { arguments };
}
//! query all children of the given window via XQueryTree()
vector<Window> XConnection::queryTree(Window window) {
Window root, parent, *children = nullptr;
unsigned int count = 0;
Status status = XQueryTree(m_display, window,
&root, &parent, &children, &count);
if (status == 0) {
return {};
}
vector<Window> result;
result.reserve(count);
for (unsigned int i = 0; i < count; i++) {
result.push_back(children[i]);
}
XFree(children);
return result;
}
#define RequestCodeAndString(C) { C, #C }
const char* XConnection::requestCodeToString(int requestCode)
{
// all request codes from X11/Xproto.h
vector<pair<int, const char*>> requestCodeTable = {
RequestCodeAndString(X_CreateWindow ),
RequestCodeAndString(X_ChangeWindowAttributes ),
RequestCodeAndString(X_GetWindowAttributes ),
RequestCodeAndString(X_DestroyWindow ),
RequestCodeAndString(X_DestroySubwindows ),
RequestCodeAndString(X_ChangeSaveSet ),
RequestCodeAndString(X_ReparentWindow ),
RequestCodeAndString(X_MapWindow ),
RequestCodeAndString(X_MapSubwindows ),
RequestCodeAndString(X_UnmapWindow ),
RequestCodeAndString(X_UnmapSubwindows ),
RequestCodeAndString(X_ConfigureWindow ),
RequestCodeAndString(X_CirculateWindow ),
RequestCodeAndString(X_GetGeometry ),
RequestCodeAndString(X_QueryTree ),
RequestCodeAndString(X_InternAtom ),
RequestCodeAndString(X_GetAtomName ),
RequestCodeAndString(X_ChangeProperty ),
RequestCodeAndString(X_DeleteProperty ),
RequestCodeAndString(X_GetProperty ),
RequestCodeAndString(X_ListProperties ),
RequestCodeAndString(X_SetSelectionOwner ),
RequestCodeAndString(X_GetSelectionOwner ),
RequestCodeAndString(X_ConvertSelection ),
RequestCodeAndString(X_SendEvent ),
RequestCodeAndString(X_GrabPointer ),
RequestCodeAndString(X_UngrabPointer ),
RequestCodeAndString(X_GrabButton ),
RequestCodeAndString(X_UngrabButton ),
RequestCodeAndString(X_ChangeActivePointerGrab ),
RequestCodeAndString(X_GrabKeyboard ),
RequestCodeAndString(X_UngrabKeyboard ),
RequestCodeAndString(X_GrabKey ),
RequestCodeAndString(X_UngrabKey ),
RequestCodeAndString(X_AllowEvents ),
RequestCodeAndString(X_GrabServer ),
RequestCodeAndString(X_UngrabServer ),
RequestCodeAndString(X_QueryPointer ),
RequestCodeAndString(X_GetMotionEvents ),
RequestCodeAndString(X_TranslateCoords ),
RequestCodeAndString(X_WarpPointer ),
RequestCodeAndString(X_SetInputFocus ),
RequestCodeAndString(X_GetInputFocus ),
RequestCodeAndString(X_QueryKeymap ),
RequestCodeAndString(X_OpenFont ),
RequestCodeAndString(X_CloseFont ),
RequestCodeAndString(X_QueryFont ),
RequestCodeAndString(X_QueryTextExtents ),
RequestCodeAndString(X_ListFonts ),
RequestCodeAndString(X_ListFontsWithInfo ),
RequestCodeAndString(X_SetFontPath ),
RequestCodeAndString(X_GetFontPath ),
RequestCodeAndString(X_CreatePixmap ),
RequestCodeAndString(X_FreePixmap ),
RequestCodeAndString(X_CreateGC ),
RequestCodeAndString(X_ChangeGC ),
RequestCodeAndString(X_CopyGC ),
RequestCodeAndString(X_SetDashes ),
RequestCodeAndString(X_SetClipRectangles ),
RequestCodeAndString(X_FreeGC ),
RequestCodeAndString(X_ClearArea ),
RequestCodeAndString(X_CopyArea ),
RequestCodeAndString(X_CopyPlane ),
RequestCodeAndString(X_PolyPoint ),
RequestCodeAndString(X_PolyLine ),
RequestCodeAndString(X_PolySegment ),
RequestCodeAndString(X_PolyRectangle ),
RequestCodeAndString(X_PolyArc ),
RequestCodeAndString(X_FillPoly ),
RequestCodeAndString(X_PolyFillRectangle ),
RequestCodeAndString(X_PolyFillArc ),
RequestCodeAndString(X_PutImage ),
RequestCodeAndString(X_GetImage ),
RequestCodeAndString(X_PolyText8 ),
RequestCodeAndString(X_PolyText16 ),
RequestCodeAndString(X_ImageText8 ),
RequestCodeAndString(X_ImageText16 ),
RequestCodeAndString(X_CreateColormap ),
RequestCodeAndString(X_FreeColormap ),
RequestCodeAndString(X_CopyColormapAndFree ),
RequestCodeAndString(X_InstallColormap ),
RequestCodeAndString(X_UninstallColormap ),
RequestCodeAndString(X_ListInstalledColormaps ),
RequestCodeAndString(X_AllocColor ),
RequestCodeAndString(X_AllocNamedColor ),
RequestCodeAndString(X_AllocColorCells ),
RequestCodeAndString(X_AllocColorPlanes ),
RequestCodeAndString(X_FreeColors ),
RequestCodeAndString(X_StoreColors ),
RequestCodeAndString(X_StoreNamedColor ),
RequestCodeAndString(X_QueryColors ),
RequestCodeAndString(X_LookupColor ),
RequestCodeAndString(X_CreateCursor ),
RequestCodeAndString(X_CreateGlyphCursor ),
RequestCodeAndString(X_FreeCursor ),
RequestCodeAndString(X_RecolorCursor ),
RequestCodeAndString(X_QueryBestSize ),
RequestCodeAndString(X_QueryExtension ),
RequestCodeAndString(X_ListExtensions ),
RequestCodeAndString(X_ChangeKeyboardMapping ),
RequestCodeAndString(X_GetKeyboardMapping ),
RequestCodeAndString(X_ChangeKeyboardControl ),
RequestCodeAndString(X_GetKeyboardControl ),
RequestCodeAndString(X_Bell ),
RequestCodeAndString(X_ChangePointerControl ),
RequestCodeAndString(X_GetPointerControl ),
RequestCodeAndString(X_SetScreenSaver ),
RequestCodeAndString(X_GetScreenSaver ),
RequestCodeAndString(X_ChangeHosts ),
RequestCodeAndString(X_ListHosts ),
RequestCodeAndString(X_SetAccessControl ),
RequestCodeAndString(X_SetCloseDownMode ),
RequestCodeAndString(X_KillClient ),
RequestCodeAndString(X_RotateProperties ),
RequestCodeAndString(X_ForceScreenSaver ),
RequestCodeAndString(X_SetPointerMapping ),
RequestCodeAndString(X_GetPointerMapping ),
RequestCodeAndString(X_SetModifierMapping ),
RequestCodeAndString(X_GetModifierMapping ),
RequestCodeAndString(X_NoOperation ),
};
for (auto& e : requestCodeTable) {
if (e.first == requestCode) {
return e.second;
}
}
return nullptr;
}
| 39.231683 | 94 | 0.610438 | [
"vector"
] |
fffa775d147c60fa9eba564f7117516b34e8260f | 10,150 | cpp | C++ | Emitter.cpp | gaartok/Fireball-CPP | d2dd2cf42edacc82ad3919a845ca67d53f5aa335 | [
"MIT"
] | null | null | null | Emitter.cpp | gaartok/Fireball-CPP | d2dd2cf42edacc82ad3919a845ca67d53f5aa335 | [
"MIT"
] | null | null | null | Emitter.cpp | gaartok/Fireball-CPP | d2dd2cf42edacc82ad3919a845ca67d53f5aa335 | [
"MIT"
] | null | null | null |
#include "Emitter.hpp"
#include "Misc.hpp"
#include "global.h"
#include "debug.h"
#include <time.h>
const int HALF_RAND = (RAND_MAX / 2);
char particleArray[2][2];
float RandomNum()
{
int rn;
rn = rand();
return ((float)(rn - HALF_RAND) / (float)HALF_RAND);
}
Emitter :: Emitter(int numParticles)
{
int loop;
// sizeof(tParticle) = 60
// dprintf("sizeof(tParticle) = %d\n", sizeof(tParticle));
// dprintf("sizeof(particleArray) = %d\n", sizeof(particleArray));
deadParticles = (tParticle *)malloc(numParticles * sizeof(tParticle));
if (!deadParticles)
{
dprintf("Out of memory!!\n");
theApp->Stop();
}
firstParticle = deadParticles;
// this is a linked list of particles, so i need to establish links
for (loop = 1; loop < numParticles - 1; loop++)
{
deadParticles[loop].prev = &deadParticles[loop - 1];
deadParticles[loop].next = &deadParticles[loop + 1];
}
deadParticles[0].prev = NULL;
deadParticles[0].next = &deadParticles[1];
deadParticles[numParticles - 1].prev = &deadParticles[numParticles - 2];
deadParticles[numParticles - 1].next = NULL;
totalParticles = numParticles;
particleCount = 0;
SetDefault();
aliveParticles = NULL; // start with no alive particles
}
Emitter :: ~Emitter()
{
delete firstParticle;
}
// Function: RotationToDirection
// Purpose: Convert a Yaw and Pitch to a direction vector
void Emitter :: RotationToDirection(float pitch, float yaw, tVector *direction)
{
direction->x = (float)(-sin(yaw) * cos(pitch));
direction->y = (float)sin(pitch);
direction->z = (float)(cos(pitch) * cos(yaw));
}
void Emitter :: SetPos(RECT *posRect)
{
posUL.x = (float)posRect->left;
posUL.y = (float)posRect->top;
posUL.z = 0;
posLR.x = (float)posRect->right;
posLR.y = (float)posRect->bottom;
posLR.z = 0;
}
void Emitter :: SetPos(int left, int right, int top, int bottom)
{
posUL.x = (float)left;
posUL.y = (float)top;
posUL.z = 0;
posLR.x = (float)right;
posLR.y = (float)bottom;
posLR.z = 0;
}
void Emitter :: SetAngles(float yawAngle, float yawVarAngle, float pitchAngle, float pitchVarAngle)
{
yaw = DEGTORAD(yawAngle);
yawVar = DEGTORAD(yawVarAngle);
pitch = DEGTORAD(pitchAngle);
pitchVar = DEGTORAD(pitchVarAngle);
}
void Emitter :: SetSpeed(float newSpeed, float newSpeedVar)
{
speed = newSpeed;
speedVar = newSpeedVar;
}
void Emitter :: SetForce(float forceX, float forceY, float forceZ)
{
force.x = forceX;
force.y = forceY;
force.z = forceZ;
}
void Emitter :: SetEmits(int newEmits, int newEmitsVar)
{
emitsPerFrame = newEmits;
emitVar = newEmitsVar;
}
void Emitter :: SetLife(int newLife, int newLifeVar)
{
life = newLife;
lifeVar = newLifeVar;
}
void Emitter :: SetColors(int newStartColor, int newStartColorVar, int newEndColor, int newEndColorVar)
{
startColor = (float)newStartColor;
startColorVar = (float)newStartColorVar;
endColor = (float)newEndColor;
endColorVar = (float)newEndColorVar;
}
void Emitter :: SetDefault(void)
{
posUL.x = 225.0f; // XYZ POSITION Upper Left
posUL.y = 120.0f; // XYZ POSITION Upper Left
posUL.z = 0.0f; // XYZ POSITION Upper Left
posLR.x = 320.0f; // XYZ POSITION Upper Left
posLR.y = 120.0f; // XYZ POSITION Upper Left
posLR.z = 50.0f; // XYZ POSITION Upper Left
yaw = DEGTORAD(0.0f);
yawVar = DEGTORAD(360.0f);
pitch = DEGTORAD(270.0f);
pitchVar = DEGTORAD(40.0f);
speed = 3.0f;
speedVar = 0.5f;
force.x = 0.000f;
force.y = 0.04f;
force.z = 0.0f;
emitsPerFrame = 2;
emitVar = 3;
life = 180;
lifeVar = 15;
startColor = 7.0f;
startColorVar = 1.0f;
endColor = 1.0f;
endColorVar = 1.0f;
}
BOOL Emitter :: AddParticle(void)
{
tParticle * thisParticle;
float thisStart;
float thisEnd;
float thisYaw;
float thisPitch;
float thisSpeed;
if ((deadParticles != NULL) && (particleCount < totalParticles) && (life > 0))
{
thisParticle = deadParticles; // the current particle
deadParticles = deadParticles->next; // fix the pool pointers
if (deadParticles != NULL)
deadParticles->prev = NULL;
if (aliveParticles != NULL)
aliveParticles->prev = thisParticle; // set back link
thisParticle->next = aliveParticles; // set its next pointer
thisParticle->prev = NULL; // it has no back pointer
aliveParticles = thisParticle; // set it in the emitter
thisParticle->pos.x = randFloat(posUL.x, posLR.x);
thisParticle->pos.y = randFloat(posUL.y, posLR.y);
thisParticle->pos.z = randFloat(posUL.z, posLR.z);
thisParticle->prevPos.x = thisParticle->pos.x;
thisParticle->prevPos.y = thisParticle->pos.y;
thisParticle->prevPos.z = thisParticle->pos.z;
// calculate the starting direction vector
thisYaw = yaw + (yawVar * RandomNum());
thisPitch = pitch + (pitchVar * RandomNum());
// convert the rotations to a vector
RotationToDirection(thisPitch, thisYaw, &thisParticle->dir);
// multiply in the speed factor
thisSpeed = speed + (speedVar * RandomNum());
thisParticle->dir.x *= thisSpeed;
thisParticle->dir.y *= thisSpeed;
thisParticle->dir.z *= thisSpeed;
thisStart = startColor + (startColorVar * randFloat(0, 1));
thisEnd = endColor + (endColorVar * randFloat(0, 1));
thisParticle->color = thisStart;
thisParticle->life = life + (int)((float)lifeVar * RandomNum());
thisParticle->deltaColor = (thisEnd - thisStart) / (float)thisParticle->life;
particleCount++; // a new particle is born
return TRUE;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// Function: updateParticle
// Purpose: updateParticle settings
// Arguments: The particle to update and the emitter it came from
///////////////////////////////////////////////////////////////////////////////
BOOL Emitter :: UpdateParticle(tParticle *thisParticle)
{
// IF THIS IS AN VALID PARTICLE
if ((thisParticle != NULL) && (thisParticle->life > 0))
{
// SAVE ITS OLD POS FOR ANTI ALIASING
thisParticle->prevPos.x = thisParticle->pos.x;
thisParticle->prevPos.y = thisParticle->pos.y;
thisParticle->prevPos.z = thisParticle->pos.z;
// CALCULATE THE NEW
thisParticle->pos.x += thisParticle->dir.x;
thisParticle->pos.y += thisParticle->dir.y;
thisParticle->pos.z += thisParticle->dir.z;
// APPLY GLOBAL FORCE TO DIRECTION
thisParticle->dir.x += force.x;
thisParticle->dir.y += force.y;
thisParticle->dir.z += force.z;
// SAVE THE OLD COLOR
thisParticle->prevColor = thisParticle->color;
// GET THE NEW COLOR
thisParticle->color += thisParticle->deltaColor;
thisParticle->life--; // IT IS A CYCLE OLDER
return TRUE;
}
else if (thisParticle != NULL && thisParticle->life == 0) // free this sucker up back to the main pool
{
if (thisParticle->prev != NULL)
thisParticle->prev->next = thisParticle->next;
else
aliveParticles = thisParticle->next;
if (thisParticle->next != NULL)
thisParticle->next->prev = thisParticle->prev;
thisParticle->next = deadParticles;
thisParticle->prev = NULL;
if (deadParticles != NULL)
deadParticles->prev = thisParticle;
deadParticles = thisParticle; // new pool pointer
if (particleCount > 0)
particleCount--; // add one to pool
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// Function: updateEmitter
// Purpose: updateEmitter setting
// Arguments: The Emitter to update
// Notes: This is called once per frame to update the emitter
///////////////////////////////////////////////////////////////////////////////
void Emitter :: Update(void)
{
int loop;
int emits;
tParticle * thisParticle;
tParticle * next;
if (aliveParticles != NULL)
{
// GO THROUGH THE PARTICLES AND UPDATE THEM
thisParticle = aliveParticles;
while (thisParticle)
{
next = thisParticle->next;
UpdateParticle(thisParticle);
thisParticle = next;
}
}
// don't add new particles if life == 0
if (life == 0)
return;
// EMIT PARTICLES FOR THIS FRAME
emits = emitsPerFrame + (int)((float)emitVar * RandomNum());
for (loop = 0; loop < emits; loop++)
AddParticle();
}
///////////////////////////////////////////////////////////////////////////////
// Function: renderEmitter
// Purpose: render particle system
// Arguments: The Emitter to render
// Notes: This is called once per frame to render the emitter
///////////////////////////////////////////////////////////////////////////////
void Emitter :: Render(void)
{
tParticle * thisParticle;
if (aliveParticles != NULL)
{
thisParticle = aliveParticles;
renderer->LockSurface();
while (thisParticle)
{
// if (antiAlias)
// {
// glColor3f(particle->prevColor.r, particle->prevColor.g, particle->prevColor.b);
// glVertex3f(particle->prevPos.x,particle->prevPos.y,particle->prevPos.z);
// }
memset(particleArray, (int)thisParticle->color, sizeof(particleArray));
renderer->DrawArray((char *)particleArray, 2, 2, (int)thisParticle->pos.x, (int)thisParticle->pos.y);
thisParticle = thisParticle->next;
}
renderer->UnlockSurface();
}
}
| 26.710526 | 111 | 0.578621 | [
"render",
"vector"
] |
0802d356c6085dd4506a168b341e20c2fa8c3f4b | 680 | hpp | C++ | test/ShaderWriter/CompileSPIRV.hpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | test/ShaderWriter/CompileSPIRV.hpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | test/ShaderWriter/CompileSPIRV.hpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | #pragma once
#include "WriterCommon.hpp"
#if SDW_Test_HasVulkan && SDW_HasVulkanLayer
# include <VulkanLayer/VulkanLayer.hpp>
#endif
namespace test
{
bool createSPIRVContext( sdw_test::TestCounts & testCounts );
void destroySPIRVContext( sdw_test::TestCounts & testCounts );
bool compileSpirV( ::ast::Shader const & shader
, std::vector< uint32_t > const & spirv
, std::string & errors
, sdw_test::TestCounts & testCounts );
#if SDW_Test_HasVulkan && SDW_HasVulkanLayer
ast::vk::BuilderContext createBuilderContext( sdw_test::TestCounts & testCounts );
bool validateProgram( ast::vk::ProgramPipeline const & program
, sdw_test::TestCounts & testCounts );
#endif
}
| 29.565217 | 83 | 0.758824 | [
"vector"
] |
0806ca40ef7cfd3cf79573f6ec29947f97b9eab5 | 32,437 | cc | C++ | be/src/exec/aggregation-node.cc | mapr/impala | 2b626c8e9f4c666d23872c228cf43daae4c9acbb | [
"Apache-2.0"
] | 2 | 2015-11-17T16:58:47.000Z | 2017-01-10T04:15:05.000Z | be/src/exec/aggregation-node.cc | mapr/impala | 2b626c8e9f4c666d23872c228cf43daae4c9acbb | [
"Apache-2.0"
] | 1 | 2016-03-10T16:34:10.000Z | 2016-03-10T16:34:10.000Z | be/src/exec/aggregation-node.cc | mapr/impala | 2b626c8e9f4c666d23872c228cf43daae4c9acbb | [
"Apache-2.0"
] | 6 | 2015-12-22T14:52:38.000Z | 2019-07-06T08:34:23.000Z | // Copyright 2012 Cloudera 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.
#include "exec/aggregation-node.h"
#include <math.h>
#include <sstream>
#include <boost/functional/hash.hpp>
#include <thrift/protocol/TDebugProtocol.h>
#include <x86intrin.h>
#include "codegen/codegen-anyval.h"
#include "codegen/llvm-codegen.h"
#include "exec/hash-table.inline.h"
#include "exprs/agg-fn-evaluator.h"
#include "exprs/expr.h"
#include "runtime/descriptors.h"
#include "runtime/mem-pool.h"
#include "runtime/raw-value.h"
#include "runtime/row-batch.h"
#include "runtime/runtime-state.h"
#include "runtime/string-value.inline.h"
#include "runtime/tuple.h"
#include "runtime/tuple-row.h"
#include "udf/udf-internal.h"
#include "util/debug-util.h"
#include "util/runtime-profile.h"
#include "gen-cpp/Exprs_types.h"
#include "gen-cpp/PlanNodes_types.h"
using namespace impala;
using namespace std;
using namespace boost;
using namespace llvm;
namespace impala {
const char* AggregationNode::LLVM_CLASS_NAME = "class.impala::AggregationNode";
// TODO: pass in maximum size; enforce by setting limit in mempool
AggregationNode::AggregationNode(ObjectPool* pool, const TPlanNode& tnode,
const DescriptorTbl& descs)
: ExecNode(pool, tnode, descs),
agg_tuple_id_(tnode.agg_node.agg_tuple_id),
agg_tuple_desc_(NULL),
singleton_output_tuple_(NULL),
codegen_process_row_batch_fn_(NULL),
process_row_batch_fn_(NULL),
is_merge_(tnode.agg_node.__isset.is_merge ? tnode.agg_node.is_merge : false),
needs_finalize_(tnode.agg_node.need_finalize),
build_timer_(NULL),
get_results_timer_(NULL),
hash_table_buckets_counter_(NULL) {
}
Status AggregationNode::Init(const TPlanNode& tnode) {
RETURN_IF_ERROR(ExecNode::Init(tnode));
RETURN_IF_ERROR(
Expr::CreateExprTrees(pool_, tnode.agg_node.grouping_exprs, &probe_exprs_));
for (int i = 0; i < tnode.agg_node.aggregate_functions.size(); ++i) {
AggFnEvaluator* evaluator;
RETURN_IF_ERROR(AggFnEvaluator::Create(
pool_, tnode.agg_node.aggregate_functions[i], &evaluator));
aggregate_evaluators_.push_back(evaluator);
}
return Status::OK;
}
Status AggregationNode::Prepare(RuntimeState* state) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
RETURN_IF_ERROR(ExecNode::Prepare(state));
tuple_pool_.reset(new MemPool(mem_tracker()));
build_timer_ = ADD_TIMER(runtime_profile(), "BuildTime");
get_results_timer_ = ADD_TIMER(runtime_profile(), "GetResultsTime");
hash_table_buckets_counter_ =
ADD_COUNTER(runtime_profile(), "BuildBuckets", TCounterType::UNIT);
hash_table_load_factor_counter_ =
ADD_COUNTER(runtime_profile(), "LoadFactor", TCounterType::DOUBLE_VALUE);
agg_tuple_desc_ = state->desc_tbl().GetTupleDescriptor(agg_tuple_id_);
RETURN_IF_ERROR(Expr::Prepare(probe_exprs_, state, child(0)->row_desc(), false));
// Construct build exprs from agg_tuple_desc_
for (int i = 0; i < probe_exprs_.size(); ++i) {
SlotDescriptor* desc = agg_tuple_desc_->slots()[i];
Expr* expr = new SlotRef(desc);
state->obj_pool()->Add(expr);
build_exprs_.push_back(expr);
}
RETURN_IF_ERROR(Expr::Prepare(build_exprs_, state, row_desc(), false));
int j = probe_exprs_.size();
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++j) {
// skip non-materialized slots; we don't have evaluators instantiated for those
while (!agg_tuple_desc_->slots()[j]->is_materialized()) {
DCHECK_LT(j, agg_tuple_desc_->slots().size() - 1)
<< "#eval= " << aggregate_evaluators_.size()
<< " #probe=" << probe_exprs_.size();
++j;
}
SlotDescriptor* desc = agg_tuple_desc_->slots()[j];
RETURN_IF_ERROR(aggregate_evaluators_[i]->Prepare(state, child(0)->row_desc(), desc));
}
// TODO: how many buckets?
hash_tbl_.reset(new HashTable(state, build_exprs_, probe_exprs_, 1, true, true,
id(), mem_tracker()));
if (probe_exprs_.empty()) {
// create single output tuple now; we need to output something
// even if our input is empty
singleton_output_tuple_ = ConstructAggTuple();
hash_tbl_->Insert(reinterpret_cast<TupleRow*>(&singleton_output_tuple_));
output_iterator_ = hash_tbl_->Begin();
}
if (state->codegen_enabled()) {
DCHECK(state->codegen() != NULL);
Function* update_tuple_fn = CodegenUpdateAggTuple(state->codegen());
if (update_tuple_fn != NULL) {
codegen_process_row_batch_fn_ =
CodegenProcessRowBatch(state->codegen(), update_tuple_fn);
if (codegen_process_row_batch_fn_ != NULL) {
// Update to using codegen'd process row batch.
state->codegen()->AddFunctionToJit(
codegen_process_row_batch_fn_,
reinterpret_cast<void**>(&process_row_batch_fn_));
AddRuntimeExecOption("Codegen Enabled");
}
}
}
return Status::OK;
}
Status AggregationNode::Open(RuntimeState* state) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
RETURN_IF_ERROR(ExecNode::Open(state));
RETURN_IF_ERROR(Expr::Open(probe_exprs_, state));
RETURN_IF_ERROR(Expr::Open(build_exprs_, state));
for (int i = 0; i < aggregate_evaluators_.size(); ++i) {
RETURN_IF_ERROR(aggregate_evaluators_[i]->Open(state));
}
RETURN_IF_ERROR(children_[0]->Open(state));
RowBatch batch(children_[0]->row_desc(), state->batch_size(), mem_tracker());
int64_t num_input_rows = 0;
while (true) {
bool eos;
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(state->CheckQueryState());
RETURN_IF_ERROR(children_[0]->GetNext(state, &batch, &eos));
SCOPED_TIMER(build_timer_);
if (VLOG_ROW_IS_ON) {
for (int i = 0; i < batch.num_rows(); ++i) {
TupleRow* row = batch.GetRow(i);
VLOG_ROW << "input row: " << PrintRow(row, children_[0]->row_desc());
}
}
if (process_row_batch_fn_ != NULL) {
process_row_batch_fn_(this, &batch);
} else if (probe_exprs_.empty()) {
ProcessRowBatchNoGrouping(&batch);
} else {
ProcessRowBatchWithGrouping(&batch);
}
COUNTER_SET(hash_table_buckets_counter_, hash_tbl_->num_buckets());
COUNTER_SET(hash_table_load_factor_counter_, hash_tbl_->load_factor());
num_input_rows += batch.num_rows();
// We must set output_iterator_ here, rather than outside the loop, because
// output_iterator_ must be set if the function returns within the loop
output_iterator_ = hash_tbl_->Begin();
batch.Reset();
RETURN_IF_ERROR(state->CheckQueryState());
if (eos) break;
}
// We have consumed all of the input from the child and transfered ownership of the
// resources we need, so the child can be closed safely to release its resources.
child(0)->Close(state);
VLOG_FILE << "aggregated " << num_input_rows << " input rows into "
<< hash_tbl_->size() << " output rows";
return Status::OK;
}
Status AggregationNode::GetNext(RuntimeState* state, RowBatch* row_batch, bool* eos) {
SCOPED_TIMER(runtime_profile_->total_time_counter());
RETURN_IF_ERROR(ExecDebugAction(TExecNodePhase::GETNEXT, state));
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(state->CheckQueryState());
SCOPED_TIMER(get_results_timer_);
if (ReachedLimit()) {
*eos = true;
return Status::OK;
}
Expr** conjuncts = &conjuncts_[0];
int num_conjuncts = conjuncts_.size();
while (!output_iterator_.AtEnd() && !row_batch->AtCapacity()) {
int row_idx = row_batch->AddRow();
TupleRow* row = row_batch->GetRow(row_idx);
Tuple* agg_tuple = output_iterator_.GetRow()->GetTuple(0);
FinalizeAggTuple(agg_tuple);
output_iterator_.Next<false>();
row->SetTuple(0, agg_tuple);
if (ExecNode::EvalConjuncts(conjuncts, num_conjuncts, row)) {
VLOG_ROW << "output row: " << PrintRow(row, row_desc());
row_batch->CommitLastRow();
++num_rows_returned_;
if (ReachedLimit()) break;
}
}
*eos = output_iterator_.AtEnd() || ReachedLimit();
COUNTER_SET(rows_returned_counter_, num_rows_returned_);
return Status::OK;
}
void AggregationNode::Close(RuntimeState* state) {
if (is_closed()) return;
// Iterate through the remaining rows in the hash table and call Serialize/Finalize on
// them in order to free any memory allocated by UDAs
while (!output_iterator_.AtEnd()) {
Tuple* agg_tuple = output_iterator_.GetRow()->GetTuple(0);
FinalizeAggTuple(agg_tuple);
output_iterator_.Next<false>();
}
if (tuple_pool_.get() != NULL) tuple_pool_->FreeAll();
if (hash_tbl_.get() != NULL) hash_tbl_->Close();
for (int i = 0; i < aggregate_evaluators_.size(); ++i) {
aggregate_evaluators_[i]->Close(state);
}
Expr::Close(probe_exprs_, state);
Expr::Close(build_exprs_, state);
ExecNode::Close(state);
}
Tuple* AggregationNode::ConstructAggTuple() {
Tuple* agg_tuple = Tuple::Create(agg_tuple_desc_->byte_size(), tuple_pool_.get());
vector<SlotDescriptor*>::const_iterator slot_desc = agg_tuple_desc_->slots().begin();
// copy grouping values
for (int i = 0; i < probe_exprs_.size(); ++i, ++slot_desc) {
if (hash_tbl_->last_expr_value_null(i)) {
agg_tuple->SetNull((*slot_desc)->null_indicator_offset());
} else {
void* src = hash_tbl_->last_expr_value(i);
void* dst = agg_tuple->GetSlot((*slot_desc)->tuple_offset());
RawValue::Write(src, dst, (*slot_desc)->type(), tuple_pool_.get());
}
}
// Initialize aggregate output.
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++slot_desc) {
while (!(*slot_desc)->is_materialized()) ++slot_desc;
AggFnEvaluator* evaluator = aggregate_evaluators_[i];
evaluator->Init(agg_tuple);
// Codegen specific path.
// To minimize branching on the UpdateAggTuple path, initialize the result value
// so that UpdateAggTuple doesn't have to check if the aggregation
// dst slot is null.
// - sum/count: 0
// - min: max_value
// - max: min_value
// TODO: remove when we don't use the irbuilder for codegen here.
// This optimization no longer applies with AnyVal
if ((*slot_desc)->type().type != TYPE_STRING &&
(*slot_desc)->type().type != TYPE_TIMESTAMP &&
(*slot_desc)->type().type != TYPE_CHAR &&
(*slot_desc)->type().type != TYPE_DECIMAL) {
ExprValue default_value;
void* default_value_ptr = NULL;
switch (evaluator->agg_op()) {
case AggFnEvaluator::MIN:
default_value_ptr = default_value.SetToMax((*slot_desc)->type());
RawValue::Write(default_value_ptr, agg_tuple, *slot_desc, NULL);
break;
case AggFnEvaluator::MAX:
default_value_ptr = default_value.SetToMin((*slot_desc)->type());
RawValue::Write(default_value_ptr, agg_tuple, *slot_desc, NULL);
break;
default:
break;
}
}
}
return agg_tuple;
}
void AggregationNode::UpdateAggTuple(Tuple* tuple, TupleRow* row) {
DCHECK(tuple != NULL || aggregate_evaluators_.empty());
for (vector<AggFnEvaluator*>::const_iterator evaluator = aggregate_evaluators_.begin();
evaluator != aggregate_evaluators_.end(); ++evaluator) {
if (is_merge_) {
(*evaluator)->Merge(row, tuple);
} else {
(*evaluator)->Update(row, tuple);
}
}
}
void AggregationNode::FinalizeAggTuple(Tuple* tuple) {
DCHECK(tuple != NULL || aggregate_evaluators_.empty());
for (vector<AggFnEvaluator*>::const_iterator evaluator = aggregate_evaluators_.begin();
evaluator != aggregate_evaluators_.end(); ++evaluator) {
if (needs_finalize_) {
(*evaluator)->Finalize(tuple);
} else {
(*evaluator)->Serialize(tuple);
}
}
}
void AggregationNode::DebugString(int indentation_level, stringstream* out) const {
*out << string(indentation_level * 2, ' ');
*out << "AggregationNode(tuple_id=" << agg_tuple_id_
<< " is_merge=" << is_merge_ << " needs_finalize=" << needs_finalize_
<< " probe_exprs=" << Expr::DebugString(probe_exprs_)
<< " agg_exprs=" << AggFnEvaluator::DebugString(aggregate_evaluators_);
ExecNode::DebugString(indentation_level, out);
*out << ")";
}
IRFunction::Type GetHllUpdateFunction(const ColumnType& type) {
switch (type.type) {
case TYPE_BOOLEAN: return IRFunction::HLL_UPDATE_BOOLEAN;
case TYPE_TINYINT: return IRFunction::HLL_UPDATE_TINYINT;
case TYPE_SMALLINT: return IRFunction::HLL_UPDATE_SMALLINT;
case TYPE_INT: return IRFunction::HLL_UPDATE_INT;
case TYPE_BIGINT: return IRFunction::HLL_UPDATE_BIGINT;
case TYPE_FLOAT: return IRFunction::HLL_UPDATE_FLOAT;
case TYPE_DOUBLE: return IRFunction::HLL_UPDATE_DOUBLE;
case TYPE_STRING: return IRFunction::HLL_UPDATE_STRING;
case TYPE_DECIMAL: return IRFunction::HLL_UPDATE_DECIMAL;
default:
DCHECK(false) << "Unsupported type: " << type;
return IRFunction::FN_END;
}
}
// IR Generation for updating a single aggregation slot. Signature is:
// void UpdateSlot(FunctionContext* fn_ctx, AggTuple* agg_tuple, char** row)
//
// The IR for sum(double_col) is:
// define void @UpdateSlot(%"class.impala_udf::FunctionContext"* %fn_ctx,
// { i8, double }* %agg_tuple, i8** %row) {
// entry:
// %src_null_ptr = alloca i1
// %src_value = call double @SlotRef(i8** %row, i8* null, i1* %src_null_ptr)
// %child_null = load i1* %src_null_ptr
// br i1 %child_null, label %ret, label %src_not_null
//
// src_not_null: ; preds = %entry
// %dst_slot_ptr = getelementptr inbounds { i8, double }* %agg_tuple, i32 0, i32 1
// call void @SetNotNull({ i8, double }* %agg_tuple)
// %dst_val = load double* %dst_slot_ptr
// %0 = fadd double %dst_val, %src_value
// store double %0, double* %dst_slot_ptr
// br label %ret
//
// ret: ; preds = %src_not_null, %entry
// ret void
// }
//
// The IR for ndv(double_col) is:
// define void @UpdateSlot(%"class.impala_udf::FunctionContext"* %fn_ctx,
// { i8, %"struct.impala::StringValue" }* %agg_tuple,
// i8** %row) {
// entry:
// %src_null_ptr = alloca i1
// %src_value = call double @SlotRef(i8** %row, i8* null, i1* %src_null_ptr)
// %child_null = load i1* %src_null_ptr
// br i1 %child_null, label %ret, label %src_not_null
//
// src_not_null: ; preds = %entry
// %dst_slot_ptr = getelementptr inbounds
// { i8, %"struct.impala::StringValue" }* %agg_tuple, i32 0, i32 1
// call void @SetNotNull({ i8, %"struct.impala::StringValue" }* %agg_tuple)
// %dst_val = load %"struct.impala::StringValue"* %dst_slot_ptr
// %src_anyval = insertvalue { i8, double } zeroinitializer, double %src_value, 1
// %src_lowered_ptr = alloca { i8, double }
// store { i8, double } %src_anyval, { i8, double }* %src_lowered_ptr
// %src_unlowered_ptr = bitcast { i8, double }* %src_lowered_ptr to
// %"struct.impala_udf::DoubleVal"*
// %ptr = extractvalue %"struct.impala::StringValue" %dst_val, 0
// %dst_stringval = insertvalue { i64, i8* } zeroinitializer, i8* %ptr, 1
// %len = extractvalue %"struct.impala::StringValue" %dst_val, 1
// %0 = extractvalue { i64, i8* } %dst_stringval, 0
// %1 = zext i32 %len to i64
// %2 = shl i64 %1, 32
// %3 = and i64 %0, 0
// %4 = or i64 %3, %2
// %dst_stringval1 = insertvalue { i64, i8* } %dst_stringval, i64 %4, 0
// %dst_lowered_ptr = alloca { i64, i8* }
// store { i64, i8* } %dst_stringval1, { i64, i8* }* %dst_lowered_ptr
// %dst_unlowered_ptr = bitcast { i64, i8* }* %dst_lowered_ptr to
// %"struct.impala_udf::StringVal"*
// call void @HllUpdate(%"class.impala_udf::FunctionContext"* %fn_ctx,
// %"struct.impala_udf::DoubleVal"* %src_unlowered_ptr,
// %"struct.impala_udf::StringVal"* %dst_unlowered_ptr)
// %anyval_result = load { i64, i8* }* %dst_lowered_ptr
// %5 = extractvalue { i64, i8* } %anyval_result, 1
// %6 = insertvalue %"struct.impala::StringValue" zeroinitializer, i8* %5, 0
// %7 = extractvalue { i64, i8* } %anyval_result, 0
// %8 = ashr i64 %7, 32
// %9 = trunc i64 %8 to i32
// %10 = insertvalue %"struct.impala::StringValue" %6, i32 %9, 1
// store %"struct.impala::StringValue" %10,
// %"struct.impala::StringValue"* %dst_slot_ptr
// br label %ret
//
// ret: ; preds = %src_not_null, %entry
// ret void
// }
llvm::Function* AggregationNode::CodegenUpdateSlot(
LlvmCodeGen* codegen, AggFnEvaluator* evaluator, SlotDescriptor* slot_desc) {
int field_idx = slot_desc->field_idx();
DCHECK(slot_desc->is_materialized());
LLVMContext& context = codegen->context();
PointerType* fn_ctx_type =
codegen->GetPtrType(FunctionContextImpl::LLVM_FUNCTIONCONTEXT_NAME);
StructType* tuple_struct = agg_tuple_desc_->GenerateLlvmStruct(codegen);
PointerType* tuple_ptr_type = PointerType::get(tuple_struct, 0);
PointerType* ptr_type = codegen->ptr_type();
// Create UpdateSlot prototype
LlvmCodeGen::FnPrototype prototype(codegen, "UpdateSlot", codegen->void_type());
prototype.AddArgument(LlvmCodeGen::NamedVariable("fn_ctx", fn_ctx_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_tuple", tuple_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", PointerType::get(ptr_type, 0)));
LlvmCodeGen::LlvmBuilder builder(context);
Value* args[3];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
Value* fn_ctx_arg = args[0];
Value* agg_tuple_arg = args[1];
Value* row_arg = args[2];
LlvmCodeGen::NamedVariable null_var("src_null_ptr", codegen->boolean_type());
Value* src_is_null_ptr = codegen->CreateEntryBlockAlloca(fn, null_var);
// Call expr function to get src slot value
DCHECK_EQ(evaluator->input_exprs().size(), 1);
Expr* input_expr = evaluator->input_exprs()[0];
Function* agg_expr_fn = input_expr->codegen_fn();
int scratch_buffer_size = input_expr->scratch_buffer_size();
DCHECK_EQ(scratch_buffer_size, 0);
DCHECK(agg_expr_fn != NULL);
if (agg_expr_fn == NULL) return NULL;
BasicBlock* src_not_null_block, *ret_block;
codegen->CreateIfElseBlocks(fn, "src_not_null", "ret", &src_not_null_block, &ret_block);
Value* expr_args[] = { row_arg, ConstantPointerNull::get(ptr_type), src_is_null_ptr };
Value* src_value = input_expr->CodegenGetValue(codegen, builder.GetInsertBlock(),
expr_args, ret_block, src_not_null_block, "src_value");
// Src slot is not null, update dst_slot
builder.SetInsertPoint(src_not_null_block);
Value* dst_ptr = builder.CreateStructGEP(agg_tuple_arg, field_idx, "dst_slot_ptr");
Value* result = NULL;
if (slot_desc->is_nullable()) {
// Dst is NULL, just update dst slot to src slot and clear null bit
Function* clear_null_fn = slot_desc->CodegenUpdateNull(codegen, tuple_struct, false);
builder.CreateCall(clear_null_fn, agg_tuple_arg);
}
// Update the slot
Value* dst_value = builder.CreateLoad(dst_ptr, "dst_val");
switch (evaluator->agg_op()) {
case AggFnEvaluator::COUNT:
result = builder.CreateAdd(dst_value,
codegen->GetIntConstant(TYPE_BIGINT, 1), "count_inc");
break;
case AggFnEvaluator::MIN: {
Function* min_fn = codegen->CodegenMinMax(slot_desc->type(), true);
Value* min_args[] = { dst_value, src_value };
result = builder.CreateCall(min_fn, min_args, "min_value");
break;
}
case AggFnEvaluator::MAX: {
Function* max_fn = codegen->CodegenMinMax(slot_desc->type(), false);
Value* max_args[] = { dst_value, src_value };
result = builder.CreateCall(max_fn, max_args, "max_value");
break;
}
case AggFnEvaluator::SUM:
if (slot_desc->type().type == TYPE_FLOAT || slot_desc->type().type == TYPE_DOUBLE) {
result = builder.CreateFAdd(dst_value, src_value);
} else {
result = builder.CreateAdd(dst_value, src_value);
}
break;
case AggFnEvaluator::NDV: {
DCHECK_EQ(slot_desc->type().type, TYPE_STRING);
IRFunction::Type ir_function_type = is_merge_ ? IRFunction::HLL_MERGE
: GetHllUpdateFunction(input_expr->type());
Function* hll_fn = codegen->GetFunction(ir_function_type);
// Convert src_value to *Val src_anyval. src_value is the returned value of a
// codegen'd expr compute function, so either is a native type or a StringVal*.
CodegenAnyVal src_anyval = CodegenAnyVal::GetNonNullVal(
codegen, &builder, input_expr->type(), "src_anyval");
if (src_value->getType()->isPointerTy()) {
DCHECK_EQ(src_value->getType(), codegen->GetPtrType(TYPE_STRING))
<< endl << LlvmCodeGen::Print(src_value);
src_anyval.SetFromRawPtr(src_value);
} else {
src_anyval.SetFromRawValue(src_value);
}
// Create pointer to src_anyval to pass to HllUpdate() function. We must use the
// unlowered type.
Value* src_lowered_ptr = codegen->CreateEntryBlockAlloca(
fn, LlvmCodeGen::NamedVariable("src_lowered_ptr",
src_anyval.value()->getType()));
builder.CreateStore(src_anyval.value(), src_lowered_ptr);
Type* unlowered_ptr_type =
CodegenAnyVal::GetUnloweredType(codegen, input_expr->type())->getPointerTo();
Value* src_unlowered_ptr =
builder.CreateBitCast(src_lowered_ptr, unlowered_ptr_type, "src_unlowered_ptr");
// Create StringVal* intermediate argument from dst_value
CodegenAnyVal dst_stringval = CodegenAnyVal::GetNonNullVal(
codegen, &builder, TYPE_STRING, "dst_stringval");
dst_stringval.SetFromRawValue(dst_value);
// Create pointer to dst_stringval to pass to HllUpdate() function. We must use
// the unlowered type.
Value* dst_lowered_ptr = codegen->CreateEntryBlockAlloca(
fn, LlvmCodeGen::NamedVariable("dst_lowered_ptr",
dst_stringval.value()->getType()));
builder.CreateStore(dst_stringval.value(), dst_lowered_ptr);
unlowered_ptr_type =
codegen->GetPtrType(CodegenAnyVal::GetUnloweredType(codegen, TYPE_STRING));
Value* dst_unlowered_ptr =
builder.CreateBitCast(dst_lowered_ptr, unlowered_ptr_type, "dst_unlowered_ptr");
// Call 'hll_fn'
builder.CreateCall3(hll_fn, fn_ctx_arg, src_unlowered_ptr, dst_unlowered_ptr);
// Convert StringVal intermediate 'dst_arg' back to StringValue
Value* anyval_result = builder.CreateLoad(dst_lowered_ptr, "anyval_result");
result = CodegenAnyVal(codegen, &builder, TYPE_STRING, anyval_result)
.ToRawValue();
break;
}
default:
DCHECK(false) << "bad aggregate operator: " << evaluator->agg_op();
}
builder.CreateStore(result, dst_ptr);
builder.CreateBr(ret_block);
builder.SetInsertPoint(ret_block);
builder.CreateRetVoid();
return codegen->FinalizeFunction(fn);
}
// IR codegen for the UpdateAggTuple loop. This loop is query specific and
// based on the aggregate functions. The function signature must match the non-
// codegen'd UpdateAggTuple exactly.
// For the query:
// select count(*), count(int_col), sum(double_col) the IR looks like:
//
// define void @UpdateAggTuple(%"class.impala::AggregationNode"* %this_ptr,
// %"class.impala::Tuple"* %agg_tuple,
// %"class.impala::TupleRow"* %tuple_row) {
// entry:
// %tuple = bitcast %"class.impala::AggregationNode"* %agg_tuple to
// { i8, i64, i64, double }*
// %row = bitcast %"class.impala::TupleRow"* %tuple_row to i8**
// %src_slot = getelementptr inbounds { i8, i64, i64, double }* %tuple, i32 0, i32 2
// %count_star_val = load i64* %src_slot
// %count_star_inc = add i64 %count_star_val, 1
// store i64 %count_star_inc, i64* %src_slot
// call void @UpdateSlot({ i8, i64, i64, double }* %tuple, i8** %row)
// call void @UpdateSlot2({ i8, i64, i64, double }* %tuple, i8** %row)
// ret void
// }
Function* AggregationNode::CodegenUpdateAggTuple(LlvmCodeGen* codegen) {
SCOPED_TIMER(codegen->codegen_timer());
for (int i = 0; i < probe_exprs_.size(); ++i) {
if (probe_exprs_[i]->codegen_fn() == NULL) {
VLOG_QUERY << "Could not codegen UpdateAggTuple because "
<< "codegen for the grouping exprs is not yet supported.";
return NULL;
}
}
int j = probe_exprs_.size();
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++j) {
// skip non-materialized slots; we don't have evaluators instantiated for those
while (!agg_tuple_desc_->slots()[j]->is_materialized()) {
DCHECK_LT(j, agg_tuple_desc_->slots().size() - 1);
++j;
}
SlotDescriptor* slot_desc = agg_tuple_desc_->slots()[j];
AggFnEvaluator* evaluator = aggregate_evaluators_[i];
// Timestamp and char are never supported. NDV supports decimal and string but no
// other functions.
// TODO: the other aggregate functions might work with decimal as-is
if (slot_desc->type().type == TYPE_TIMESTAMP || slot_desc->type().type == TYPE_CHAR ||
(evaluator->agg_op() != AggFnEvaluator::NDV &&
(slot_desc->type().type == TYPE_DECIMAL ||
slot_desc->type().type == TYPE_STRING))) {
VLOG_QUERY << "Could not codegen UpdateAggTuple because "
<< "string, char, timestamp and decimal are not yet supported.";
return NULL;
}
// If the evaluator can't be generated, bail generating this function
if (!evaluator->is_count_star() &&
evaluator->input_exprs()[0]->codegen_fn() == NULL) {
VLOG_QUERY << "Could not codegen UpdateAggTuple because the "
<< "underlying exprs cannot be codegened.";
return NULL;
}
// Don't codegen things that aren't builtins (for now)
if (!evaluator->is_builtin()) return NULL;
}
if (agg_tuple_desc_->GenerateLlvmStruct(codegen) == NULL) {
VLOG_QUERY << "Could not codegen UpdateAggTuple because we could"
<< "not generate a matching llvm struct for the result agg tuple.";
return NULL;
}
// Get the types to match the UpdateAggTuple signature
Type* agg_node_type = codegen->GetType(AggregationNode::LLVM_CLASS_NAME);
Type* agg_tuple_type = codegen->GetType(Tuple::LLVM_CLASS_NAME);
Type* tuple_row_type = codegen->GetType(TupleRow::LLVM_CLASS_NAME);
DCHECK(agg_node_type != NULL);
DCHECK(agg_tuple_type != NULL);
DCHECK(tuple_row_type != NULL);
PointerType* agg_node_ptr_type = PointerType::get(agg_node_type, 0);
PointerType* agg_tuple_ptr_type = PointerType::get(agg_tuple_type, 0);
PointerType* tuple_row_ptr_type = PointerType::get(tuple_row_type, 0);
// The signature needs to match the non-codegen'd signature exactly.
PointerType* ptr_type = codegen->ptr_type();
StructType* tuple_struct = agg_tuple_desc_->GenerateLlvmStruct(codegen);
PointerType* tuple_ptr = PointerType::get(tuple_struct, 0);
LlvmCodeGen::FnPrototype prototype(codegen, "UpdateAggTuple", codegen->void_type());
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", agg_node_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_tuple", agg_tuple_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple_row", tuple_row_ptr_type));
LlvmCodeGen::LlvmBuilder builder(codegen->context());
Value* args[3];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
// Cast the parameter types to the internal llvm runtime types.
args[1] = builder.CreateBitCast(args[1], tuple_ptr, "tuple");
args[2] = builder.CreateBitCast(args[2], PointerType::get(ptr_type, 0), "row");
// Loop over each expr and generate the IR for that slot. If the expr is not
// count(*), generate a helper IR function to update the slot and call that.
j = probe_exprs_.size();
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++j) {
// skip non-materialized slots; we don't have evaluators instantiated for those
while (!agg_tuple_desc_->slots()[j]->is_materialized()) {
DCHECK_LT(j, agg_tuple_desc_->slots().size() - 1);
++j;
}
SlotDescriptor* slot_desc = agg_tuple_desc_->slots()[j];
AggFnEvaluator* evaluator = aggregate_evaluators_[i];
if (evaluator->is_count_star()) {
// TODO: we should be able to hoist this up to the loop over the batch and just
// increment the slot by the number of rows in the batch.
int field_idx = slot_desc->field_idx();
Value* const_one = codegen->GetIntConstant(TYPE_BIGINT, 1);
Value* slot_ptr = builder.CreateStructGEP(args[1], field_idx, "src_slot");
Value* slot_loaded = builder.CreateLoad(slot_ptr, "count_star_val");
Value* count_inc = builder.CreateAdd(slot_loaded, const_one, "count_star_inc");
builder.CreateStore(count_inc, slot_ptr);
} else {
Function* update_slot_fn = CodegenUpdateSlot(codegen, evaluator, slot_desc);
if (update_slot_fn == NULL) return NULL;
Value* fn_ctx_arg = codegen->CastPtrToLlvmPtr(
codegen->GetPtrType(FunctionContextImpl::LLVM_FUNCTIONCONTEXT_NAME),
evaluator->ctx());
builder.CreateCall3(update_slot_fn, fn_ctx_arg, args[1], args[2]);
}
}
builder.CreateRetVoid();
// CodegenProcessRowBatch() does the final optimizations.
return codegen->FinalizeFunction(fn);
}
Function* AggregationNode::CodegenProcessRowBatch(
LlvmCodeGen* codegen, Function* update_tuple_fn) {
SCOPED_TIMER(codegen->codegen_timer());
DCHECK(update_tuple_fn != NULL);
// Get the cross compiled update row batch function
IRFunction::Type ir_fn = (!probe_exprs_.empty() ?
IRFunction::AGG_NODE_PROCESS_ROW_BATCH_WITH_GROUPING :
IRFunction::AGG_NODE_PROCESS_ROW_BATCH_NO_GROUPING);
Function* process_batch_fn = codegen->GetFunction(ir_fn);
if (process_batch_fn == NULL) {
LOG(ERROR) << "Could not find AggregationNode::ProcessRowBatch in module.";
return NULL;
}
int replaced = 0;
if (!probe_exprs_.empty()) {
// Aggregation w/o grouping does not use a hash table.
// Codegen for hash
Function* hash_fn = hash_tbl_->CodegenHashCurrentRow(codegen);
if (hash_fn == NULL) return NULL;
// Codegen HashTable::Equals
Function* equals_fn = hash_tbl_->CodegenEquals(codegen);
if (equals_fn == NULL) return NULL;
// Codegen for evaluating build rows
Function* eval_build_row_fn = hash_tbl_->CodegenEvalTupleRow(codegen, true);
if (eval_build_row_fn == NULL) return NULL;
// Codegen for evaluating probe rows
Function* eval_probe_row_fn = hash_tbl_->CodegenEvalTupleRow(codegen, false);
if (eval_probe_row_fn == NULL) return NULL;
// Replace call sites
process_batch_fn = codegen->ReplaceCallSites(process_batch_fn, false,
eval_build_row_fn, "EvalBuildRow", &replaced);
DCHECK_EQ(replaced, 1);
process_batch_fn = codegen->ReplaceCallSites(process_batch_fn, false,
eval_probe_row_fn, "EvalProbeRow", &replaced);
DCHECK_EQ(replaced, 1);
process_batch_fn = codegen->ReplaceCallSites(process_batch_fn, false,
hash_fn, "HashCurrentRow", &replaced);
DCHECK_EQ(replaced, 2);
process_batch_fn = codegen->ReplaceCallSites(process_batch_fn, false,
equals_fn, "Equals", &replaced);
DCHECK_EQ(replaced, 1);
}
process_batch_fn = codegen->ReplaceCallSites(process_batch_fn, false,
update_tuple_fn, "UpdateAggTuple", &replaced);
DCHECK_EQ(replaced, 1) << "One call site should be replaced.";
DCHECK(process_batch_fn != NULL);
return codegen->OptimizeFunctionWithExprs(process_batch_fn);
}
}
| 41.321019 | 90 | 0.679841 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.