hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f58556ede8696afedb94d37d8f9a456486b89674
| 6,305
|
cpp
|
C++
|
modules/basegl/algorithm/imageconvolution.cpp
|
liu3xing3long/inviwo
|
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
|
[
"BSD-2-Clause"
] | 1
|
2018-04-07T14:30:29.000Z
|
2018-04-07T14:30:29.000Z
|
modules/basegl/algorithm/imageconvolution.cpp
|
liu3xing3long/inviwo
|
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
|
[
"BSD-2-Clause"
] | null | null | null |
modules/basegl/algorithm/imageconvolution.cpp
|
liu3xing3long/inviwo
|
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
|
[
"BSD-2-Clause"
] | null | null | null |
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2016-2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/algorithm/imageconvolution.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <modules/opengl/image/layergl.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/image/layergl.h>
#include <modules/opengl/texture/texture2d.h>
namespace inviwo {
std::shared_ptr<Image> ImageConvolution::gaussianLowpass(const Layer &layer, int kernelSize) {
float sigma =
kernelSize / (2.f * 2.576f); // 99% of samples are within +- 2.576 standard deviations
// https://de.wikipedia.org/wiki/Normalverteilung
return gaussianLowpass(layer, kernelSize, sigma);
}
std::shared_ptr<Image> ImageConvolution::gaussianLowpass(const Layer &layer, float sigma) {
int kernelSize = static_cast<int>(
sigma * 2 * 2.576); // 99% of samples are within +- 2.576 standard deviations
// https://de.wikipedia.org/wiki/Normalverteilung
return gaussianLowpass(layer, kernelSize, sigma);
}
std::shared_ptr<Image> ImageConvolution::gaussianLowpass(const Layer &layer, int kernelSize,
float sigma) {
float sigmaSq2 = 2.0f * sigma * sigma;
float a = 1.0f / (sigmaSq2 * glm::pi<float>());
float totWeight = 0;
auto kernelFunc = [&](float p) {
float w = a * std::exp(-(p * p) / sigmaSq2);
totWeight += w;
return w;
};
return convolution_separable(layer, kernelFunc, kernelSize, totWeight);
}
std::shared_ptr<Image> ImageConvolution::lowpass(const Layer &layer, int kernelSize) {
return convolution_separable(layer, [kernelSize](float /*p*/) { return 1.f; }, kernelSize,
static_cast<float>(kernelSize));
}
std::shared_ptr<Image> ImageConvolution::convolution(const Layer &layer,
std::function<float(vec2)> kernelWeight,
const float &kernelScale, ivec2 kernelSize) {
auto kernel1DSize = kernelSize.x * kernelSize.y;
if (kernel1DSize == 1) {
auto newlayer = std::make_shared<Layer>(layer);
return std::make_shared<Image>(newlayer);
}
std::vector<float> kernel(kernel1DSize);
vec2 kernelCenter(kernelSize);
kernelCenter /= 2.0f;
for (int j = 0; j < kernelSize.y; j++) {
for (int i = 0; i < kernelSize.x; i++) {
vec2 p = vec2(i, j) - kernelCenter;
kernel[i + j * kernelSize.y] = kernelWeight(p);
}
}
return convolution_internal(layer, kernelSize.x, kernelSize.y, kernel, kernelScale);
}
std::shared_ptr<Image> ImageConvolution::convolution_separable(
const Layer &layer, std::function<float(float)> kernelWeight, int kernelSize,
const float &kernelScale) {
std::vector<float> kernel(kernelSize);
float kernelCenter = (kernelSize - 1) / 2.0f;
for (int i = 0; i < kernelSize; i++) {
float p = i - kernelCenter;
kernel[i] = kernelWeight(p);
}
auto hori = convolution_internal(layer, kernelSize, 1, kernel, kernelScale);
return convolution_internal(*hori->getColorLayer(), 1, kernelSize, kernel, kernelScale);
}
std::shared_ptr<Image> ImageConvolution::convolution_internal(const Layer &layer, int kw, int kh,
const std::vector<float> &kernel,
const float &kernelScale) {
shader_.getFragmentShaderObject()->addShaderDefine("KERNELWIDTH", std::to_string(kw));
shader_.getFragmentShaderObject()->addShaderDefine("KERNELHEIGHT", std::to_string(kh));
shader_.getFragmentShaderObject()->addShaderDefine("KERNELSIZE", std::to_string(kw * kh));
shader_.build();
auto outImage = std::make_shared<Image>(std::make_shared<Layer>(
layer.getDimensions(), layer.getDataFormat(),
LayerType::Color, // always treat as color, even if picking or depth
layer.getSwizzleMask()));
TextureUnitContainer cont;
utilgl::activateTarget(*outImage);
shader_.activate();
utilgl::bindAndSetUniforms(shader_, cont, *layer.getRepresentation<LayerGL>()->getTexture(),
"tex");
shader_.setUniform("kernel", kw * kh, kernel.data());
shader_.setUniform("kernelScale", kernelScale);
shader_.setUniform("reciprocalDimensions", vec2(1) / vec2(layer.getDimensions()));
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
utilgl::deactivateCurrentTarget();
return outImage;
}
} // namespace
| 42.315436
| 98
| 0.648692
|
liu3xing3long
|
f585e7241f39e3fbbe7260ebabf3270189f1610f
| 4,627
|
cpp
|
C++
|
libs/log/example/doc/sinks_xml_file.cpp
|
HelloSunyi/boost_1_54_0
|
429fea793612f973d4b7a0e69c5af8156ae2b56e
|
[
"BSL-1.0"
] | 7
|
2015-03-03T15:45:12.000Z
|
2021-04-25T03:37:17.000Z
|
libs/log/example/doc/sinks_xml_file.cpp
|
graehl/boost
|
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
|
[
"BSL-1.0"
] | 1
|
2015-09-05T12:23:01.000Z
|
2015-09-05T12:23:01.000Z
|
libs/log/example/doc/sinks_xml_file.cpp
|
graehl/boost
|
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
|
[
"BSL-1.0"
] | 2
|
2017-07-28T17:38:16.000Z
|
2018-04-30T05:37:32.000Z
|
/*
* Copyright Andrey Semashev 2007 - 2013.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#include <stdexcept>
#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/sources/logger.hpp>
namespace logging = boost::log;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;
typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink;
//[ example_sinks_xml_file_collecting
void init_file_collecting(boost::shared_ptr< file_sink > sink)
{
sink->locked_backend()->set_file_collector(sinks::file::make_collector(
keywords::target = "logs", /*< the target directory >*/
keywords::max_size = 16 * 1024 * 1024, /*< maximum total size of the stored files, in bytes >*/
keywords::min_free_space = 100 * 1024 * 1024 /*< minimum free space on the drive, in bytes >*/
));
}
//]
#if 0
//[ example_sinks_xml_file
// Complete file sink type
typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink;
void write_header(sinks::text_file_backend::stream_type& file)
{
file << "<?xml version=\"1.0\"?>\n<log>\n";
}
void write_footer(sinks::text_file_backend::stream_type& file)
{
file << "</log>\n";
}
void init_logging()
{
// Create a text file sink
boost::shared_ptr< file_sink > sink(new file_sink(
keywords::file_name = "%Y%m%d_%H%M%S_%5N.xml", /*< the resulting file name pattern >*/
keywords::rotation_size = 16384 /*< rotation size, in characters >*/
));
sink->set_formatter
(
expr::format("\t<record id=\"%1%\" timestamp=\"%2%\">%3%</record>")
% expr::attr< unsigned int >("RecordID")
% expr::attr< boost::posix_time::ptime >("TimeStamp")
% expr::xml_decor[ expr::stream << expr::smessage ] /*< the log message has to be decorated, if it contains special characters >*/
);
// Set header and footer writing functors
sink->locked_backend()->set_open_handler(&write_header);
sink->locked_backend()->set_close_handler(&write_footer);
// Add the sink to the core
logging::core::get()->add_sink(sink);
}
//]
#endif
//[ example_sinks_xml_file_final
void init_logging()
{
// Create a text file sink
boost::shared_ptr< file_sink > sink(new file_sink(
keywords::file_name = "%Y%m%d_%H%M%S_%5N.xml",
keywords::rotation_size = 16384
));
// Set up where the rotated files will be stored
init_file_collecting(sink);
// Upon restart, scan the directory for files matching the file_name pattern
sink->locked_backend()->scan_for_files();
sink->set_formatter
(
expr::format("\t<record id=\"%1%\" timestamp=\"%2%\">%3%</record>")
% expr::attr< unsigned int >("RecordID")
% expr::attr< boost::posix_time::ptime >("TimeStamp")
% expr::xml_decor[ expr::stream << expr::smessage ]
);
// Set header and footer writing functors
namespace bll = boost::lambda;
sink->locked_backend()->set_open_handler
(
bll::_1 << "<?xml version=\"1.0\"?>\n<log>\n"
);
sink->locked_backend()->set_close_handler
(
bll::_1 << "</log>\n"
);
// Add the sink to the core
logging::core::get()->add_sink(sink);
}
//]
enum { LOG_RECORDS_TO_WRITE = 2000 };
int main(int argc, char* argv[])
{
try
{
// Initialize logging library
init_logging();
// And also add some attributes
logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock());
logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >());
// Do some logging
src::logger lg;
for (unsigned int i = 0; i < LOG_RECORDS_TO_WRITE; ++i)
{
BOOST_LOG(lg) << "XML log record " << i;
}
// Test that XML character decoration works
BOOST_LOG(lg) << "Special XML characters: &, <, >, '";
return 0;
}
catch (std::exception& e)
{
std::cout << "FAILURE: " << e.what() << std::endl;
return 1;
}
}
| 30.24183
| 153
| 0.625027
|
HelloSunyi
|
f5884bb8f6fd88d870fdbd3d009c2c38ac43f8f1
| 28,108
|
cc
|
C++
|
src/ServerConfig.cc
|
srmainwaring/ign-gazebo
|
c473a08ea3a8cc73a9fb722efb08772abcf48dfe
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/ServerConfig.cc
|
srmainwaring/ign-gazebo
|
c473a08ea3a8cc73a9fb722efb08772abcf48dfe
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/ServerConfig.cc
|
srmainwaring/ign-gazebo
|
c473a08ea3a8cc73a9fb722efb08772abcf48dfe
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "ignition/gazebo/ServerConfig.hh"
#include <tinyxml2.h>
#include <ignition/common/Console.hh>
#include <ignition/common/Filesystem.hh>
#include <ignition/common/Util.hh>
#include <ignition/fuel_tools/FuelClient.hh>
#include <ignition/fuel_tools/Result.hh>
#include <ignition/math/Rand.hh>
#include "ignition/gazebo/Util.hh"
using namespace ignition;
using namespace gazebo;
/// \brief Private data for PluginInfoConfig.
class ignition::gazebo::ServerConfig::PluginInfoPrivate
{
/// \brief Default constructor.
public: PluginInfoPrivate() = default;
/// \brief Copy constructor
/// \param[in] _info Plugin to copy.
public: explicit PluginInfoPrivate(
const std::unique_ptr<ServerConfig::PluginInfoPrivate> &_info)
: entityName(_info->entityName),
entityType(_info->entityType),
filename(_info->filename),
name(_info->name)
{
if (_info->sdf)
this->sdf = _info->sdf->Clone();
}
/// \brief Constructor based on values.
/// \param[in] _entityName Name of the entity which should receive
/// this plugin. The name is used in conjuction with _entityType to
/// uniquely identify an entity.
/// \param[in] _entityType Entity type which should receive this
/// plugin. The type is used in conjuction with _entityName to
/// uniquely identify an entity.
/// \param[in] _filename Plugin library filename.
/// \param[in] _name Name of the interface within the plugin library
/// to load.
/// \param[in] _sdf Plugin XML elements associated with this plugin.
// cppcheck-suppress passedByValue
public: PluginInfoPrivate(std::string _entityName,
// cppcheck-suppress passedByValue
std::string _entityType,
// cppcheck-suppress passedByValue
std::string _filename,
// cppcheck-suppress passedByValue
std::string _name)
: entityName(std::move(_entityName)),
entityType(std::move(_entityType)),
filename(std::move(_filename)),
name(std::move(_name))
{
}
/// \brief The name of the entity.
public: std::string entityName = "";
/// \brief The type of entity.
public: std::string entityType = "";
/// \brief _filename The plugin library.
public: std::string filename = "";
/// \brief Name of the plugin implementation.
public: std::string name = "";
/// \brief XML elements associated with this plugin
public: sdf::ElementPtr sdf = nullptr;
};
//////////////////////////////////////////////////
ServerConfig::PluginInfo::PluginInfo()
: dataPtr(new ServerConfig::PluginInfoPrivate)
{
}
//////////////////////////////////////////////////
ServerConfig::PluginInfo::~PluginInfo() = default;
//////////////////////////////////////////////////
ServerConfig::PluginInfo::PluginInfo(const std::string &_entityName,
const std::string &_entityType,
const std::string &_filename,
const std::string &_name,
const sdf::ElementPtr &_sdf)
: dataPtr(new ServerConfig::PluginInfoPrivate(_entityName, _entityType,
_filename, _name))
{
if (_sdf)
this->dataPtr->sdf = _sdf->Clone();
}
//////////////////////////////////////////////////
ServerConfig::PluginInfo::PluginInfo(const ServerConfig::PluginInfo &_info)
: dataPtr(new ServerConfig::PluginInfoPrivate(_info.dataPtr))
{
}
//////////////////////////////////////////////////
ServerConfig::PluginInfo &ServerConfig::PluginInfo::operator=(
const ServerConfig::PluginInfo &_info)
{
this->dataPtr = std::make_unique<ServerConfig::PluginInfoPrivate>(
_info.dataPtr);
return *this;
}
//////////////////////////////////////////////////
const std::string &ServerConfig::PluginInfo::EntityName() const
{
return this->dataPtr->entityName;
}
//////////////////////////////////////////////////
void ServerConfig::PluginInfo::SetEntityName(const std::string &_entityName)
{
this->dataPtr->entityName = _entityName;
}
//////////////////////////////////////////////////
const std::string &ServerConfig::PluginInfo::EntityType() const
{
return this->dataPtr->entityType;
}
//////////////////////////////////////////////////
void ServerConfig::PluginInfo::SetEntityType(const std::string &_entityType)
{
this->dataPtr->entityType = _entityType;
}
//////////////////////////////////////////////////
const std::string &ServerConfig::PluginInfo::Filename() const
{
return this->dataPtr->filename;
}
//////////////////////////////////////////////////
void ServerConfig::PluginInfo::SetFilename(const std::string &_filename)
{
this->dataPtr->filename = _filename;
}
//////////////////////////////////////////////////
const std::string &ServerConfig::PluginInfo::Name() const
{
return this->dataPtr->name;
}
//////////////////////////////////////////////////
void ServerConfig::PluginInfo::SetName(const std::string &_name)
{
this->dataPtr->name = _name;
}
//////////////////////////////////////////////////
const sdf::ElementPtr &ServerConfig::PluginInfo::Sdf() const
{
return this->dataPtr->sdf;
}
//////////////////////////////////////////////////
void ServerConfig::PluginInfo::SetSdf(const sdf::ElementPtr &_sdf)
{
if (_sdf)
this->dataPtr->sdf = _sdf->Clone();
else
this->dataPtr->sdf = nullptr;
}
/// \brief Private data for ServerConfig.
class ignition::gazebo::ServerConfigPrivate
{
/// \brief Default constructor.
public: ServerConfigPrivate()
{
std::string home;
common::env(IGN_HOMEDIR, home);
this->timestamp = IGN_SYSTEM_TIME();
// Set a default log record path
this->logRecordPath = common::joinPaths(home,
".ignition", "gazebo", "log", common::timeToIso(this->timestamp));
// If directory already exists, do not overwrite. This could potentially
// happen if multiple simulation instances are started in rapid
// succession.
if (common::exists(this->logRecordPath))
{
this->logRecordPath = common::uniqueDirectoryPath(this->logRecordPath);
}
}
/// \brief Copy constructor.
/// \param[in] _cfg Configuration to copy.
public: explicit ServerConfigPrivate(
const std::unique_ptr<ServerConfigPrivate> &_cfg)
: sdfFile(_cfg->sdfFile),
updateRate(_cfg->updateRate),
useLevels(_cfg->useLevels),
useLogRecord(_cfg->useLogRecord),
logRecordPath(_cfg->logRecordPath),
logIgnoreSdfPath(_cfg->logIgnoreSdfPath),
logPlaybackPath(_cfg->logPlaybackPath),
logRecordResources(_cfg->logRecordResources),
logRecordCompressPath(_cfg->logRecordCompressPath),
resourceCache(_cfg->resourceCache),
physicsEngine(_cfg->physicsEngine),
renderEngineServer(_cfg->renderEngineServer),
renderEngineGui(_cfg->renderEngineGui),
plugins(_cfg->plugins),
networkRole(_cfg->networkRole),
networkSecondaries(_cfg->networkSecondaries),
seed(_cfg->seed),
logRecordTopics(_cfg->logRecordTopics) { }
// \brief The SDF file that the server should load
public: std::string sdfFile = "";
// \brief The SDF string that the server should load
public: std::string sdfString = "";
/// \brief An optional update rate.
public: std::optional<double> updateRate;
/// \brief Use the level system
public: bool useLevels{false};
/// \brief Use the logging system to record states
public: bool useLogRecord{false};
/// \brief Path to place recorded states
public: std::string logRecordPath = "";
/// TODO(anyone) Deprecate in public APIs in Ignition-D, remove in Ignition-E
/// \brief Whether log record path is specified from command line
public: bool logIgnoreSdfPath{false};
/// \brief Path to recorded states to play back using logging system
public: std::string logPlaybackPath = "";
/// \brief Record meshes and material files
public: bool logRecordResources{false};
/// \brief Path to compress log files to
public: std::string logRecordCompressPath = "";
/// \brief Path to where simulation resources, such as models downloaded
/// from fuel.ignitionrobotics.org, should be stored.
public: std::string resourceCache = "";
/// \brief File containing physics engine plugin. If empty, DART will be used.
public: std::string physicsEngine = "";
/// \brief File containing render engine server plugin. If empty, OGRE2
/// will be used.
public: std::string renderEngineServer = "";
/// \brief File containing render engine gui plugin. If empty, OGRE2
/// will be used.
public: std::string renderEngineGui = "";
/// \brief List of plugins to load.
public: std::list<ServerConfig::PluginInfo> plugins;
/// \brief The network role.
public: std::string networkRole = "";
/// \brief The number of network secondaries.
public: unsigned int networkSecondaries = 0;
/// \brief The given random seed.
public: unsigned int seed = 0;
/// \brief Timestamp that marks when this ServerConfig was created.
public: std::chrono::time_point<std::chrono::system_clock> timestamp;
/// \brief Topics to record.
public: std::vector<std::string> logRecordTopics;
};
//////////////////////////////////////////////////
ServerConfig::ServerConfig()
: dataPtr(new ServerConfigPrivate)
{
}
//////////////////////////////////////////////////
ServerConfig::ServerConfig(const ServerConfig &_config)
: dataPtr(new ServerConfigPrivate(_config.dataPtr))
{
}
//////////////////////////////////////////////////
ServerConfig::~ServerConfig() = default;
//////////////////////////////////////////////////
bool ServerConfig::SetSdfFile(const std::string &_file)
{
this->dataPtr->sdfFile = _file;
this->dataPtr->sdfString = "";
return true;
}
/////////////////////////////////////////////////
std::string ServerConfig::SdfFile() const
{
return this->dataPtr->sdfFile;
}
//////////////////////////////////////////////////
bool ServerConfig::SetSdfString(const std::string &_sdfString)
{
this->dataPtr->sdfFile = "";
this->dataPtr->sdfString = _sdfString;
return true;
}
/////////////////////////////////////////////////
std::string ServerConfig::SdfString() const
{
return this->dataPtr->sdfString;
}
//////////////////////////////////////////////////
void ServerConfig::SetUpdateRate(const double &_hz)
{
if (_hz > 0)
this->dataPtr->updateRate = _hz;
}
/////////////////////////////////////////////////
std::optional<double> ServerConfig::UpdateRate() const
{
return this->dataPtr->updateRate;
}
/////////////////////////////////////////////////
std::optional<std::chrono::steady_clock::duration>
ServerConfig::UpdatePeriod() const
{
if (this->dataPtr->updateRate)
{
std::chrono::duration<double, std::ratio<1>> seconds(
1.0 / this->dataPtr->updateRate.value());
return std::chrono::duration_cast<std::chrono::nanoseconds>(seconds);
}
return std::nullopt;
}
/////////////////////////////////////////////////
bool ServerConfig::UseLevels() const
{
return this->dataPtr->useLevels;
}
/////////////////////////////////////////////////
void ServerConfig::SetUseLevels(const bool _levels)
{
this->dataPtr->useLevels = _levels;
}
/////////////////////////////////////////////////
void ServerConfig::SetNetworkSecondaries(unsigned int _secondaries)
{
this->dataPtr->networkSecondaries = _secondaries;
}
/////////////////////////////////////////////////
unsigned int ServerConfig::NetworkSecondaries() const
{
return this->dataPtr->networkSecondaries;
}
/////////////////////////////////////////////////
void ServerConfig::SetNetworkRole(const std::string &_role)
{
this->dataPtr->networkRole = _role;
}
/////////////////////////////////////////////////
std::string ServerConfig::NetworkRole() const
{
return this->dataPtr->networkRole;
}
/////////////////////////////////////////////////
bool ServerConfig::UseDistributedSimulation() const
{
// We just check that network role is not empty.
// src/network/NetworkConfig.cc checks if this value is valid.
return !this->dataPtr->networkRole.empty();
}
/////////////////////////////////////////////////
bool ServerConfig::UseLogRecord() const
{
return this->dataPtr->useLogRecord;
}
/////////////////////////////////////////////////
void ServerConfig::SetUseLogRecord(const bool _record)
{
this->dataPtr->useLogRecord = _record;
}
/////////////////////////////////////////////////
const std::string ServerConfig::LogRecordPath() const
{
return this->dataPtr->logRecordPath;
}
/////////////////////////////////////////////////
void ServerConfig::SetLogRecordPath(const std::string &_recordPath)
{
this->dataPtr->logRecordPath = _recordPath;
}
/////////////////////////////////////////////////
bool ServerConfig::LogIgnoreSdfPath() const
{
return this->dataPtr->logIgnoreSdfPath;
}
/////////////////////////////////////////////////
void ServerConfig::SetLogIgnoreSdfPath(bool _ignore)
{
this->dataPtr->logIgnoreSdfPath = _ignore;
}
/////////////////////////////////////////////////
const std::string ServerConfig::LogPlaybackPath() const
{
return this->dataPtr->logPlaybackPath;
}
/////////////////////////////////////////////////
void ServerConfig::SetLogPlaybackPath(const std::string &_playbackPath)
{
this->dataPtr->logPlaybackPath = _playbackPath;
}
/////////////////////////////////////////////////
bool ServerConfig::LogRecordResources() const
{
return this->dataPtr->logRecordResources;
}
/////////////////////////////////////////////////
void ServerConfig::SetLogRecordResources(bool _recordResources)
{
this->dataPtr->logRecordResources = _recordResources;
}
/////////////////////////////////////////////////
std::string ServerConfig::LogRecordCompressPath() const
{
return this->dataPtr->logRecordCompressPath;
}
/////////////////////////////////////////////////
void ServerConfig::SetLogRecordCompressPath(const std::string &_path)
{
this->dataPtr->logRecordCompressPath = _path;
}
/////////////////////////////////////////////////
unsigned int ServerConfig::Seed() const
{
return this->dataPtr->seed;
}
/////////////////////////////////////////////////
void ServerConfig::SetSeed(unsigned int _seed)
{
this->dataPtr->seed = _seed;
ignition::math::Rand::Seed(_seed);
}
/////////////////////////////////////////////////
const std::string &ServerConfig::ResourceCache() const
{
return this->dataPtr->resourceCache;
}
/////////////////////////////////////////////////
void ServerConfig::SetResourceCache(const std::string &_path)
{
this->dataPtr->resourceCache = _path;
}
/////////////////////////////////////////////////
const std::string &ServerConfig::PhysicsEngine() const
{
return this->dataPtr->physicsEngine;
}
/////////////////////////////////////////////////
void ServerConfig::SetPhysicsEngine(const std::string &_physicsEngine)
{
this->dataPtr->physicsEngine = _physicsEngine;
}
/////////////////////////////////////////////////
const std::string &ServerConfig::RenderEngineServer() const
{
return this->dataPtr->renderEngineServer;
}
/////////////////////////////////////////////////
void ServerConfig::SetRenderEngineServer(const std::string &_renderEngineServer)
{
this->dataPtr->renderEngineServer = _renderEngineServer;
}
/////////////////////////////////////////////////
const std::string &ServerConfig::RenderEngineGui() const
{
return this->dataPtr->renderEngineGui;
}
/////////////////////////////////////////////////
void ServerConfig::SetRenderEngineGui(const std::string &_renderEngineGui)
{
this->dataPtr->renderEngineGui = _renderEngineGui;
}
/////////////////////////////////////////////////
void ServerConfig::AddPlugin(const ServerConfig::PluginInfo &_info)
{
this->dataPtr->plugins.push_back(_info);
}
/////////////////////////////////////////////////
ServerConfig::PluginInfo
ServerConfig::LogPlaybackPlugin() const
{
auto entityName = "*";
auto entityType = "world";
auto pluginName = "ignition::gazebo::systems::LogPlayback";
auto pluginFilename = "ignition-gazebo-log-system";
sdf::ElementPtr playbackElem;
playbackElem = std::make_shared<sdf::Element>();
playbackElem->SetName("plugin");
if (!this->LogPlaybackPath().empty())
{
sdf::ElementPtr pathElem = std::make_shared<sdf::Element>();
pathElem->SetName("playback_path");
playbackElem->AddElementDescription(pathElem);
pathElem = playbackElem->GetElement("playback_path");
pathElem->AddValue("string", "", false, "");
pathElem->Set<std::string>(this->LogPlaybackPath());
}
return ServerConfig::PluginInfo(entityName,
entityType,
pluginFilename,
pluginName,
playbackElem);
}
/////////////////////////////////////////////////
ServerConfig::PluginInfo
ServerConfig::LogRecordPlugin() const
{
auto entityName = "*";
auto entityType = "world";
auto pluginName = "ignition::gazebo::systems::LogRecord";
auto pluginFilename = "ignition-gazebo-log-system";
sdf::ElementPtr recordElem;
recordElem = std::make_shared<sdf::Element>();
recordElem->SetName("plugin");
igndbg << "Generating LogRecord SDF:" << std::endl;
if (!this->LogRecordPath().empty())
{
sdf::ElementPtr pathElem = std::make_shared<sdf::Element>();
pathElem->SetName("record_path");
recordElem->AddElementDescription(pathElem);
pathElem = recordElem->GetElement("record_path");
pathElem->AddValue("string", "", false, "");
pathElem->Set<std::string>(this->LogRecordPath());
}
// Set whether to record resources
sdf::ElementPtr resourceElem = std::make_shared<sdf::Element>();
resourceElem->SetName("record_resources");
recordElem->AddElementDescription(resourceElem);
resourceElem = recordElem->GetElement("record_resources");
resourceElem->AddValue("bool", "false", false, "");
resourceElem->Set<bool>(this->LogRecordResources() ? true : false);
if (!this->LogRecordCompressPath().empty())
{
// Set whether to compress
sdf::ElementPtr compressElem = std::make_shared<sdf::Element>();
compressElem->SetName("compress");
recordElem->AddElementDescription(compressElem);
compressElem = recordElem->GetElement("compress");
compressElem->AddValue("bool", "false", false, "");
compressElem->Set<bool>(true);
// Set compress path
sdf::ElementPtr cPathElem = std::make_shared<sdf::Element>();
cPathElem->SetName("compress_path");
recordElem->AddElementDescription(cPathElem);
cPathElem = recordElem->GetElement("compress_path");
cPathElem->AddValue("string", "", false, "");
cPathElem->Set<std::string>(this->LogRecordCompressPath());
}
// If record topics specified, add in SDF
for (const std::string &topic : this->LogRecordTopics())
{
sdf::ElementPtr topicElem = std::make_shared<sdf::Element>();
topicElem->SetName("record_topic");
recordElem->AddElementDescription(topicElem);
topicElem = recordElem->AddElement("record_topic");
topicElem->AddValue("string", "false", false, "");
topicElem->Set<std::string>(topic);
}
igndbg << recordElem->ToString("") << std::endl;
return ServerConfig::PluginInfo(entityName,
entityType,
pluginFilename,
pluginName,
recordElem);
}
/////////////////////////////////////////////////
const std::list<ServerConfig::PluginInfo> &ServerConfig::Plugins() const
{
return this->dataPtr->plugins;
}
/////////////////////////////////////////////////
ServerConfig &ServerConfig::operator=(const ServerConfig &_cfg)
{
this->dataPtr = std::make_unique<ServerConfigPrivate>(_cfg.dataPtr);
return *this;
}
/////////////////////////////////////////////////
const std::chrono::time_point<std::chrono::system_clock> &
ServerConfig::Timestamp() const
{
return this->dataPtr->timestamp;
}
/////////////////////////////////////////////////
void ServerConfig::AddLogRecordTopic(const std::string &_topic)
{
this->dataPtr->logRecordTopics.push_back(_topic);
}
/////////////////////////////////////////////////
void ServerConfig::ClearLogRecordTopics()
{
this->dataPtr->logRecordTopics.clear();
}
/////////////////////////////////////////////////
const std::vector<std::string> &ServerConfig::LogRecordTopics() const
{
return this->dataPtr->logRecordTopics;
}
/////////////////////////////////////////////////
void copyElement(sdf::ElementPtr _sdf, const tinyxml2::XMLElement *_xml)
{
_sdf->SetName(_xml->Value());
if (_xml->GetText() != nullptr)
_sdf->AddValue("string", _xml->GetText(), "1");
for (const tinyxml2::XMLAttribute *attribute = _xml->FirstAttribute();
attribute; attribute = attribute->Next())
{
_sdf->AddAttribute(attribute->Name(), "string", "", 1, "");
_sdf->GetAttribute(attribute->Name())->SetFromString(
attribute->Value());
}
// Iterate over all the child elements
const tinyxml2::XMLElement *elemXml = nullptr;
for (elemXml = _xml->FirstChildElement(); elemXml;
elemXml = elemXml->NextSiblingElement())
{
sdf::ElementPtr element(new sdf::Element);
element->SetParent(_sdf);
copyElement(element, elemXml);
_sdf->InsertElement(element);
}
}
/////////////////////////////////////////////////
std::list<ServerConfig::PluginInfo>
parsePluginsFromDoc(const tinyxml2::XMLDocument &_doc)
{
auto ret = std::list<ServerConfig::PluginInfo>();
auto root = _doc.RootElement();
if (root == nullptr)
{
ignerr << "No <server_config> element found when parsing plugins\n";
return ret;
}
auto plugins = root->FirstChildElement("plugins");
if (plugins == nullptr)
{
ignerr << "No <plugins> element found when parsing plugins\n";
return ret;
}
const tinyxml2::XMLElement *elem{nullptr};
// Note, this was taken from ign-launch, where this type of parsing happens.
// Process all the plugins.
for (elem = plugins->FirstChildElement("plugin"); elem;
elem = elem->NextSiblingElement("plugin"))
{
// Get the plugin's name
const char *nameStr = elem->Attribute("name");
std::string name = nameStr == nullptr ? "" : nameStr;
if (name.empty())
{
ignerr << "Plugin is missing the name attribute. "
<< "Skipping this plugin.\n";
continue;
}
// Get the plugin's filename
const char *fileStr = elem->Attribute("filename");
std::string file = fileStr == nullptr ? "" : fileStr;
if (file.empty())
{
ignerr << "A Plugin with name[" << name << "] is "
<< "missing the filename attribute. Skipping this plugin.\n";
continue;
}
// Get the plugin's entity name attachment information.
const char *entityNameStr = elem->Attribute("entity_name");
std::string entityName = entityNameStr == nullptr ? "" : entityNameStr;
if (entityName.empty())
{
ignerr << "A Plugin with name[" << name << "] and "
<< "filename[" << file << "] is missing the entity_name attribute. "
<< "Skipping this plugin.\n";
continue;
}
// Get the plugin's entity type attachment information.
const char *entityTypeStr = elem->Attribute("entity_type");
std::string entityType = entityTypeStr == nullptr ? "" : entityTypeStr;
if (entityType.empty())
{
ignerr << "A Plugin with name[" << name << "] and "
<< "filename[" << file << "] is missing the entity_type attribute. "
<< "Skipping this plugin.\n";
continue;
}
// Create an SDF element of the plugin
sdf::ElementPtr sdf(new sdf::Element);
copyElement(sdf, elem);
// Add the plugin to the server config
ret.push_back({entityName, entityType, file, name, sdf});
}
return ret;
}
/////////////////////////////////////////////////
std::list<ServerConfig::PluginInfo>
ignition::gazebo::parsePluginsFromFile(const std::string &_fname)
{
tinyxml2::XMLDocument doc;
doc.LoadFile(_fname.c_str());
return parsePluginsFromDoc(doc);
}
/////////////////////////////////////////////////
std::list<ServerConfig::PluginInfo>
ignition::gazebo::parsePluginsFromString(const std::string &_str)
{
tinyxml2::XMLDocument doc;
doc.Parse(_str.c_str());
return parsePluginsFromDoc(doc);
}
/////////////////////////////////////////////////
std::list<ServerConfig::PluginInfo>
ignition::gazebo::loadPluginInfo(bool _isPlayback)
{
std::list<ServerConfig::PluginInfo> ret;
// 1. Check contents of environment variable
std::string envConfig;
bool configSet = ignition::common::env(gazebo::kServerConfigPathEnv,
envConfig,
true);
if (configSet)
{
if (ignition::common::exists(envConfig))
{
// Parse configuration stored in environment variable
ret = ignition::gazebo::parsePluginsFromFile(envConfig);
if (ret.empty())
{
// This may be desired behavior, but warn just in case.
// Some users may want to defer all loading until later
// during runtime.
ignwarn << gazebo::kServerConfigPathEnv
<< " set but no plugins found\n";
}
igndbg << "Loaded (" << ret.size() << ") plugins from file " <<
"[" << envConfig << "]\n";
return ret;
}
else
{
// This may be desired behavior, but warn just in case.
// Some users may want to defer all loading until late
// during runtime.
ignwarn << gazebo::kServerConfigPathEnv
<< " set but no file found,"
<< " no plugins loaded\n";
return ret;
}
}
std::string configFilename;
if (_isPlayback)
{
configFilename = "playback_server.config";
}
else
{
configFilename = "server.config";
}
std::string defaultConfigDir;
ignition::common::env(IGN_HOMEDIR, defaultConfigDir);
defaultConfigDir = ignition::common::joinPaths(defaultConfigDir, ".ignition",
"gazebo");
auto defaultConfig = ignition::common::joinPaths(defaultConfigDir,
configFilename);
if (!ignition::common::exists(defaultConfig))
{
auto installedConfig = ignition::common::joinPaths(
IGNITION_GAZEBO_SERVER_CONFIG_PATH,
configFilename);
if (!ignition::common::createDirectories(defaultConfigDir))
{
ignerr << "Failed to create directory [" << defaultConfigDir
<< "]." << std::endl;
return ret;
}
if (!ignition::common::exists(installedConfig))
{
ignerr << "Failed to copy installed config [" << installedConfig
<< "] to default config [" << defaultConfig << "]."
<< "(file " << installedConfig << " doesn't exist)"
<< std::endl;
return ret;
}
else if (!ignition::common::copyFile(installedConfig, defaultConfig))
{
ignerr << "Failed to copy installed config [" << installedConfig
<< "] to default config [" << defaultConfig << "]."
<< std::endl;
return ret;
}
else
{
ignmsg << "Copied installed config [" << installedConfig
<< "] to default config [" << defaultConfig << "]."
<< std::endl;
}
}
ret = ignition::gazebo::parsePluginsFromFile(defaultConfig);
if (ret.empty())
{
// This may be desired behavior, but warn just in case.
ignwarn << "Loaded config: [" << defaultConfig
<< "], but no plugins found\n";
}
igndbg << "Loaded (" << ret.size() << ") plugins from file " <<
"[" << defaultConfig << "]\n";
return ret;
}
| 29.997866
| 80
| 0.59773
|
srmainwaring
|
f588fba044454b25731d2a5babd568d573654fda
| 12,610
|
cpp
|
C++
|
src/perception/segmentation/ground_truth_detections/test/test_ground_truth_detections_node.cpp
|
ruvus/auto
|
25ae62d6e575cae40212356eed43ec3e76e9a13e
|
[
"Apache-2.0"
] | 1
|
2022-02-24T07:36:59.000Z
|
2022-02-24T07:36:59.000Z
|
src/perception/segmentation/ground_truth_detections/test/test_ground_truth_detections_node.cpp
|
ruvus/auto
|
25ae62d6e575cae40212356eed43ec3e76e9a13e
|
[
"Apache-2.0"
] | null | null | null |
src/perception/segmentation/ground_truth_detections/test/test_ground_truth_detections_node.cpp
|
ruvus/auto
|
25ae62d6e575cae40212356eed43ec3e76e9a13e
|
[
"Apache-2.0"
] | 1
|
2021-12-09T15:44:10.000Z
|
2021-12-09T15:44:10.000Z
|
// Copyright 2021 The Autoware Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Co-developed by Tier IV, Inc. and Apex.AI, Inc.
#include <ground_truth_detections/ground_truth_detections_node.hpp>
#include <geometry_msgs/msg/vector3.hpp>
#include <fake_test_node/fake_test_node.hpp>
#include <math.h>
#include <memory>
#include "gtest/gtest.h"
namespace
{
using autoware::ground_truth_detections::GroundTruthDetectionsNode;
using autoware_auto_perception_msgs::msg::ClassifiedRoiArray;
using autoware_auto_perception_msgs::msg::DetectedObjects;
using geometry_msgs::msg::Vector3;
using lgsvl_msgs::msg::Detection2DArray;
using lgsvl_msgs::msg::Detection2D;
using lgsvl_msgs::msg::Detection3DArray;
using lgsvl_msgs::msg::Detection3D;
using GroundTruth2dDetectionsTest = autoware::tools::testing::FakeTestNode;
using GroundTruth3dDetectionsTest = autoware::tools::testing::FakeTestNode;
using namespace std::chrono_literals;
static constexpr float_t CAR_CENTER_X = 15.3F;
static constexpr float_t CAR_CENTER_Y = 17.4F;
static constexpr float_t CAR_BBOX_HEIGHT = 5.2F;
static constexpr float_t CAR_BBOX_WIDTH = 2.7F;
static constexpr double_t CAR_CENTER_3D_X = CAR_CENTER_X;
static constexpr double_t CAR_CENTER_3D_Y = CAR_CENTER_Y;
static constexpr double_t CAR_CENTER_3D_Z = 9.9F;
// unit quaternion representing a rotation of 61.1° around an axis (-0.14, 0.16, 0.98)
static constexpr double_t CAR_ORIENTATION_X = -0.0696078;
static constexpr double_t CAR_ORIENTATION_Y = 0.0795518;
static constexpr double_t CAR_ORIENTATION_Z = 0.497199;
static constexpr double_t CAR_ORIENTATION_W = 0.861173;
static constexpr float_t CAR_BBOX_3D_HEIGHT = 2.1F;
static constexpr float_t CAR_BBOX_3D_LENGTH = 4.8F;
static constexpr float_t CAR_BBOX_3D_WIDTH = 2.15F;
static constexpr double_t CAR_TWIST_LINEAR_X = 2.0F;
static constexpr double_t CAR_TWIST_LINEAR_Y = 2.3F;
static constexpr double_t CAR_TWIST_LINEAR_Z = 2.5F;
// One detection for each supported label + one detection with unsupported label
Detection2DArray make_sample_detections_2d()
{
Detection2DArray detections;
detections.header.stamp.sec = 24;
detections.header.stamp.nanosec = 8723U;
const auto add_detection = [&detections](const char * label) -> Detection2D & {
detections.detections.emplace_back(detections.detections.back());
auto & d = detections.detections.back();
d.label = label;
++d.id;
return d;
};
{
Detection2D d;
d.label = "Hatchback";
d.header = detections.header;
d.bbox.x = CAR_CENTER_X;
d.bbox.y = CAR_CENTER_Y;
d.bbox.height = CAR_BBOX_HEIGHT;
d.bbox.width = CAR_BBOX_WIDTH;
d.id = 0;
d.score = 1.0F;
d.velocity.linear = geometry_msgs::build<Vector3>()
.x(CAR_TWIST_LINEAR_X)
.y(CAR_TWIST_LINEAR_Y)
.z(CAR_TWIST_LINEAR_Z);
detections.detections.emplace_back(d);
}
add_detection("Jeep");
add_detection("Sedan");
add_detection("SUV");
add_detection("BoxTruck");
// add a position that would give rise to a lower-left corner just outside the allowed
// range if half of the width (or height) were subtracted
{
Detection2D & d = add_detection("Pedestrian");
d.bbox.x = 5.0F;
d.bbox.width = 10.00003F;
d.bbox.y = 6.0F;
d.bbox.height = 12.00002F;
}
add_detection("Unsupported_label");
return detections;
}
// cppcheck-suppress syntaxError
TEST_F(GroundTruth2dDetectionsTest, ReceiveDetections)
{
rclcpp::NodeOptions options{};
const auto node = std::make_shared<GroundTruthDetectionsNode>(options);
ClassifiedRoiArray::SharedPtr last_received_msg{};
const auto input_topic = "/simulator/ground_truth/detections2D";
const auto output_topic = "/perception/ground_truth_detections_2d";
auto fake_publisher = create_publisher<Detection2DArray>(input_topic, 1s);
auto result_subscription = create_subscription<ClassifiedRoiArray>(
output_topic, *node, //
[&last_received_msg](
const ClassifiedRoiArray::SharedPtr msg) {
last_received_msg = msg;
});
Detection2DArray input_msg = make_sample_detections_2d();
const auto dt{100ms};
const auto max_wait_time{std::chrono::seconds{1LL}};
auto time_passed{std::chrono::milliseconds{0LL}};
while (!last_received_msg) {
fake_publisher->publish(input_msg);
rclcpp::spin_some(node);
rclcpp::spin_some(get_fake_node());
std::this_thread::sleep_for(dt);
time_passed += dt;
if (time_passed > max_wait_time) {
FAIL() << "Did not receive a message soon enough.";
}
}
ASSERT_TRUE(last_received_msg);
ASSERT_EQ(last_received_msg->rois.size(), input_msg.detections.size());
const auto & car_detection = last_received_msg->rois.front();
ASSERT_EQ(car_detection.classifications.size(), 1U);
EXPECT_FLOAT_EQ(car_detection.classifications.front().probability, 1.0);
EXPECT_EQ(
car_detection.classifications.front().classification,
autoware_auto_perception_msgs::msg::ObjectClassification::CAR);
ASSERT_EQ(car_detection.polygon.points.size(), 4U);
{
const auto & lower_left = car_detection.polygon.points[0];
EXPECT_FLOAT_EQ(lower_left.x, CAR_CENTER_X - 0.5F * CAR_BBOX_WIDTH);
EXPECT_FLOAT_EQ(lower_left.y, CAR_CENTER_Y - 0.5F * CAR_BBOX_HEIGHT);
EXPECT_EQ(lower_left.z, 0.0F);
const auto & lower_right = car_detection.polygon.points[1];
EXPECT_FLOAT_EQ(lower_right.x, CAR_CENTER_X + 0.5F * CAR_BBOX_WIDTH);
EXPECT_FLOAT_EQ(lower_right.y, CAR_CENTER_Y - 0.5F * CAR_BBOX_HEIGHT);
EXPECT_EQ(lower_right.z, 0.0F);
const auto & upper_right = car_detection.polygon.points[2];
EXPECT_FLOAT_EQ(upper_right.x, CAR_CENTER_X + 0.5F * CAR_BBOX_WIDTH);
EXPECT_FLOAT_EQ(upper_right.y, CAR_CENTER_Y + 0.5F * CAR_BBOX_HEIGHT);
EXPECT_EQ(upper_right.z, 0.0F);
const auto & upper_left = car_detection.polygon.points[3];
EXPECT_FLOAT_EQ(upper_left.x, CAR_CENTER_X - 0.5F * CAR_BBOX_WIDTH);
EXPECT_FLOAT_EQ(upper_left.y, CAR_CENTER_Y + 0.5F * CAR_BBOX_HEIGHT);
EXPECT_EQ(upper_left.z, 0.0F);
}
static constexpr size_t N_CARS = 4;
for (size_t i = 1U; i < N_CARS; ++i) {
const auto & other_car_roi = last_received_msg->rois[i];
EXPECT_EQ(other_car_roi.classifications, car_detection.classifications);
EXPECT_EQ(other_car_roi.polygon, car_detection.polygon);
}
{
const auto & truck_roi = last_received_msg->rois[N_CARS];
EXPECT_EQ(
truck_roi.classifications.at(0).classification,
autoware_auto_perception_msgs::msg::ObjectClassification::TRUCK);
EXPECT_EQ(truck_roi.polygon, car_detection.polygon);
}
const auto & pedestrian_roi = *(last_received_msg->rois.rbegin() + 1);
{
EXPECT_EQ(
pedestrian_roi.classifications.at(0).classification,
autoware_auto_perception_msgs::msg::ObjectClassification::PEDESTRIAN);
EXPECT_NE(pedestrian_roi.polygon, car_detection.polygon);
// check clipping to non-negative values
const auto & lower_left = pedestrian_roi.polygon.points.at(0);
EXPECT_EQ(lower_left.x, 0.0F);
EXPECT_EQ(lower_left.y, 0.0F);
}
{
const auto & unknown_roi = last_received_msg->rois.back();
EXPECT_EQ(
unknown_roi.classifications.at(0).classification,
autoware_auto_perception_msgs::msg::ObjectClassification::UNKNOWN);
EXPECT_EQ(unknown_roi.polygon, pedestrian_roi.polygon);
}
}
Detection3DArray make_sample_detections_3d()
{
Detection3DArray detections;
detections.header.stamp.sec = 24;
detections.header.stamp.nanosec = 8723U;
{
Detection3D d;
d.header = detections.header;
d.id = 14224;
d.label = "Hatchback";
d.score = 1.0F;
d.bbox.position.position.x = CAR_CENTER_3D_X;
d.bbox.position.position.y = CAR_CENTER_3D_Y;
d.bbox.position.position.z = CAR_CENTER_3D_Z;
d.bbox.position.orientation.x = CAR_ORIENTATION_X;
d.bbox.position.orientation.y = CAR_ORIENTATION_Y;
d.bbox.position.orientation.z = CAR_ORIENTATION_Z;
d.bbox.position.orientation.w = CAR_ORIENTATION_W;
d.bbox.size.x = CAR_BBOX_3D_LENGTH;
d.bbox.size.y = CAR_BBOX_3D_WIDTH;
d.bbox.size.z = CAR_BBOX_3D_HEIGHT;
d.velocity.linear = geometry_msgs::build<Vector3>()
.x(CAR_TWIST_LINEAR_X)
.y(CAR_TWIST_LINEAR_Y)
.z(CAR_TWIST_LINEAR_Z);
detections.detections.emplace_back(d);
}
return detections;
}
TEST_F(GroundTruth3dDetectionsTest, ReceiveDetections)
{
rclcpp::NodeOptions options{};
const auto node = std::make_shared<GroundTruthDetectionsNode>(options);
DetectedObjects::SharedPtr last_received_msg{};
const auto input_topic = "/simulator/ground_truth/detections3D";
const auto output_topic = "/perception/ground_truth_detections_3d";
auto fake_publisher = create_publisher<Detection3DArray>(input_topic, 1s);
auto result_subscription = create_subscription<DetectedObjects>(
output_topic, *node, //
[&last_received_msg](
const DetectedObjects::SharedPtr msg) {
last_received_msg = msg;
});
Detection3DArray input_msg = make_sample_detections_3d();
const auto dt{100ms};
const auto max_wait_time{std::chrono::seconds{1LL}};
auto time_passed{std::chrono::milliseconds{0LL}};
while (!last_received_msg) {
fake_publisher->publish(input_msg);
rclcpp::spin_some(node);
rclcpp::spin_some(get_fake_node());
std::this_thread::sleep_for(dt);
time_passed += dt;
if (time_passed > max_wait_time) {
FAIL() << "Did not receive a message soon enough.";
}
}
ASSERT_TRUE(last_received_msg);
ASSERT_EQ(last_received_msg->objects.size(), input_msg.detections.size());
const auto & car_detection = last_received_msg->objects.front();
ASSERT_EQ(car_detection.existence_probability, 1.0F);
// classification
{
ASSERT_EQ(car_detection.classification.size(), 1U);
EXPECT_FLOAT_EQ(car_detection.classification.front().probability, 1.0);
EXPECT_EQ(
car_detection.classification.front().classification,
autoware_auto_perception_msgs::msg::ObjectClassification::CAR);
}
// kinematics
{
const auto & k = car_detection.kinematics;
EXPECT_EQ(k.pose_with_covariance.pose.position.x, CAR_CENTER_3D_X);
EXPECT_EQ(k.pose_with_covariance.pose.position.y, CAR_CENTER_3D_Y);
EXPECT_EQ(k.pose_with_covariance.pose.position.z, CAR_CENTER_3D_Z);
EXPECT_FALSE(k.has_position_covariance);
ASSERT_EQ(
k.orientation_availability,
autoware_auto_perception_msgs::msg::DetectedObjectKinematics::AVAILABLE);
EXPECT_EQ(k.pose_with_covariance.pose.orientation.x, CAR_ORIENTATION_X);
EXPECT_EQ(k.pose_with_covariance.pose.orientation.y, CAR_ORIENTATION_Y);
EXPECT_EQ(k.pose_with_covariance.pose.orientation.z, CAR_ORIENTATION_Z);
EXPECT_EQ(k.pose_with_covariance.pose.orientation.w, CAR_ORIENTATION_W);
}
// shape
{
const auto & s = car_detection.shape;
EXPECT_EQ(s.height, CAR_BBOX_3D_HEIGHT);
ASSERT_EQ(s.polygon.points.size(), 4UL);
// contract: all corners have zero z value
for (size_t i = 1; i < 4; ++i) {
EXPECT_EQ(s.polygon.points[i].z, 0.0F) << i;
}
{
const auto & rear_left_corner = s.polygon.points[0];
EXPECT_FLOAT_EQ(rear_left_corner.x, -0.5F * CAR_BBOX_3D_LENGTH);
EXPECT_FLOAT_EQ(rear_left_corner.y, -0.5F * CAR_BBOX_3D_WIDTH);
}
{
const auto & rear_right_corner = s.polygon.points[1];
EXPECT_FLOAT_EQ(rear_right_corner.x, -0.5F * CAR_BBOX_3D_LENGTH);
EXPECT_FLOAT_EQ(rear_right_corner.y, +0.5F * CAR_BBOX_3D_WIDTH);
}
{
const auto & front_right_corner = s.polygon.points[2];
EXPECT_FLOAT_EQ(front_right_corner.x, +0.5F * CAR_BBOX_3D_LENGTH);
EXPECT_FLOAT_EQ(front_right_corner.y, +0.5F * CAR_BBOX_3D_WIDTH);
}
{
const auto & front_left_corner = s.polygon.points[3];
EXPECT_FLOAT_EQ(front_left_corner.x, +0.5F * CAR_BBOX_3D_LENGTH);
EXPECT_FLOAT_EQ(front_left_corner.y, -0.5F * CAR_BBOX_3D_WIDTH);
}
}
}
} // namespace
| 33.806971
| 92
| 0.727201
|
ruvus
|
f58b8b8ed78ab4e2e8a07025bb0b54ddc60bd931
| 1,349
|
cpp
|
C++
|
CO1028/LAB7/Ex4/main.cpp
|
Smithienious/hcmut-192
|
4f1dfa322321fc18d151835213a5b544c9d764f2
|
[
"MIT"
] | null | null | null |
CO1028/LAB7/Ex4/main.cpp
|
Smithienious/hcmut-192
|
4f1dfa322321fc18d151835213a5b544c9d764f2
|
[
"MIT"
] | null | null | null |
CO1028/LAB7/Ex4/main.cpp
|
Smithienious/hcmut-192
|
4f1dfa322321fc18d151835213a5b544c9d764f2
|
[
"MIT"
] | 1
|
2020-04-26T10:28:41.000Z
|
2020-04-26T10:28:41.000Z
|
#include <iostream>
#include <fstream>
using namespace std;
ifstream ifs;
struct node
{
int data;
node *next;
};
node *createLinkList(int n)
{
node *head = new node;
node *current = head;
int dat = 0;
for (int i = 0; i < n; i += 1)
{
ifs >> dat;
current->data = dat;
if (i != n - 1)
{
node *next = new node;
current->next = next;
current = next;
}
else
current->next = nullptr;
}
return head;
}
bool isEqual(node *head1, node *head2)
{
node *current1 = head1, *current2 = head2;
int result = 1, num1 = 0, num2 = 0;
while (current1 != nullptr)
{
num1 += 1;
current1 = current1->next;
}
while (current2 != nullptr)
{
num2 += 1;
current2 = current2->next;
}
if (num1 != num2)
result = 0;
current1 = head1;
current2 = head2;
while (result && current1 != nullptr && current2 != nullptr)
{
if (current1->data != current2->data)
result = 0;
current1 = current1->next;
current2 = current2->next;
}
return result;
}
int main(int argc, char **argv)
{
ifs.open(argv[1]);
int n = 0;
ifs >> n;
if (n <= 0)
{
cout << "Invalid n" << endl;
return 0;
}
node *head1 = createLinkList(n);
int m = 0;
ifs >> m;
if (m <= 0)
{
cout << "Invalid m" << endl;
return 0;
}
node *head2 = createLinkList(m);
cout << isEqual(head1, head2) << endl;
ifs.close();
return 0;
}
| 14.052083
| 61
| 0.58043
|
Smithienious
|
f58bc06edf3f00bb3c33dd86ab1d5c698dfb2179
| 740
|
cc
|
C++
|
src/lidar_sim/apps/glMapEditor.cc
|
Enigmatisms/LiDARSim2D
|
92992c281672ae8892ce9355bf1e417ea6cf706c
|
[
"BSD-3-Clause"
] | 5
|
2021-10-17T00:55:24.000Z
|
2022-03-29T05:59:49.000Z
|
src/lidar_sim/apps/glMapEditor.cc
|
Enigmatisms/ParticleFilter
|
92992c281672ae8892ce9355bf1e417ea6cf706c
|
[
"BSD-3-Clause"
] | null | null | null |
src/lidar_sim/apps/glMapEditor.cc
|
Enigmatisms/ParticleFilter
|
92992c281672ae8892ce9355bf1e417ea6cf706c
|
[
"BSD-3-Clause"
] | null | null | null |
#include "gl/viewer.hpp"
#include "gl/glMap.h"
#include "utils/mapEdit.h"
void makeMapBorder(Walls& walls) {
Wall border;
border.emplace_back(1200, 0, 0);
border.emplace_back(0, 0, 0);
border.emplace_back(0, 900, 0);
border.emplace_back(1200, 900, 0);
border.emplace_back(30, 30, 0);
border.emplace_back(1170, 30, 0);
border.emplace_back(1170, 870, 0);
border.emplace_back(30, 870, 0);
walls.push_back(border);
}
int main(int argc, char* argv[]) {
Walls walls;
mapLoad("/home/sentinel/ParticleFilter/maps/standard3.txt", walls);
// makeMapBorder(walls);
wall_ptr = std::unique_ptr<Walls>(&walls);
printf("Size: %lu\n", wall_ptr->size());
viewer(argc, argv);
return 0;
}
| 27.407407
| 71
| 0.652703
|
Enigmatisms
|
f58c2231face6a37661e160650d6ee2b4e7ebb5f
| 7,960
|
cpp
|
C++
|
driver_files/src/Driver/HMDDevice.cpp
|
justinliang1020/AirPose
|
e651883f0e9c33fee0d7180d118b2456d54705e4
|
[
"MIT"
] | 28
|
2021-06-15T21:06:01.000Z
|
2022-03-31T02:20:25.000Z
|
driver_files/src/Driver/HMDDevice.cpp
|
gergelyszaz/AirPose
|
9ba902b29aeaae6aa0eed4fdb4d7ea63014d546e
|
[
"MIT"
] | 16
|
2021-10-30T21:24:31.000Z
|
2021-11-21T15:12:08.000Z
|
driver_files/src/Driver/HMDDevice.cpp
|
gergelyszaz/AirPose
|
9ba902b29aeaae6aa0eed4fdb4d7ea63014d546e
|
[
"MIT"
] | 2
|
2021-09-10T13:15:15.000Z
|
2022-01-16T01:51:21.000Z
|
#include "HMDDevice.hpp"
#include <Windows.h>
PoseVRDriver::HMDDevice::HMDDevice(std::string serial):serial_(serial)
{
}
std::string PoseVRDriver::HMDDevice::GetSerial()
{
return this->serial_;
}
void PoseVRDriver::HMDDevice::Update()
{
if (this->device_index_ == vr::k_unTrackedDeviceIndexInvalid)
return;
// Setup pose for this frame
auto pose = IVRDevice::MakeDefaultPose();
float delta_seconds = GetDriver()->GetLastFrameTime().count() / 1000.0f;
// Get orientation
this->rot_y_ += (1.0f * (GetAsyncKeyState(VK_RIGHT) == 0) - 1.0f * (GetAsyncKeyState(VK_LEFT) == 0)) * delta_seconds;
this->rot_x_ += (-1.0f * (GetAsyncKeyState(VK_UP) == 0) + 1.0f * (GetAsyncKeyState(VK_DOWN) == 0)) * delta_seconds;
this->rot_x_ = std::fmax(this->rot_x_, -3.14159f/2);
this->rot_x_ = std::fmin(this->rot_x_, 3.14159f/2);
linalg::vec<float, 4> y_quat{ 0, std::sinf(this->rot_y_ / 2), 0, std::cosf(this->rot_y_ / 2) };
linalg::vec<float, 4> x_quat{ std::sinf(this->rot_x_ / 2), 0, 0, std::cosf(this->rot_x_ / 2) };
linalg::vec<float, 4> pose_rot = linalg::qmul(y_quat, x_quat);
pose.qRotation.w = (float) pose_rot.w;
pose.qRotation.x = (float) pose_rot.x;
pose.qRotation.y = (float) pose_rot.y;
pose.qRotation.z = (float) pose_rot.z;
// Update position based on rotation
linalg::vec<float, 3> forward_vec{-1.0f * (GetAsyncKeyState(0x44) == 0) + 1.0f * (GetAsyncKeyState(0x41) == 0), 0, 0};
linalg::vec<float, 3> right_vec{0, 0, 1.0f * (GetAsyncKeyState(0x57) == 0) - 1.0f * (GetAsyncKeyState(0x53) == 0) };
linalg::vec<float, 3> final_dir = forward_vec + right_vec;
if (linalg::length(final_dir) > 0.01) {
final_dir = linalg::normalize(final_dir) * (float)delta_seconds;
final_dir = linalg::qrot(pose_rot, final_dir);
this->pos_x_ += final_dir.x;
this->pos_y_ += final_dir.y;
this->pos_z_ += final_dir.z;
}
pose.vecPosition[0] = (float) this->pos_x_;
pose.vecPosition[1] = (float) this->pos_y_;
pose.vecPosition[2] = (float) this->pos_z_;
// Post pose
GetDriver()->GetDriverHost()->TrackedDevicePoseUpdated(this->device_index_, pose, sizeof(vr::DriverPose_t));
this->last_pose_ = pose;
}
DeviceType PoseVRDriver::HMDDevice::GetDeviceType()
{
return DeviceType::HMD;
}
vr::TrackedDeviceIndex_t PoseVRDriver::HMDDevice::GetDeviceIndex()
{
return this->device_index_;
}
vr::EVRInitError PoseVRDriver::HMDDevice::Activate(uint32_t unObjectId)
{
this->device_index_ = unObjectId;
GetDriver()->Log("Activating HMD " + this->serial_);
// Load settings values
// Could probably make this cleaner with making a wrapper class
try {
int window_x = std::get<int>(GetDriver()->GetSettingsValue("window_x"));
if (window_x > 0)
this->window_x_ = window_x;
}
catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist
try {
int window_y = std::get<int>(GetDriver()->GetSettingsValue("window_y"));
if (window_y > 0)
this->window_x_ = window_y;
}
catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist
try {
int window_width = std::get<int>(GetDriver()->GetSettingsValue("window_width"));
if (window_width > 0)
this->window_width_ = window_width;
}
catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist
try {
int window_height = std::get<int>(GetDriver()->GetSettingsValue("window_height"));
if (window_height > 0)
this->window_height_ = window_height;
}
catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist
// Get the properties handle
auto props = GetDriver()->GetProperties()->TrackedDeviceToPropertyContainer(this->device_index_);
// Set some universe ID (Must be 2 or higher)
GetDriver()->GetProperties()->SetUint64Property(props, vr::Prop_CurrentUniverseId_Uint64, 2);
// Set the IPD to be whatever steam has configured
GetDriver()->GetProperties()->SetFloatProperty(props, vr::Prop_UserIpdMeters_Float, vr::VRSettings()->GetFloat(vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_IPD_Float));
// Set the display FPS
GetDriver()->GetProperties()->SetFloatProperty(props, vr::Prop_DisplayFrequency_Float, 90.f);
// Set up a model "number" (not needed but good to have)
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_ModelNumber_String, "EXAMPLE_HMD_DEVICE");
// Set up icon paths
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceReady_String, "{example}/icons/hmd_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceOff_String, "{example}/icons/hmd_not_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceSearching_String, "{example}/icons/hmd_not_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{example}/icons/hmd_not_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{example}/icons/hmd_not_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceNotReady_String, "{example}/icons/hmd_not_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceStandby_String, "{example}/icons/hmd_not_ready.png");
GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceAlertLow_String, "{example}/icons/hmd_not_ready.png");
return vr::EVRInitError::VRInitError_None;
}
void PoseVRDriver::HMDDevice::Deactivate()
{
this->device_index_ = vr::k_unTrackedDeviceIndexInvalid;
}
void PoseVRDriver::HMDDevice::EnterStandby()
{
}
void* PoseVRDriver::HMDDevice::GetComponent(const char* pchComponentNameAndVersion)
{
if (!_stricmp(pchComponentNameAndVersion, vr::IVRDisplayComponent_Version)) {
return static_cast<vr::IVRDisplayComponent*>(this);
}
return nullptr;
}
void PoseVRDriver::HMDDevice::DebugRequest(const char* pchRequest, char* pchResponseBuffer, uint32_t unResponseBufferSize)
{
if (unResponseBufferSize >= 1)
pchResponseBuffer[0] = 0;
}
vr::DriverPose_t PoseVRDriver::HMDDevice::GetPose()
{
return this->last_pose_;
}
void PoseVRDriver::HMDDevice::GetWindowBounds(int32_t* pnX, int32_t* pnY, uint32_t* pnWidth, uint32_t* pnHeight)
{
*pnX = this->window_x_;
*pnY = this->window_y_;
*pnWidth = this->window_width_;
*pnHeight = this->window_height_;
}
bool PoseVRDriver::HMDDevice::IsDisplayOnDesktop()
{
return true;
}
bool PoseVRDriver::HMDDevice::IsDisplayRealDisplay()
{
return false;
}
void PoseVRDriver::HMDDevice::GetRecommendedRenderTargetSize(uint32_t* pnWidth, uint32_t* pnHeight)
{
*pnWidth = this->window_width_;
*pnHeight = this->window_height_;
}
void PoseVRDriver::HMDDevice::GetEyeOutputViewport(vr::EVREye eEye, uint32_t* pnX, uint32_t* pnY, uint32_t* pnWidth, uint32_t* pnHeight)
{
*pnY = 0;
*pnWidth = this->window_width_ / 2;
*pnHeight = this->window_height_;
if (eEye == vr::EVREye::Eye_Left) {
*pnX = 0;
}
else {
*pnX = this->window_width_ / 2;
}
}
void PoseVRDriver::HMDDevice::GetProjectionRaw(vr::EVREye eEye, float* pfLeft, float* pfRight, float* pfTop, float* pfBottom)
{
*pfLeft = -1;
*pfRight = 1;
*pfTop = -1;
*pfBottom = 1;
}
vr::DistortionCoordinates_t PoseVRDriver::HMDDevice::ComputeDistortion(vr::EVREye eEye, float fU, float fV)
{
vr::DistortionCoordinates_t coordinates;
coordinates.rfBlue[0] = fU;
coordinates.rfBlue[1] = fV;
coordinates.rfGreen[0] = fU;
coordinates.rfGreen[1] = fV;
coordinates.rfRed[0] = fU;
coordinates.rfRed[1] = fV;
return coordinates;
}
| 35.695067
| 172
| 0.690955
|
justinliang1020
|
f58dd8aa820c864c8f89624f653d346e798698a3
| 4,902
|
cc
|
C++
|
src/tir/ir/function.cc
|
cli99/tvm
|
6c6e873a1325a32418108daad6e38f3df8c37660
|
[
"Apache-2.0"
] | null | null | null |
src/tir/ir/function.cc
|
cli99/tvm
|
6c6e873a1325a32418108daad6e38f3df8c37660
|
[
"Apache-2.0"
] | null | null | null |
src/tir/ir/function.cc
|
cli99/tvm
|
6c6e873a1325a32418108daad6e38f3df8c37660
|
[
"Apache-2.0"
] | 1
|
2022-03-02T16:24:54.000Z
|
2022-03-02T16:24:54.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.
*/
/*!
* \file src/tir/ir/function.cc
* \brief The function data structure.
*/
#include <tvm/runtime/registry.h>
#include <tvm/tir/function.h>
#include <tvm/tir/op.h>
namespace tvm {
namespace tir {
// Get the function type of a PrimFunc
PrimFunc::PrimFunc(Array<tir::Var> params, Stmt body, Type ret_type,
Map<tir::Var, Buffer> buffer_map, DictAttrs attrs, Span span) {
// Assume void-return type for now
// TODO(tvm-team) consider type deduction from body.
if (!ret_type.defined()) {
ret_type = VoidType();
}
auto n = make_object<PrimFuncNode>();
n->params = std::move(params);
n->body = std::move(body);
n->ret_type = std::move(ret_type);
n->buffer_map = std::move(buffer_map);
n->attrs = std::move(attrs);
n->checked_type_ = n->func_type_annotation();
n->span = std::move(span);
data_ = std::move(n);
}
FuncType PrimFuncNode::func_type_annotation() const {
Array<Type> param_types;
for (auto param : this->params) {
param_types.push_back(GetType(param));
}
return FuncType(param_types, ret_type, {}, {});
}
TVM_REGISTER_NODE_TYPE(PrimFuncNode);
class TensorIntrinManager {
public:
Map<String, tir::TensorIntrin> reg;
static TensorIntrinManager* Global() {
static TensorIntrinManager* inst = new TensorIntrinManager();
return inst;
}
};
TensorIntrin::TensorIntrin(PrimFunc desc, PrimFunc impl) {
// Check the number of func var is equal
CHECK_EQ(desc->params.size(), impl->params.size())
<< "ValueError: The number of parameters of the description and the implementation of the "
"tensor intrinsic doesn't match.";
for (size_t i = 0; i < desc->params.size(); i++) {
CHECK(desc->params[i]->dtype.is_handle()) << "ValueError: Parameters of the description of the "
"tensor intrinsic should be handle only.";
CHECK(impl->params[i]->dtype.is_handle()) << "ValueError: Parameters of the implementation of "
"the tensor intrinsic should be handle only.";
}
ICHECK_EQ(desc->buffer_map.size(), impl->buffer_map.size());
ObjectPtr<TensorIntrinNode> n = make_object<TensorIntrinNode>();
n->desc = std::move(desc);
n->impl = std::move(impl);
data_ = std::move(n);
}
void TensorIntrin::Register(String name, TensorIntrin intrin) {
TensorIntrinManager* manager = TensorIntrinManager::Global();
CHECK_EQ(manager->reg.count(name), 0)
<< "ValueError: TensorIntrin '" << name << "' has already been registered";
manager->reg.Set(name, intrin);
}
TensorIntrin TensorIntrin::Get(String name) {
const TensorIntrinManager* manager = TensorIntrinManager::Global();
auto it = manager->reg.find(name);
CHECK(it != manager->reg.end()) << "ValueError: TensorIntrin '" << name << "' is not registered";
return manager->reg.at(name);
}
TVM_REGISTER_NODE_TYPE(TensorIntrinNode);
TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<PrimFuncNode>([](const ObjectRef& ref, ReprPrinter* p) {
// TODO(tvm-team) redirect to Text printer once we have a good text format.
auto* node = static_cast<const PrimFuncNode*>(ref.get());
p->stream << "PrimFunc(" << node->params << ") ";
if (node->attrs.defined()) {
p->stream << "attrs=" << node->attrs;
}
p->stream << " {\n";
p->indent += 2;
p->Print(node->body);
p->indent -= 2;
p->stream << "}\n";
});
TVM_REGISTER_GLOBAL("tir.PrimFunc")
.set_body_typed([](Array<tir::Var> params, Stmt body, Type ret_type,
Map<tir::Var, Buffer> buffer_map, DictAttrs attrs, Span span) {
return PrimFunc(params, body, ret_type, buffer_map, attrs, span);
});
TVM_REGISTER_GLOBAL("tir.TensorIntrin")
.set_body_typed([](PrimFunc desc_func, PrimFunc intrin_func) {
return TensorIntrin(desc_func, intrin_func);
});
TVM_REGISTER_GLOBAL("tir.TensorIntrinRegister").set_body_typed(TensorIntrin::Register);
TVM_REGISTER_GLOBAL("tir.TensorIntrinGet").set_body_typed(TensorIntrin::Get);
} // namespace tir
} // namespace tvm
| 36.311111
| 100
| 0.675031
|
cli99
|
f58e68715c7e0dc39bc9fce281b2e2b812f16124
| 3,658
|
cpp
|
C++
|
Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp
|
gaoxiaojun/minircp
|
fe20201a768515cd0387f0b76a16c0c766cf939d
|
[
"BSD-3-Clause"
] | 5
|
2015-05-27T06:57:53.000Z
|
2020-03-12T21:08:23.000Z
|
Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp
|
kometa-dev/MITK
|
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
|
[
"BSD-3-Clause"
] | 141
|
2015-03-03T06:52:01.000Z
|
2020-12-10T07:28:14.000Z
|
Plugins/org.blueberry.ui.qt/src/internal/intro/berryViewIntroAdapterPart.cpp
|
kometa-dev/MITK
|
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
|
[
"BSD-3-Clause"
] | 4
|
2015-02-19T06:48:13.000Z
|
2020-06-19T16:20:25.000Z
|
/*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryViewIntroAdapterPart.h"
#include "berryIntroPartAdapterSite.h"
#include "internal/berryWorkbench.h"
#include "internal/berryWorkbenchPlugin.h"
namespace berry
{
ViewIntroAdapterPart::ViewIntroAdapterPart() :
propChangeListener(new PropertyChangeIntAdapter<ViewIntroAdapterPart>(this, &ViewIntroAdapterPart::PropertyChange))
{
}
void ViewIntroAdapterPart::SetStandby(bool standby)
{
// final Control control = ((PartSite) getSite()).getPane().getControl();
// BusyIndicator.showWhile(control.getDisplay(), new Runnable() {
// public void run() {
// try {
// control.setRedraw(false);
introPart->StandbyStateChanged(standby);
// } finally {
// control.setRedraw(true);
// }
//
// setBarVisibility(standby);
// }
// });
}
void ViewIntroAdapterPart::CreatePartControl(QWidget* parent)
{
//addPaneListener();
introPart->CreatePartControl(parent);
}
ViewIntroAdapterPart::~ViewIntroAdapterPart()
{
//setBarVisibility(true);
introPart->RemovePropertyListener(propChangeListener.data());
GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro(
introPart);
}
QIcon ViewIntroAdapterPart::GetTitleImage() const
{
return introPart->GetTitleImage();
}
QString ViewIntroAdapterPart::GetPartName() const
{
// this method is called eagerly before our init method is called (and
// therefore before our intropart is created). By default return
// the view title from the view declaration. We will fire a property
// change to set the title to the proper value in the init method.
return introPart.IsNull() ? ViewPart::GetPartName() : introPart->GetPartName();
}
void ViewIntroAdapterPart::Init(IViewSite::Pointer site,
IMemento::Pointer memento) throw (PartInitException)
{
ViewPart::Init(site);
Workbench* workbench =
dynamic_cast<Workbench*>(site->GetWorkbenchWindow()->GetWorkbench());
try
{
introPart = workbench->GetWorkbenchIntroManager() ->CreateNewIntroPart();
// reset the part name of this view to be that of the intro title
SetPartName(introPart->GetPartName());
introPart->AddPropertyListener(propChangeListener.data());
introSite
= IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor()));
introPart->Init(introSite, memento);
} catch (CoreException& e)
{
//TODO IStatus
// WorkbenchPlugin.log(
// IntroMessages.Intro_could_not_create_proxy,
// new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH,
// IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e));
WorkbenchPlugin::Log("Could not create intro view proxy.", e);
}
}
void ViewIntroAdapterPart::PropertyChange(const Object::Pointer& /*source*/,
int propId)
{
FirePropertyChange(propId);
}
void ViewIntroAdapterPart::SetFocus()
{
introPart->SetFocus();
}
void ViewIntroAdapterPart::SaveState(IMemento::Pointer memento)
{
introPart->SaveState(memento);
}
}
| 29.983607
| 117
| 0.666758
|
gaoxiaojun
|
f591f76aa9a9b3d4737ffd18385afff19d88dede
| 359
|
cpp
|
C++
|
config/src/vespa/config/print/configdatabuffer.cpp
|
Anlon-Burke/vespa
|
5ecd989b36cc61716bf68f032a3482bf01fab726
|
[
"Apache-2.0"
] | 4,054
|
2017-08-11T07:58:38.000Z
|
2022-03-31T22:32:15.000Z
|
config/src/vespa/config/print/configdatabuffer.cpp
|
Anlon-Burke/vespa
|
5ecd989b36cc61716bf68f032a3482bf01fab726
|
[
"Apache-2.0"
] | 4,854
|
2017-08-10T20:19:25.000Z
|
2022-03-31T19:04:23.000Z
|
config/src/vespa/config/print/configdatabuffer.cpp
|
Anlon-Burke/vespa
|
5ecd989b36cc61716bf68f032a3482bf01fab726
|
[
"Apache-2.0"
] | 541
|
2017-08-10T18:51:18.000Z
|
2022-03-11T03:18:56.000Z
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "configdatabuffer.h"
#include <vespa/vespalib/data/slime/slime.h>
namespace config {
ConfigDataBuffer::ConfigDataBuffer() :
_slime(std::make_unique<vespalib::Slime>())
{ }
ConfigDataBuffer::~ConfigDataBuffer() { }
} // namespace config
| 23.933333
| 104
| 0.743733
|
Anlon-Burke
|
f592a71e54548674f08d1c1ba8cdc6b11b68d3e6
| 28,338
|
hpp
|
C++
|
include/seqan3/alphabet/composite/alphabet_variant.hpp
|
anbratu/seqan3
|
8cbfe77a996572065b57c3fe67094cc56a2c43da
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
include/seqan3/alphabet/composite/alphabet_variant.hpp
|
anbratu/seqan3
|
8cbfe77a996572065b57c3fe67094cc56a2c43da
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
include/seqan3/alphabet/composite/alphabet_variant.hpp
|
anbratu/seqan3
|
8cbfe77a996572065b57c3fe67094cc56a2c43da
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Marcel Ehrhardt <marcel.ehrhardt AT fu-berlin.de>
* \author David Heller <david.heller AT fu-berlin.de>
* \brief Provides seqan3::alphabet_variant.
*/
#pragma once
#include <algorithm>
#include <array>
#include <utility>
#include <cassert>
#include <variant>
#include <meta/meta.hpp>
#include <seqan3/alphabet/concept.hpp>
#include <seqan3/alphabet/composite/detail.hpp>
#include <seqan3/alphabet/alphabet_base.hpp>
#include <seqan3/core/concept/core_language.hpp>
#include <seqan3/core/detail/int_types.hpp>
#include <seqan3/core/type_traits/pack.hpp>
#include <seqan3/core/type_traits/range.hpp>
#include <seqan3/core/type_traits/transformation_trait_or.hpp>
#include <seqan3/core/tuple_utility.hpp>
#include <seqan3/std/concepts>
#include <seqan3/std/type_traits>
namespace seqan3::detail
{
/*!\brief Evaluates to true if the one of the alternatives of the seqan3::alphabet_variant satisifes a compile-time
* predicate.
* \tparam variant_t A specialisation of seqan3::alphabet_variant.
* \tparam fun_t A template template that takes target_t as argument and exposes an `invoke` member type that
* evaluates some predicate and returns `std::true_type` or `std::false_type`.
* \tparam target_t The type you wish query.
* \ingroup composite
*
* \details
*
* To prevent recursive template and/or concept instantiation this call needs to be guarded against many exceptions.
* See the source file for more details.
*/
// default is false
template <typename variant_t,
template <typename> typename fun_t,
typename target_t>
inline bool constexpr one_alternative_is = false;
//!\cond
// actual implementation
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
target_t>
= !meta::empty<meta::find_if<meta::list<alternatives...>, fun_t<target_t>>>::value;
// guard against self
template <typename ...alternatives,
template <typename> typename fun_t>
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
alphabet_variant<alternatives...>> = false;
// guard against types convertible to self without needing self's constructors
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
requires convertible_to_by_member<target_t, alphabet_variant<alternatives...>>
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
target_t> = false;
// guard against tuple composites that contain the variant somewhere (they can implicitly convert at source)
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
requires alphabet_tuple_base_specialisation<target_t> &&
meta::in<detail::transformation_trait_or_t<recursive_tuple_components<target_t>, meta::list<>>,
alphabet_variant<alternatives...>>::value
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
target_t> = false;
// guard against alternatives
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
requires type_in_pack_v<target_t, alternatives...>
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
target_t> = false;
// guard against alternatives (LHS and RHS switched)
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
requires type_in_pack_v<target_t, alternatives...>
inline bool constexpr one_alternative_is<target_t,
fun_t,
alphabet_variant<alternatives...>> = false;
// guard against ranges and iterators over self to prevent recursive instantiation
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
//NO, it's not possible to use the value_type type trait here
requires requires { std::same_as<typename target_t::value_type, alphabet_variant<alternatives...>>; }
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
target_t> = false;
// guard against pairs/tuples that *might* contain self to prevent recursive instantiation
// (applying tuple_like unfortunately does not work because it itself starts recursive instantiation)
template <typename ...alternatives,
template <typename> typename fun_t,
typename target_t>
requires tuple_size<target_t> && !alphabet_tuple_base_specialisation<target_t>
inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>,
fun_t,
target_t> = false;
//!\endcond
} // namespace seqan3::detail
namespace seqan3
{
/*!\brief A combined alphabet that can hold values of either of its alternatives.
* \ingroup composite
* \if DEV
* \tparam ...alternative_types Types of possible values (at least 2); all must model
* seqan3::detail::writable_constexpr_alphabet, not be references and be unique.
* \implements seqan3::detail::writable_constexpr_alphabet
* \else
* \tparam ...alternative_types Types of possible values (at least 2); all must model seqan3::writable_alphabet,
* must not be references and must be unique; all required functions for
* seqan3::writable_alphabet need to be callable in a `constexpr`-context.
* \endif
* \implements seqan3::writable_alphabet
* \implements seqan3::trivially_copyable
* \implements seqan3::standard_layout
* \details
*
* The alphabet_variant represents the union of two or more alternative alphabets (e.g. the
* four letter DNA alternative + the gap alternative). It behaves similar to a
* [variant](https://en.cppreference.com/w/cpp/language/variant) or std::variant, but it preserves the
* seqan3::alphabet.
*
* Short description:
* * combines multiple different alphabets in an "either-or"-fashion;
* * is itself a seqan3::alphabet;
* * its alphabet size is the sum of the individual sizes;
* * default initialises to the the first alternative's default (no empty state like std::variant);
* * constructible, assignable and (in-)equality-comparable with each alternative type and also all types that
* these are constructible/assignable/equality-comparable with;
* * only convertible to its alternatives through the member function convert_to() (which can throw!)
*
* ### Example
*
* \include test/snippet/alphabet/composite/alphabet_variant.cpp
*
* ### The `char` representation of an alphabet_variant
*
* Part of the seqan3::alphabet concept requires that the alphabet_variant provides a char representation in addition
* to the rank representation. For an object of seqan3::alphabet_variant, the `to_char()` member function will always
* return the same character as if invoked on the respective alternative.
* In contrast, the `assign_char()` member function might be ambiguous between the alternative alphabets in a variant.
*
* For example, assigning a '!' to seqan3::dna15 resolves to an object of rank 8 with char representation 'N' while
* assigning '!' to seqan3::gap always resolves to rank 0, the gap symbol itself ('-'_gap).
* We tackle this ambiguousness by **defaulting unknown characters to the representation of the first alternative**
* (e.g. `alphabet_variant<dna15, gap>{}.assign_char('!')` resolves to rank 8, representing `N`_dna15).
*
* On the other hand, two alternative alphabets might have the same char representation (e.g if
* you combine dna4 with dna5, 'A', 'C', 'G' and 'T' are ambiguous).
* We tackle this ambiguousness by **always choosing the first valid char representation** (e.g.
* `alphabet_variant<dna4, dna5>{}.assign_char('A')` resolves to rank 0, representing an `A`_dna4).
*
* To explicitly assign via the character representation of a specific alphabet,
* assign to that type first and then assign to the variant, e.g.
*
* \include test/snippet/alphabet/composite/alphabet_variant_char_representation.cpp
*/
template <typename ...alternative_types>
//!\cond
requires (detail::writable_constexpr_alphabet<alternative_types> && ...) &&
(!std::is_reference_v<alternative_types> && ...) &&
(sizeof...(alternative_types) >= 2)
//TODO same char_type
//!\endcond
class alphabet_variant : public alphabet_base<alphabet_variant<alternative_types...>,
(static_cast<size_t>(alphabet_size<alternative_types>) + ...),
char> //TODO underlying char t
{
private:
//!\brief The base type.
using base_t = alphabet_base<alphabet_variant<alternative_types...>,
(static_cast<size_t>(alphabet_size<alternative_types>) + ...),
char>;
//!\brief Befriend the base type.
friend base_t;
//!\brief A meta::list of the types of each alternative in the composite
using alternatives = meta::list<alternative_types...>;
static_assert(std::same_as<alternatives, meta::unique<alternatives>>,
"All types in a alphabet_variant must be distinct.");
using typename base_t::char_type;
using typename base_t::rank_type;
public:
using base_t::alphabet_size;
using base_t::to_char;
using base_t::to_rank;
using base_t::assign_rank;
/*!\brief Returns true if alternative_t is one of the given alternative types.
* \tparam alternative_t The type to check.
*
* \include test/snippet/alphabet/composite/alphabet_variant_holds_alternative.cpp
*/
template <typename alternative_t>
static constexpr bool holds_alternative() noexcept
{
return detail::type_in_pack_v<alternative_t, alternative_types...>;
}
/*!\name Constructors, destructor and assignment
* \{
*/
constexpr alphabet_variant() noexcept = default; //!< Defaulted.
constexpr alphabet_variant(alphabet_variant const &) noexcept = default; //!< Defaulted.
constexpr alphabet_variant(alphabet_variant &&) noexcept = default; //!< Defaulted.
constexpr alphabet_variant & operator=(alphabet_variant const &) noexcept = default; //!< Defaulted.
constexpr alphabet_variant & operator=(alphabet_variant &&) noexcept = default; //!< Defaulted.
~alphabet_variant() noexcept = default; //!< Defaulted.
/*!\brief Construction via the value of an alternative.
* \tparam alternative_t One of the alternative types.
* \param alternative The value of a alternative that should be assigned.
*
* \include test/snippet/alphabet/composite/alphabet_variant_value_construction.cpp
*/
template <typename alternative_t>
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
constexpr alphabet_variant(alternative_t const & alternative) noexcept
{
assign_rank(rank_by_type_(alternative));
}
/*!\brief Construction via the value of a type that an alternative type is constructible from.
* \tparam indirect_alternative_t A type that one of the alternative types is constructible from.
* \param rhs The value that should be assigned.
*
* \include test/snippet/alphabet/composite/alphabet_variant_conversion.cpp
* \attention When selecting the alternative alphabet types which require only implicit conversion
* or constructor calls, are preferred over those that require explicit ones.
*/
template <typename indirect_alternative_t>
//!\cond
requires !detail::one_alternative_is<alphabet_variant,
detail::implicitly_convertible_from,
indirect_alternative_t> &&
detail::one_alternative_is<alphabet_variant,
detail::constructible_from,
indirect_alternative_t>
//!\endcond
constexpr alphabet_variant(indirect_alternative_t const & rhs) noexcept
{
assign_rank(rank_by_type_(meta::front<meta::find_if<alternatives,
detail::constructible_from<indirect_alternative_t>>>(rhs)));
}
//!\cond
template <typename indirect_alternative_t>
requires detail::one_alternative_is<alphabet_variant,
detail::implicitly_convertible_from,
indirect_alternative_t>
constexpr alphabet_variant(indirect_alternative_t const & rhs) noexcept
{
assign_rank(
rank_by_type_(
meta::front<meta::find_if<alternatives,
detail::implicitly_convertible_from<indirect_alternative_t>>>(rhs)));
}
//!\endcond
/*!\brief Assignment via a value that one of the alternative types is assignable from.
* \tparam indirect_alternative_t A type that one of the alternatives is assignable from.
* \param rhs The value of an alternative.
*
* \include test/snippet/alphabet/composite/alphabet_variant_subtype_construction.cpp
*/
template <typename indirect_alternative_t>
//!\cond
requires !detail::one_alternative_is<alphabet_variant,
detail::implicitly_convertible_from,
indirect_alternative_t> && // constructor takes care
!detail::one_alternative_is<alphabet_variant,
detail::constructible_from,
indirect_alternative_t> && // constructor takes care
detail::one_alternative_is<alphabet_variant,
detail::assignable_from,
indirect_alternative_t>
//!\endcond
constexpr alphabet_variant & operator=(indirect_alternative_t const & rhs) noexcept
{
using alternative_t = meta::front<meta::find_if<alternatives, detail::assignable_from<indirect_alternative_t>>>;
alternative_t alternative{};
alternative = rhs;
assign_rank(rank_by_type_(alternative));
return *this;
}
//!\}
/*!\name Conversion (by index)
* \{
*/
//!\brief Whether the variant alphabet currently holds a value of the given alternative.
//!\tparam index Index of the alternative to check for.
template <size_t index>
constexpr bool is_alternative() const noexcept
{
static_assert(index < alphabet_size, "The alphabet_variant contains less alternatives than you are checking.");
return (to_rank() >= partial_sum_sizes[index]) && (to_rank() < partial_sum_sizes[index + 1]);
}
/*!\brief Convert to the specified alphabet (throws if is_alternative() would be false).
* \tparam index Index of the alternative to check for.
* \throws std::bad_variant_access If the variant_alphabet currently holds the value of a different alternative.
*/
template <size_t index>
constexpr auto convert_to() const
{
return convert_impl<index, true>();
}
/*!\brief Convert to the specified alphabet (**undefined behaviour** if is_alternative() would be false).
* \tparam index Index of the alternative to check for.
*/
template <size_t index>
constexpr auto convert_unsafely_to() const noexcept
{
return convert_impl<index, false>();
}
//!\}
/*!\name Conversion (by type)
* \{
*/
/*!\copybrief is_alternative()
* \tparam alternative_t The type of the alternative that you wish to check for.
*/
template <typename alternative_t>
constexpr bool is_alternative() const noexcept
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
{
constexpr size_t index = meta::find_index<alternatives, alternative_t>::value;
return is_alternative<index>();
}
/*!\copybrief convert_to()
* \tparam alternative_t The type of the alternative that you wish to check for.
* \throws std::bad_variant_access If the variant_alphabet currently holds the value of a different alternative.
*/
template <typename alternative_t>
constexpr alternative_t convert_to() const
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
{
constexpr size_t index = meta::find_index<alternatives, alternative_t>::value;
return convert_impl<index, true>();
}
/*!\copybrief convert_unsafely_to()
* \tparam alternative_t The type of the alternative that you wish to check for.
*/
template <typename alternative_t>
constexpr alternative_t convert_unsafely_to() const noexcept
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
{
constexpr size_t index = meta::find_index<alternatives, alternative_t>::value;
return convert_impl<index, false>();
}
//!\}
/*!\name Comparison operators (against alternatives)
* \brief Defines comparison against alternatives, e.g. `alphabet_variant<dna5, gap>{gap{}} == 'C'_dna5`. Only
* (in-)equality comparison is explicitly defined, because it would be difficult to argue about e.g.
* `alphabet_variant<dna5, gap>{gap{}} < 'C'_dna5`.
* \{
*/
//!\brief Checks for equality.
template <typename alternative_t>
constexpr bool operator==(alternative_t const rhs) const noexcept
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
{
return is_alternative<alternative_t>() && (convert_unsafely_to<alternative_t>() == rhs);
}
//!\brief Checks for inequality.
template <typename alternative_t>
constexpr bool operator!=(alternative_t const rhs) const noexcept
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
{
return !operator==(rhs);
}
//!\}
/*!\name Comparison operators (against indirect alternatives)
* \brief Defines comparison against types that are comparable with alternatives, e.g.
* `alphabet_variant<dna5, gap>{'C'_dna5} == 'C'_rna5`. Only (in-)equality comparison is explicitly defined,
* because it would be difficult to argue about e.g.
* `alphabet_variant<dna5, gap>{gap{}} < 'C'_rna5`.
* \{
*/
//!\brief Checks for equality.
template <typename indirect_alternative_type>
constexpr bool operator==(indirect_alternative_type const rhs) const noexcept
//!\cond
requires detail::one_alternative_is<alphabet_variant,
detail::weakly_equality_comparable_with_,
indirect_alternative_type>
//!\endcond
{
using alternative_t =
meta::front<meta::find_if<alternatives,
detail::weakly_equality_comparable_with_<indirect_alternative_type>>>;
return is_alternative<alternative_t>() && (convert_unsafely_to<alternative_t>() == rhs);
}
//!\brief Checks for inequality.
template <typename indirect_alternative_type>
constexpr bool operator!=(indirect_alternative_type const rhs) const noexcept
//!\cond
requires detail::one_alternative_is<alphabet_variant,
detail::weakly_equality_comparable_with_,
indirect_alternative_type>
//!\endcond
{
return !operator==(rhs);
}
//!\}
protected:
//!\privatesection
/*!\brief Implementation function for convert_to() and convert_unsafely_to().
* \tparam index Index of the alternative to convert to.
* \tparam throws Whether to perform checks (and throw) or not.
*/
template <size_t index, bool throws>
constexpr auto convert_impl() const noexcept(!throws) -> meta::at_c<alternatives, index>
{
static_assert(index < alphabet_size, "The alphabet_variant contains less alternatives than you are checking.");
using alternative_t = meta::at_c<alternatives, index>;
if constexpr (throws)
{
if (!is_alternative<index>()) // [[unlikely]]
{
throw std::bad_variant_access{};
}
}
return seqan3::assign_rank_to(to_rank() - partial_sum_sizes[index], alternative_t{});
}
/*!\brief Compile-time generated lookup table which contains the partial
* sum up to the position of each alternative.
*
* An array which contains the prefix sum over all
* alternative_types::alphabet_size's.
*
*/
static constexpr std::array partial_sum_sizes = []() constexpr
{
constexpr size_t N = sizeof...(alternative_types) + 1;
std::array<rank_type, N> partial_sum{0, seqan3::alphabet_size<alternative_types>...};
for (size_t i = 1u; i < N; ++i)
partial_sum[i] += partial_sum[i-1];
return partial_sum;
}();
/*!\brief Compile-time generated lookup table which maps the rank to char.
*
* A map generated at compile time where the key is the rank of the variant
* of all alternatives and the value is the corresponding char of that rank
* and alternative.
*
*/
static constexpr std::array<char_type, alphabet_size> rank_to_char = []() constexpr
{
// Explicitly writing assign_rank_to_char within assign_rank_to_char
// causes this bug (g++-7 and g++-8):
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84684
auto assign_rank_to_char = [](auto alternative, size_t rank) constexpr
{
return seqan3::to_char(seqan3::assign_rank_to(rank, alternative));
};
auto assign_value_to_char = [assign_rank_to_char] (auto alternative, auto & value_to_char, auto & value) constexpr
{
using alternative_t = std::decay_t<decltype(alternative)>;
for (size_t i = 0u; i < seqan3::alphabet_size<alternative_t>; ++i, ++value)
value_to_char[value] = assign_rank_to_char(alternative, i);
};
unsigned value = 0u;
std::array<char_type, alphabet_size> value_to_char{};
// initializer lists guarantee sequencing;
// the following expression behaves as:
// for(auto alternative: alternative_types)
// assign_rank_to_char(alternative, rank_to_char, value);
((assign_value_to_char(alternative_types{}, value_to_char, value)),...);
return value_to_char;
}();
//!\brief Converts an object of one of the given alternatives into the internal representation.
//!\tparam index The position of `alternative_t` in the template pack `alternative_types`.
//!\tparam alternative_t One of the alternative types.
//!\param alternative The value of a alternative.
template <size_t index, typename alternative_t>
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
static constexpr rank_type rank_by_index_(alternative_t const & alternative) noexcept
{
return partial_sum_sizes[index] + static_cast<rank_type>(seqan3::to_rank(alternative));
}
//!\brief Converts an object of one of the given alternatives into the internal representation.
//!\details Finds the index of alternative_t in the given types.
//!\tparam alternative_t One of the alternative types.
//!\param alternative The value of a alternative.
template <typename alternative_t>
//!\cond
requires holds_alternative<alternative_t>()
//!\endcond
static constexpr rank_type rank_by_type_(alternative_t const & alternative) noexcept
{
constexpr size_t index = meta::find_index<alternatives, alternative_t>::value;
return rank_by_index_<index>(alternative);
}
/*!\brief Compile-time generated lookup table which maps the char to rank.
*
* An map generated at compile time where the key is the char of one of the
* alternatives and the value is the corresponding rank over all alternatives (by
* conflict will default to the first).
*
*/
static constexpr std::array char_to_rank = []() constexpr
{
constexpr size_t table_size = 1 << (sizeof(char_type) * 8);
std::array<rank_type, table_size> char_to_rank{};
for (size_t i = 0u; i < table_size; ++i)
{
char_type chr = static_cast<char_type>(i);
bool there_was_no_valid_representation{true};
meta::for_each(alternatives{}, [&] (auto && alt)
{
using alt_type = remove_cvref_t<decltype(alt)>;
if (there_was_no_valid_representation && char_is_valid_for<alt_type>(chr))
{
there_was_no_valid_representation = false;
char_to_rank[i] = rank_by_type_(assign_char_to(chr, alt_type{}));
}
});
if (there_was_no_valid_representation)
char_to_rank[i] = rank_by_type_(assign_char_to(chr, meta::front<alternatives>{}));
}
return char_to_rank;
}();
//!\brief Validate whether a character is valid in the by any of the combined alphabet.
static constexpr bool char_is_valid(char_type const chr) noexcept
{
bool is_valid{false};
meta::for_each(alternatives{}, [&] (auto && alt)
{
if (char_is_valid_for<remove_cvref_t<decltype(alt)>>(chr))
is_valid = true;
});
return is_valid;
}
};
/*!\name Comparison operators
* \relates alphabet_variant
* \brief Free function (in-)equality comparison operators that forward to member operators (for types != self).
*\{
*/
//!\brief Checks for equality.
template <typename lhs_t, typename ...alternative_types>
constexpr bool operator==(lhs_t const lhs, alphabet_variant<alternative_types...> const rhs) noexcept
//!\cond
requires detail::weakly_equality_comparable_by_members_with<alphabet_variant<alternative_types...>, lhs_t> &&
!detail::weakly_equality_comparable_by_members_with<lhs_t, alphabet_variant<alternative_types...>>
//!\endcond
{
return rhs == lhs;
}
//!\brief Checks for inequality.
template <typename lhs_t, typename ...alternative_types>
constexpr bool operator!=(lhs_t const lhs, alphabet_variant<alternative_types...> const rhs) noexcept
//!\cond
requires detail::weakly_equality_comparable_by_members_with<alphabet_variant<alternative_types...>, lhs_t> &&
!detail::weakly_equality_comparable_by_members_with<lhs_t, alphabet_variant<alternative_types...>>
//!\endcond
{
return rhs != lhs;
}
//!\}
} // namespace seqan3
| 43.198171
| 122
| 0.649058
|
anbratu
|
f592cba1aa5c92fe820cbceed75f181233d318e5
| 902
|
cpp
|
C++
|
Engine/Plugins/Runtime/Synthesis/Source/SynthesisEditor/Private/EpicSynth1PresetBank.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | 1
|
2022-01-29T18:36:12.000Z
|
2022-01-29T18:36:12.000Z
|
Engine/Plugins/Runtime/Synthesis/Source/SynthesisEditor/Private/EpicSynth1PresetBank.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
Engine/Plugins/Runtime/Synthesis/Source/SynthesisEditor/Private/EpicSynth1PresetBank.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "EpicSynth1PresetBank.h"
#include "SynthComponents/EpicSynth1Component.h"
#include "UObject/ObjectMacros.h"
#include "UObject/Object.h"
UClass* FAssetTypeActions_ModularSynthPresetBank::GetSupportedClass() const
{
return UModularSynthPresetBank::StaticClass();
}
UModularSynthPresetBankFactory::UModularSynthPresetBankFactory(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
SupportedClass = UModularSynthPresetBank::StaticClass();
bCreateNew = true;
bEditorImport = false;
bEditAfterNew = true;
}
UObject* UModularSynthPresetBankFactory::FactoryCreateNew(UClass* Class, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn)
{
UModularSynthPresetBank* NewPresetBank = NewObject<UModularSynthPresetBank>(InParent, InName, Flags);
return NewPresetBank;
}
| 32.214286
| 167
| 0.818182
|
windystrife
|
f5933b011ba63be0e9947627c5f263c62da7056f
| 5,231
|
cpp
|
C++
|
libs/tbb44_20160128oss_win_0/tbb44_20160128oss/examples/parallel_reduce/primes/main.cpp
|
umetaman/ofxExtremeGpuVideo
|
0bf28b131dedaf44899c269aef57e95dd700586c
|
[
"Zlib"
] | 59
|
2016-04-13T20:18:50.000Z
|
2022-01-24T00:46:16.000Z
|
libs/tbb44_20160128oss_win_0/tbb44_20160128oss/examples/parallel_reduce/primes/main.cpp
|
umetaman/ofxExtremeGpuVideo
|
0bf28b131dedaf44899c269aef57e95dd700586c
|
[
"Zlib"
] | 3
|
2016-11-19T18:33:49.000Z
|
2022-01-24T00:43:10.000Z
|
libs/tbb44_20160128oss_win_0/tbb44_20160128oss/examples/parallel_reduce/primes/main.cpp
|
umetaman/ofxExtremeGpuVideo
|
0bf28b131dedaf44899c269aef57e95dd700586c
|
[
"Zlib"
] | 7
|
2016-05-01T02:58:05.000Z
|
2021-09-17T02:20:19.000Z
|
/*
Copyright 2005-2016 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks is free software;
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
#include "primes.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <utility>
#include <iostream>
#include <sstream>
#include "tbb/tick_count.h"
#include "../../common/utility/utility.h"
struct RunOptions{
//! NumberType of threads to use.
utility::thread_number_range threads;
//whether to suppress additional output
bool silentFlag;
//
NumberType n;
//! Grain size parameter
NumberType grainSize;
// number of time to repeat calculation
NumberType repeatNumber;
RunOptions(utility::thread_number_range threads, NumberType grainSize, NumberType n, bool silentFlag, NumberType repeatNumber)
: threads(threads), grainSize(grainSize), n(n), silentFlag(silentFlag), repeatNumber(repeatNumber)
{}
};
int do_get_default_num_threads() {
int threads;
#if __TBB_MIC_OFFLOAD
#pragma offload target(mic) out(threads)
#endif // __TBB_MIC_OFFLOAD
threads = tbb::task_scheduler_init::default_num_threads();
return threads;
}
int get_default_num_threads() {
static int threads = do_get_default_num_threads();
return threads;
}
//! Parse the command line.
static RunOptions ParseCommandLine( int argc, const char* argv[] ) {
utility::thread_number_range threads( get_default_num_threads, 0, get_default_num_threads() );
NumberType grainSize = 1000;
bool silent = false;
NumberType number = 100000000;
NumberType repeatNumber = 1;
utility::parse_cli_arguments(argc,argv,
utility::cli_argument_pack()
//"-h" option for displaying help is present implicitly
.positional_arg(threads,"n-of-threads",utility::thread_number_range_desc)
.positional_arg(number,"number","upper bound of range to search primes in, must be a positive integer")
.positional_arg(grainSize,"grain-size","must be a positive integer")
.positional_arg(repeatNumber,"n-of-repeats","repeat the calculation this number of times, must be a positive integer")
.arg(silent,"silent","no output except elapsed time")
);
RunOptions options(threads,grainSize, number, silent, repeatNumber);
return options;
}
int main( int argc, const char* argv[] ) {
tbb::tick_count mainBeginMark = tbb::tick_count::now();
RunOptions options =ParseCommandLine(argc,argv);
// Try different numbers of threads
for( int p=options.threads.first; p<=options.threads.last; p=options.threads.step(p) ) {
for (NumberType i=0; i<options.repeatNumber;++i){
tbb::tick_count iterationBeginMark = tbb::tick_count::now();
NumberType count = 0;
NumberType n = options.n;
if( p==0 ) {
#if __TBB_MIC_OFFLOAD
#pragma offload target(mic) in(n) out(count)
#endif // __TBB_MIC_OFFLOAD
count = SerialCountPrimes(n);
} else {
NumberType grainSize = options.grainSize;
#if __TBB_MIC_OFFLOAD
#pragma offload target(mic) in(n, p, grainSize) out(count)
#endif // __TBB_MIC_OFFLOAD
count = ParallelCountPrimes(n, p, grainSize);
}
tbb::tick_count iterationEndMark = tbb::tick_count::now();
if (!options.silentFlag){
std::cout
<<"#primes from [2.." <<options.n<<"] = " << count
<<" ("<<(iterationEndMark-iterationBeginMark).seconds()<< " sec with "
;
if( 0 != p )
std::cout<<p<<"-way parallelism";
else
std::cout<<"serial code";
std::cout<<")\n" ;
}
}
}
utility::report_elapsed_time((tbb::tick_count::now()-mainBeginMark).seconds());
return 0;
}
| 41.848
| 130
| 0.66125
|
umetaman
|
f593c1a79a0d63012e1b82c7e73138654f643a27
| 10,546
|
cpp
|
C++
|
contrib/libpoco/Foundation/testsuite/src/BasicEventTest.cpp
|
189569400/ClickHouse
|
0b8683c8c9f0e17446bef5498403c39e9cb483b8
|
[
"Apache-2.0"
] | 111
|
2015-01-13T18:14:31.000Z
|
2022-02-20T14:26:55.000Z
|
contrib/libpoco/Foundation/testsuite/src/BasicEventTest.cpp
|
189569400/ClickHouse
|
0b8683c8c9f0e17446bef5498403c39e9cb483b8
|
[
"Apache-2.0"
] | 54
|
2015-02-23T16:57:41.000Z
|
2021-02-19T08:16:27.000Z
|
contrib/libpoco/Foundation/testsuite/src/BasicEventTest.cpp
|
189569400/ClickHouse
|
0b8683c8c9f0e17446bef5498403c39e9cb483b8
|
[
"Apache-2.0"
] | 26
|
2015-01-17T13:07:56.000Z
|
2021-12-02T07:43:29.000Z
|
//
// BasicEventTest.cpp
//
// $Id: //poco/1.4/Foundation/testsuite/src/BasicEventTest.cpp#2 $
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "BasicEventTest.h"
#include "DummyDelegate.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Expire.h"
#include "Poco/Delegate.h"
#include "Poco/FunctionDelegate.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
using namespace Poco;
#define LARGEINC 100
BasicEventTest::BasicEventTest(const std::string& name): CppUnit::TestCase(name)
{
}
BasicEventTest::~BasicEventTest()
{
}
void BasicEventTest::testNoDelegate()
{
int tmp = 0;
EventArgs args;
assert (_count == 0);
assert (Void.empty());
Void.notify(this);
assert (_count == 0);
Void += delegate(this, &BasicEventTest::onVoid);
assert (!Void.empty());
Void -= delegate(this, &BasicEventTest::onVoid);
assert (Void.empty());
Void.notify(this);
assert (_count == 0);
assert (Simple.empty());
Simple.notify(this, tmp);
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
assert (!Simple.empty());
Simple -= delegate(this, &BasicEventTest::onSimple);
assert (Simple.empty());
Simple.notify(this, tmp);
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimpleNoSender);
Simple -= delegate(this, &BasicEventTest::onSimpleNoSender);
Simple.notify(this, tmp);
assert (_count == 0);
ConstSimple += delegate(this, &BasicEventTest::onConstSimple);
ConstSimple -= delegate(this, &BasicEventTest::onConstSimple);
ConstSimple.notify(this, tmp);
assert (_count == 0);
//Note: passing &args will not work due to &
EventArgs* pArgs = &args;
Complex += delegate(this, &BasicEventTest::onComplex);
Complex -= delegate(this, &BasicEventTest::onComplex);
Complex.notify(this, pArgs);
assert (_count == 0);
Complex2 += delegate(this, &BasicEventTest::onComplex2);
Complex2 -= delegate(this, &BasicEventTest::onComplex2);
Complex2.notify(this, args);
assert (_count == 0);
const EventArgs* pCArgs = &args;
ConstComplex += delegate(this, &BasicEventTest::onConstComplex);
ConstComplex -= delegate(this, &BasicEventTest::onConstComplex);
ConstComplex.notify(this, pCArgs);
assert (_count == 0);
Const2Complex += delegate(this, &BasicEventTest::onConst2Complex);
Const2Complex -= delegate(this, &BasicEventTest::onConst2Complex);
Const2Complex.notify(this, pArgs);
assert (_count == 0);
Simple += delegate(&BasicEventTest::onStaticSimple);
Simple += delegate(&BasicEventTest::onStaticSimple);
Simple += delegate(&BasicEventTest::onStaticSimple2);
Simple += delegate(&BasicEventTest::onStaticSimple3);
Simple.notify(this, tmp);
assert (_count == 3);
Simple -= delegate(BasicEventTest::onStaticSimple);
Void += delegate(&BasicEventTest::onStaticVoid);
Void += delegate(&BasicEventTest::onStaticVoid);
Void.notify(this);
assert (_count == 5);
Void -= delegate(BasicEventTest::onStaticVoid);
}
void BasicEventTest::testSingleDelegate()
{
int tmp = 0;
EventArgs args;
assert (_count == 0);
Void += delegate(this, &BasicEventTest::onVoid);
Void.notify(this);
assert (_count == 1);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assert (_count == 2);
ConstSimple += delegate(this, &BasicEventTest::onConstSimple);
ConstSimple.notify(this, tmp);
assert (_count == 3);
EventArgs* pArgs = &args;
Complex += delegate(this, &BasicEventTest::onComplex);
Complex.notify(this, pArgs);
assert (_count == 4);
Complex2 += delegate(this, &BasicEventTest::onComplex2);
Complex2.notify(this, args);
assert (_count == 5);
const EventArgs* pCArgs = &args;
ConstComplex += delegate(this, &BasicEventTest::onConstComplex);
ConstComplex.notify(this, pCArgs);
assert (_count == 6);
Const2Complex += delegate(this, &BasicEventTest::onConst2Complex);
Const2Complex.notify(this, pArgs);
assert (_count == 7);
// check if 2nd notify also works
Const2Complex.notify(this, pArgs);
assert (_count == 8);
}
void BasicEventTest::testDuplicateRegister()
{
int tmp = 0;
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assert (_count == 2);
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assert (_count == 3);
}
void BasicEventTest::testNullMutex()
{
Poco::BasicEvent<int, NullMutex> ev;
int tmp = 0;
assert (_count == 0);
ev += delegate(this, &BasicEventTest::onSimple);
ev += delegate(this, &BasicEventTest::onSimple);
ev.notify(this, tmp);
assert (_count == 2);
ev -= delegate(this, &BasicEventTest::onSimple);
ev.notify(this, tmp);
assert (_count == 3);
}
void BasicEventTest::testDuplicateUnregister()
{
// duplicate unregister shouldn't give an error,
int tmp = 0;
assert (_count == 0);
Simple -= delegate(this, &BasicEventTest::onSimple); // should work
Simple.notify(this, tmp);
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assert (_count == 1);
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assert (_count == 1);
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assert (_count == 1);
}
void BasicEventTest::testDisabling()
{
int tmp = 0;
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.disable();
Simple.notify(this, tmp);
assert (_count == 0);
Simple.enable();
Simple.notify(this, tmp);
assert (_count == 1);
// unregister should also work with disabled event
Simple.disable();
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.enable();
Simple.notify(this, tmp);
assert (_count == 1);
}
void BasicEventTest::testExpire()
{
int tmp = 0;
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple, 500);
Simple.notify(this, tmp);
assert (_count == 1);
Poco::Thread::sleep(700);
Simple.notify(this, tmp);
assert (_count == 1);
Simple += delegate(&BasicEventTest::onStaticSimple, 400);
Simple += delegate(&BasicEventTest::onStaticSimple, 400);
Simple += delegate(&BasicEventTest::onStaticSimple2, 400);
Simple += delegate(&BasicEventTest::onStaticSimple3, 400);
Simple.notify(this, tmp);
assert (_count == 4);
Poco::Thread::sleep(700);
Simple.notify(this, tmp);
assert (_count == 4);
}
void BasicEventTest::testExpireReRegister()
{
int tmp = 0;
assert (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple, 500);
Simple.notify(this, tmp);
assert (_count == 1);
Poco::Thread::sleep(200);
Simple.notify(this, tmp);
assert (_count == 2);
// renew registration
Simple += delegate(this, &BasicEventTest::onSimple, 600);
Poco::Thread::sleep(400);
Simple.notify(this, tmp);
assert (_count == 3);
Poco::Thread::sleep(300);
Simple.notify(this, tmp);
assert (_count == 3);
}
void BasicEventTest::testReturnParams()
{
DummyDelegate o1;
Simple += delegate(&o1, &DummyDelegate::onSimple);
int tmp = 0;
Simple.notify(this, tmp);
assert (tmp == 1);
}
void BasicEventTest::testOverwriteDelegate()
{
DummyDelegate o1;
Simple += delegate(&o1, &DummyDelegate::onSimple);
Simple += delegate(&o1, &DummyDelegate::onSimple2);
int tmp = 0; // onsimple requires 0 as input
Simple.notify(this, tmp);
assert (tmp == 2);
}
void BasicEventTest::testAsyncNotify()
{
Poco::BasicEvent<int>* pSimple= new Poco::BasicEvent<int>();
(*pSimple) += delegate(this, &BasicEventTest::onAsync);
assert (_count == 0);
int tmp = 0;
Poco::ActiveResult<int>retArg = pSimple->notifyAsync(this, tmp);
delete pSimple; // must work even when the event got deleted!
pSimple = NULL;
assert (_count == 0);
retArg.wait();
assert (retArg.data() == tmp);
assert (_count == LARGEINC);
}
void BasicEventTest::onStaticVoid(const void* pSender)
{
BasicEventTest* p = const_cast<BasicEventTest*>(reinterpret_cast<const BasicEventTest*>(pSender));
p->_count++;
}
void BasicEventTest::onVoid(const void* pSender)
{
_count++;
}
void BasicEventTest::onSimpleNoSender(int& i)
{
_count++;
}
void BasicEventTest::onSimple(const void* pSender, int& i)
{
_count++;
}
void BasicEventTest::onStaticSimple(const void* pSender, int& i)
{
BasicEventTest* p = const_cast<BasicEventTest*>(reinterpret_cast<const BasicEventTest*>(pSender));
p->_count++;
}
void BasicEventTest::onStaticSimple2(void* pSender, int& i)
{
BasicEventTest* p = reinterpret_cast<BasicEventTest*>(pSender);
p->_count++;
}
void BasicEventTest::onStaticSimple3(int& i)
{
}
void BasicEventTest::onSimpleOther(const void* pSender, int& i)
{
_count+=100;
}
void BasicEventTest::onConstSimple(const void* pSender, const int& i)
{
_count++;
}
void BasicEventTest::onComplex(const void* pSender, Poco::EventArgs* & i)
{
_count++;
}
void BasicEventTest::onComplex2(const void* pSender, Poco::EventArgs & i)
{
_count++;
}
void BasicEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i)
{
_count++;
}
void BasicEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i)
{
_count++;
}
void BasicEventTest::onAsync(const void* pSender, int& i)
{
Poco::Thread::sleep(700);
_count += LARGEINC ;
}
int BasicEventTest::getCount() const
{
return _count;
}
void BasicEventTest::setUp()
{
_count = 0;
// must clear events, otherwise repeating test executions will fail
// because tests are only created once, only setup is called before
// each test run
Void.clear();
Simple.clear();
ConstSimple.clear();
Complex.clear();
Complex2.clear();
ConstComplex.clear();
Const2Complex.clear();
}
void BasicEventTest::tearDown()
{
}
CppUnit::Test* BasicEventTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BasicEventTest");
CppUnit_addTest(pSuite, BasicEventTest, testNoDelegate);
CppUnit_addTest(pSuite, BasicEventTest, testSingleDelegate);
CppUnit_addTest(pSuite, BasicEventTest, testReturnParams);
CppUnit_addTest(pSuite, BasicEventTest, testDuplicateRegister);
CppUnit_addTest(pSuite, BasicEventTest, testDuplicateUnregister);
CppUnit_addTest(pSuite, BasicEventTest, testDisabling);
CppUnit_addTest(pSuite, BasicEventTest, testExpire);
CppUnit_addTest(pSuite, BasicEventTest, testExpireReRegister);
CppUnit_addTest(pSuite, BasicEventTest, testOverwriteDelegate);
CppUnit_addTest(pSuite, BasicEventTest, testAsyncNotify);
CppUnit_addTest(pSuite, BasicEventTest, testNullMutex);
return pSuite;
}
| 23.913832
| 99
| 0.714868
|
189569400
|
f5958c43110a7b5d25be2c39fe2e1e008476944d
| 842
|
cpp
|
C++
|
java/app/src/main/cpp/CXSparse/Source/cs_cholsol_ci.cpp
|
thatmooglie/epilepsy-detection
|
8d9b4451190db5ba9781a19d0c97b9a411fbb8d6
|
[
"MIT"
] | 28
|
2020-03-12T03:25:30.000Z
|
2022-02-21T07:22:44.000Z
|
java/app/src/main/cpp/CXSparse/Source/cs_cholsol_ci.cpp
|
thatmooglie/epilepsy-detection
|
8d9b4451190db5ba9781a19d0c97b9a411fbb8d6
|
[
"MIT"
] | 2
|
2020-05-07T18:13:58.000Z
|
2021-01-07T20:26:00.000Z
|
java/app/src/main/cpp/CXSparse/Source/cs_cholsol_ci.cpp
|
thatmooglie/epilepsy-detection
|
8d9b4451190db5ba9781a19d0c97b9a411fbb8d6
|
[
"MIT"
] | 10
|
2020-04-10T02:14:39.000Z
|
2021-01-17T14:00:53.000Z
|
#include "cs.h"
/* x=A\b where A is symmetric positive definite; b overwritten with solution */
CS_INT cs_cholsol(CS_INT order, const cs* A, CS_ENTRY* b) {
CS_ENTRY* x;
css* S;
csn* N;
CS_INT n, ok;
if (!CS_CSC(A) || !b) {
return (0);
} /* check inputs */
n = A->n;
S = cs_schol(order, A); /* ordering and symbolic analysis */
N = cs_chol(A, S); /* numeric Cholesky factorization */
x = (CS_ENTRY*)cs_malloc(n, sizeof(CS_ENTRY)); /* get workspace */
ok = (S && N && x);
if (ok) {
cs_ipvec(S->pinv, b, x, n); /* x = P*b */
cs_lsolve(N->L, x); /* x = L\x */
cs_ltsolve(N->L, x); /* x = L'\x */
cs_pvec(S->pinv, x, b, n); /* b = P'*x */
}
cs_free(x);
cs_sfree(S);
cs_nfree(N);
return (ok);
}
| 31.185185
| 79
| 0.483373
|
thatmooglie
|
f595936fa2415f4fd4f84723cd7ca17c1f20799a
| 234
|
cc
|
C++
|
simple-test-program/test.cc
|
gusenov/examples-gtest
|
4c2da11aea2d114fe5f7a33c84aed6495b4aaa19
|
[
"MIT"
] | 1
|
2021-12-25T21:35:54.000Z
|
2021-12-25T21:35:54.000Z
|
simple-test-program/test.cc
|
gusenov/examples-gtest
|
4c2da11aea2d114fe5f7a33c84aed6495b4aaa19
|
[
"MIT"
] | null | null | null |
simple-test-program/test.cc
|
gusenov/examples-gtest
|
4c2da11aea2d114fe5f7a33c84aed6495b4aaa19
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include <string>
TEST(FooTest, Foo) {
std::string foo("foo");
EXPECT_STREQ("foo", foo.c_str());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 18
| 41
| 0.653846
|
gusenov
|
f5961e8f0d68ed56253795151ded30646697bee3
| 887
|
cpp
|
C++
|
Source/moja.datarepository/tests/src/landunitinfotests.cpp
|
YevenLourance/FLINT
|
e584e39c36d3e898c9293c09bd0768557312e8ea
|
[
"BSL-1.0"
] | null | null | null |
Source/moja.datarepository/tests/src/landunitinfotests.cpp
|
YevenLourance/FLINT
|
e584e39c36d3e898c9293c09bd0768557312e8ea
|
[
"BSL-1.0"
] | null | null | null |
Source/moja.datarepository/tests/src/landunitinfotests.cpp
|
YevenLourance/FLINT
|
e584e39c36d3e898c9293c09bd0768557312e8ea
|
[
"BSL-1.0"
] | null | null | null |
#include <moja/datarepository/landunitinfo.h>
#include <moja/test/mockaspatialtileinfo.h>
#include <boost/test/unit_test.hpp>
using moja::datarepository::LandUnitInfo;
using moja::test::MockAspatialTileInfo;
BOOST_AUTO_TEST_SUITE(LandUnitInfoTests);
BOOST_AUTO_TEST_CASE(datarepository_LandUnitInfo_ConstructorThrowsExceptionIfIdIsLessThanOne) {
MockAspatialTileInfo mockTile;
auto badIds = {0, -1, -100};
for (auto id : badIds) {
BOOST_CHECK_THROW(LandUnitInfo(mockTile, id, 1.0), std::invalid_argument);
}
}
BOOST_AUTO_TEST_CASE(datarepository_LandUnitInfo_ConstructorThrowsExceptionIfAreaIsZeroOrNegative) {
MockAspatialTileInfo mockTile;
auto badAreas = {0.0, -0.1, -100.0};
for (auto area : badAreas) {
BOOST_CHECK_THROW(LandUnitInfo(mockTile, 1, area), std::invalid_argument);
}
}
BOOST_AUTO_TEST_SUITE_END();
| 30.586207
| 101
| 0.750846
|
YevenLourance
|
f59645bf0540bba3ebef773575b6b8a761f92080
| 12,541
|
cpp
|
C++
|
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateCoilCoolingDXTwoSpeed.cpp
|
ORNL-BTRIC/OpenStudio
|
878f94bebf6f025445d1373e8b2304ececac16d8
|
[
"blessing"
] | null | null | null |
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateCoilCoolingDXTwoSpeed.cpp
|
ORNL-BTRIC/OpenStudio
|
878f94bebf6f025445d1373e8b2304ececac16d8
|
[
"blessing"
] | null | null | null |
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateCoilCoolingDXTwoSpeed.cpp
|
ORNL-BTRIC/OpenStudio
|
878f94bebf6f025445d1373e8b2304ececac16d8
|
[
"blessing"
] | null | null | null |
/**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <energyplus/ForwardTranslator.hpp>
#include <model/Model.hpp>
#include <model/Schedule.hpp>
#include <model/Schedule_Impl.hpp>
#include <model/CoilCoolingDXTwoSpeed.hpp>
#include <model/CoilCoolingDXTwoSpeed_Impl.hpp>
#include <model/Curve.hpp>
#include <model/Curve_Impl.hpp>
#include <utilities/core/Logger.hpp>
#include <utilities/core/Assert.hpp>
#include <utilities/idd/CoilSystem_Cooling_DX_FieldEnums.hxx>
#include <utilities/idd/Coil_Cooling_DX_TwoSpeed_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
using namespace openstudio::model;
using namespace std;
namespace openstudio {
namespace energyplus {
boost::optional<IdfObject> ForwardTranslator::translateCoilCoolingDXTwoSpeedWithoutUnitary( model::CoilCoolingDXTwoSpeed & modelObject )
{
//setup two boost optionals to use to store get method returns
boost::optional<std::string> s;
boost::optional<double> d;
//create the IdfObject that will be the coil
IdfObject idfObject(IddObjectType::Coil_Cooling_DX_TwoSpeed);
//Name
m_idfObjects.push_back(idfObject);
s = modelObject.name();
if( s )
{
idfObject.setName(*s);
}
// A2 , \field Availability Schedule Name
Schedule sched = modelObject.getAvailabilitySchedule();
translateAndMapModelObject(sched);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AvailabilityScheduleName,
sched.name().get() );
// N1 , \field Rated High Speed Total Cooling Capacity
d = modelObject.getRatedHighSpeedTotalCoolingCapacity();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedGrossRatedTotalCoolingCapacity,*d);
}
else
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::HighSpeedGrossRatedTotalCoolingCapacity,"Autosize");
}
// N2 , \field Rated High Speed Sensible Heat Ratio
d = modelObject.getRatedHighSpeedSensibleHeatRatio();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedSensibleHeatRatio,*d);
}
else
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedSensibleHeatRatio,"Autosize");
}
// N3 , \field Rated High Speed COP
d = modelObject.getRatedHighSpeedCOP();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedGrossRatedCoolingCOP,*d);
}
// N4 , \field Rated High Speed Air Flow Rate
d = modelObject.getRatedHighSpeedAirFlowRate();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedAirFlowRate,*d);
}
else
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedAirFlowRate,"Autosize");
}
//A3 , \field Air Inlet Node Name
OptionalModelObject omo = modelObject.inletModelObject();
if( omo )
{
translateAndMapModelObject(*omo);
s = omo->name();
if(s)
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AirInletNodeName,*s );
}
}
//A4 , \field Air Outlet Node Name
omo= modelObject.outletModelObject();
if( omo )
{
translateAndMapModelObject(*omo);
s = omo->name();
if(s)
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AirOutletNodeName,*s);
}
}
// A5 , \field Total Cooling Capacity Function of Temperature Curve Name
Curve cb = modelObject.getTotalCoolingCapacityFunctionOfTemperatureCurve();
translateAndMapModelObject(cb);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::TotalCoolingCapacityFunctionofTemperatureCurveName,
cb.name().get());
// A6 , \field Total Cooling Capacity Function of Flow Fraction Curve Name
cb = modelObject.getTotalCoolingCapacityFunctionOfFlowFractionCurve();
translateAndMapModelObject(cb);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::TotalCoolingCapacityFunctionofFlowFractionCurveName,
cb.name().get());
// A7 , \field Energy Input Ratio Function of Temperature Curve Name
cb =modelObject.getEnergyInputRatioFunctionOfTemperatureCurve();
translateAndMapModelObject(cb);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::EnergyInputRatioFunctionofTemperatureCurveName,
cb.name().get());
// A8 , \field Energy Input Ratio Function of Flow Fraction Curve Name
Curve cq = modelObject.getEnergyInputRatioFunctionOfFlowFractionCurve();
translateAndMapModelObject(cq);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::EnergyInputRatioFunctionofFlowFractionCurveName,
cq.name().get());
// A9 , \field Part Load Fraction Correlation Curve Name
cq = modelObject.getPartLoadFractionCorrelationCurve();
translateAndMapModelObject(cq);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::PartLoadFractionCorrelationCurveName,
cq.name().get());
// N5 , \field Rated Low Speed Total Cooling Capacity
d = modelObject.getRatedLowSpeedTotalCoolingCapacity();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedTotalCoolingCapacity,*d);
}
else
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedTotalCoolingCapacity,"Autosize");
}
// N6 , \field Rated Low Speed Sensible Heat Ratio
d = modelObject.getRatedLowSpeedSensibleHeatRatio();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedSensibleHeatRatio,*d);
}
else
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedSensibleHeatRatio,"Autosize");
}
// N7 , \field Rated Low Speed COP
d = modelObject.getRatedLowSpeedCOP();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedCoolingCOP,*d);
}
// N8 , \field Rated Low Speed Air Flow Rate
d = modelObject.getRatedLowSpeedAirFlowRate();
if( d )
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedRatedAirFlowRate,*d);
}
else
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedRatedAirFlowRate,"Autosize");
}
// A10, \field Low Speed Total Cooling Capacity Function of Temperature Curve Name
cq = modelObject.getLowSpeedTotalCoolingCapacityFunctionOfTemperatureCurve();
translateAndMapModelObject(cq);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedTotalCoolingCapacityFunctionofTemperatureCurveName,
cq.name().get());
// A11, \field Low Speed Energy Input Ratio Function of Temperature Curve Name
cq = modelObject.getLowSpeedEnergyInputRatioFunctionOfTemperatureCurve();
translateAndMapModelObject(cq);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEnergyInputRatioFunctionofTemperatureCurveName,
cq.name().get());
// A12, \field Condenser Air Inlet Node Name
s=modelObject.getCondenserAirInletNodeName();
if(s)
{
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::CondenserAirInletNodeName,*s);
}
// A13, \field Condenser Type
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::CondenserType,modelObject.getCondenserType());
// N9, \field High Speed Evaporative Condenser Effectiveness
d=modelObject.getHighSpeedEvaporativeCondenserEffectiveness();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserEffectiveness,*d);
}
// N10, \field High Speed Evaporative Condenser Air Flow Rate
d=modelObject.getHighSpeedEvaporativeCondenserAirFlowRate();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserAirFlowRate,*d);
}
// N11, \field High Speed Evaporative Condenser Pump Rated Power Consumption
d=modelObject.getHighSpeedEvaporativeCondenserPumpRatedPowerConsumption();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserPumpRatedPowerConsumption,*d);
}
// N12, \field Low Speed Evaporative Condenser Effectiveness
d=modelObject.getLowSpeedEvaporativeCondenserEffectiveness();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserEffectiveness,*d);
}
// N13, \field Low Speed Evaporative Condenser Air Flow Rate
d=modelObject.getLowSpeedEvaporativeCondenserAirFlowRate();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserAirFlowRate,*d);
}
// N14, \field Low Speed Evaporative Condenser Pump Rated Power Consumption
d=modelObject.getLowSpeedEvaporativeCondenserPumpRatedPowerConsumption();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserPumpRatedPowerConsumption,*d);
}
//TODO
// A14, \field Supply Water Storage Tank Name
//getSupplyWaterStorageTankName
//TODO
// A15, \field Condensate Collection Water Storage Tank Name
//getCondensateCollectionWaterStorageTankName
// N15, \field Basin Heater Capacity
d=modelObject.getBasinHeaterCapacity();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterCapacity,*d);
}
// N16, \field Basin Heater Setpoint Temperature
d=modelObject.getBasinHeaterSetpointTemperature();
if(d)
{
idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterSetpointTemperature,*d);
}
// A16; \field Basin Heater Operating Schedule Name
OptionalSchedule os = modelObject.getBasinHeaterOperatingSchedule();
if( os )
{
translateAndMapModelObject(*os);
idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterOperatingScheduleName,
os->name().get() );
}
return idfObject;
}
boost::optional<IdfObject> ForwardTranslator::translateCoilCoolingDXTwoSpeed( CoilCoolingDXTwoSpeed& modelObject )
{
IdfObject coilSystemCoolingDXIdf(IddObjectType::CoilSystem_Cooling_DX);
m_idfObjects.push_back(coilSystemCoolingDXIdf);
boost::optional<IdfObject> oIdfObject = translateCoilCoolingDXTwoSpeedWithoutUnitary(modelObject);
if( ! oIdfObject ) { return boost::none; }
IdfObject idfObject = oIdfObject.get();
OptionalString s;
s = modelObject.name();
if( s )
{
coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::CoolingCoilObjectType,idfObject.iddObject().name());
coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::CoolingCoilName,*s);
coilSystemCoolingDXIdf.setName(*s + " CoilSystem");
}
Schedule sched = modelObject.getAvailabilitySchedule();
translateAndMapModelObject(sched);
coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::AvailabilityScheduleName,sched.name().get());
OptionalModelObject omo = modelObject.inletModelObject();
if( omo )
{
translateAndMapModelObject(*omo);
s = omo->name();
if(s)
{
coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::DXCoolingCoilSystemInletNodeName,*s);
}
}
omo= modelObject.outletModelObject();
if( omo )
{
translateAndMapModelObject(*omo);
s = omo->name();
if(s)
{
coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::DXCoolingCoilSystemOutletNodeName,*s);
coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::DXCoolingCoilSystemSensorNodeName,*s);
}
}
return coilSystemCoolingDXIdf;
}
} // energyplus
} // openstudio
| 35.030726
| 137
| 0.728889
|
ORNL-BTRIC
|
f5973e76be760ccb5431975049488c77d9bf4592
| 638
|
cpp
|
C++
|
DATA STRUCTURES/Array/Kth Smallest Element/code_1.cpp
|
Jatin-Goyal5/Data-Structures-and-Algorithms
|
f6bd0f77e5640c2e0568f3fffc4694758e77af96
|
[
"MIT"
] | 27
|
2019-01-31T10:22:29.000Z
|
2021-08-29T08:25:12.000Z
|
DATA STRUCTURES/Array/Kth Smallest Element/code_1.cpp
|
Jatin-Goyal5/Data-Structures-and-Algorithms
|
f6bd0f77e5640c2e0568f3fffc4694758e77af96
|
[
"MIT"
] | 6
|
2020-09-30T19:01:49.000Z
|
2020-12-17T15:10:54.000Z
|
DATA STRUCTURES/Array/Kth Smallest Element/code_1.cpp
|
Jatin-Goyal5/Data-Structures-and-Algorithms
|
f6bd0f77e5640c2e0568f3fffc4694758e77af96
|
[
"MIT"
] | 27
|
2019-09-21T14:19:32.000Z
|
2021-09-15T03:06:41.000Z
|
//
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
using namespace std;
int kthSmallest(int arr[], int n, int k) {
sort(arr, arr+n);
return arr[k-1];
}
int main() {
int n;
cout << "\nEnter Size\t:\t";
cin >> n;
int *a = new int[n];
cout << "\nEnter Array Elements\n";
for ( int i = 0; i < n; i++ ) {
cin >> a[i];
}
int k;
cout << "Enter K\t:\t";
cin >> k;
cout << "\nKth Smallest Element\t:\t" << kthSmallest( a , n , k ) << endl;
delete[] a;
return 0;
}
| 18.764706
| 78
| 0.523511
|
Jatin-Goyal5
|
60d6724ded3faac6c89df2a481c3676b9c87b110
| 925
|
cpp
|
C++
|
unique-binary-search-trees-ii/solution-0.cpp
|
tsenmu/leetcode
|
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
|
[
"Apache-2.0"
] | null | null | null |
unique-binary-search-trees-ii/solution-0.cpp
|
tsenmu/leetcode
|
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
|
[
"Apache-2.0"
] | null | null | null |
unique-binary-search-trees-ii/solution-0.cpp
|
tsenmu/leetcode
|
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
|
[
"Apache-2.0"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<TreeNode*> constructTree(int l, int r) {
vector<TreeNode*> ans;
if (l > r) {
ans.push_back(NULL);
return ans;
}
for (int i = l; i <= r; ++i) {
vector<TreeNode*> leftNodes = constructTree(l, i - 1);
vector<TreeNode*> rightNodes = constructTree(i + 1, r);
for (int li = 0; li < leftNodes.size(); ++li) {
for (int ri = 0; ri < rightNodes.size(); ++ri) {
TreeNode* root = new TreeNode(i);
root->left = leftNodes[li];
root->right = rightNodes[ri];
ans.push_back(root);
}
}
}
return ans;
}
public:
vector<TreeNode*> generateTrees(int n) {
return constructTree(1, n);
}
};
| 25.694444
| 61
| 0.537297
|
tsenmu
|
60d826675a40b7b77af03c245ec391d50e0c87d9
| 4,925
|
hpp
|
C++
|
dependencies/cpp/boost/container/detail/node_pool.hpp
|
fduffy/QuantLibAdjoint
|
d9d355db4f46824bb5e607e28381943aef994ed4
|
[
"BSD-3-Clause"
] | 41
|
2016-03-19T02:31:54.000Z
|
2022-01-20T13:23:20.000Z
|
dependencies/cpp/boost/container/detail/node_pool.hpp
|
fduffy/QuantLibAdjoint
|
d9d355db4f46824bb5e607e28381943aef994ed4
|
[
"BSD-3-Clause"
] | 4
|
2017-07-18T21:17:45.000Z
|
2020-09-17T02:54:52.000Z
|
dependencies/cpp/boost/container/detail/node_pool.hpp
|
fduffy/QuantLibAdjoint
|
d9d355db4f46824bb5e607e28381943aef994ed4
|
[
"BSD-3-Clause"
] | 22
|
2016-03-17T14:14:36.000Z
|
2022-03-28T10:33:19.000Z
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_HPP
#define BOOST_CONTAINER_DETAIL_NODE_POOL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
#include <boost/container/detail/mutex.hpp>
#include <boost/container/detail/pool_common_alloc.hpp>
#include <boost/container/detail/node_pool_impl.hpp>
#include <boost/container/detail/mutex.hpp>
#include <boost/intrusive/slist.hpp>
#include <boost/move/utility_core.hpp>
#include <cstddef>
#include <functional> //std::unary_function
#include <algorithm> //std::swap
#include <cassert>
namespace boost {
namespace container {
namespace container_detail {
//!Pooled memory allocator using single segregated storage. Includes
//!a reference count but the class does not delete itself, this is
//!responsibility of user classes. Node size (NodeSize) and the number of
//!nodes allocated per block (NodesPerBlock) are known at compile time
template< std::size_t NodeSize, std::size_t NodesPerBlock >
class private_node_pool
//Inherit from the implementation to avoid template bloat
: public boost::container::container_detail::
private_node_pool_impl<fake_segment_manager>
{
typedef boost::container::container_detail::
private_node_pool_impl<fake_segment_manager> base_t;
//Non-copyable
private_node_pool(const private_node_pool &);
private_node_pool &operator=(const private_node_pool &);
public:
typedef typename base_t::multiallocation_chain multiallocation_chain;
static const std::size_t nodes_per_block = NodesPerBlock;
//!Constructor from a segment manager. Never throws
private_node_pool()
: base_t(0, NodeSize, NodesPerBlock)
{}
};
template< std::size_t NodeSize
, std::size_t NodesPerBlock
>
class shared_node_pool
: public private_node_pool<NodeSize, NodesPerBlock>
{
private:
typedef private_node_pool<NodeSize, NodesPerBlock> private_node_allocator_t;
public:
typedef typename private_node_allocator_t::free_nodes_t free_nodes_t;
typedef typename private_node_allocator_t::multiallocation_chain multiallocation_chain;
//!Constructor from a segment manager. Never throws
shared_node_pool()
: private_node_allocator_t(){}
//!Destructor. Deallocates all allocated blocks. Never throws
~shared_node_pool()
{}
//!Allocates array of count elements. Can throw std::bad_alloc
void *allocate_node()
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
return private_node_allocator_t::allocate_node();
}
//!Deallocates an array pointed by ptr. Never throws
void deallocate_node(void *ptr)
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
private_node_allocator_t::deallocate_node(ptr);
}
//!Allocates a singly linked list of n nodes ending in null pointer.
//!can throw std::bad_alloc
void allocate_nodes(const std::size_t n, multiallocation_chain &chain)
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
return private_node_allocator_t::allocate_nodes(n, chain);
}
void deallocate_nodes(multiallocation_chain &chain)
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
private_node_allocator_t::deallocate_nodes(chain);
}
//!Deallocates all the free blocks of memory. Never throws
void deallocate_free_blocks()
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
private_node_allocator_t::deallocate_free_blocks();
}
//!Deallocates all blocks. Never throws
void purge_blocks()
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
private_node_allocator_t::purge_blocks();
}
std::size_t num_free_nodes()
{
//-----------------------
scoped_lock<default_mutex> guard(mutex_);
//-----------------------
return private_node_allocator_t::num_free_nodes();
}
private:
default_mutex mutex_;
};
} //namespace container_detail {
} //namespace container {
} //namespace boost {
#include <boost/container/detail/config_end.hpp>
#endif //#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_HPP
| 31.369427
| 90
| 0.655431
|
fduffy
|
60d82f9ea1605997d1fa082bb16e6bc9a8d02a9a
| 7,234
|
cpp
|
C++
|
hmi_sdk/UIShare/UI/Slider/Slider.cpp
|
APCVSRepo/android_packet
|
5d4237234656b777cd9b0cae4731afea51986582
|
[
"BSD-3-Clause"
] | 4
|
2016-09-21T12:36:24.000Z
|
2020-10-29T01:45:03.000Z
|
hmi_sdk/UIShare/UI/Slider/Slider.cpp
|
APCVSRepo/android_packet
|
5d4237234656b777cd9b0cae4731afea51986582
|
[
"BSD-3-Clause"
] | 7
|
2016-06-01T01:21:44.000Z
|
2017-11-03T08:18:23.000Z
|
hmi_sdk/UIShare/UI/Slider/Slider.cpp
|
APCVSRepo/android_packet
|
5d4237234656b777cd9b0cae4731afea51986582
|
[
"BSD-3-Clause"
] | 8
|
2017-08-29T10:51:50.000Z
|
2021-03-24T10:19:11.000Z
|
#include "Slider.h"
#include "QHBoxLayout"
#include "QVBoxLayout"
#include "UI/Config/Config.h"
#include "Common/AppBase.h"
Slider::Slider(AppListInterface * pList, QWidget *parent) :
AppBase(pList, parent),m_iPos(0),m_bDynamic(false)
{
InitLayout();
connect(&m_timer,SIGNAL(timeout()),this,SLOT(timeoutSlots()));
connect(this,SIGNAL(sliderClicked(int,int)),this,SLOT(sliderClickedSlots(int,int)));
connect(this, SIGNAL(onSpaceCliced()), this, SLOT(onButtonCancelClicked()));
}
Slider::~Slider()
{
delete m_labelText1;
delete m_labelText2;
delete m_labelText3;
delete m_btnSoft1;
delete m_btnSoft2;
delete m_btnSoft3;
delete m_btnSoft4;
}
void Slider::InitLayout()
{
m_labelText1 = new QLabel;
m_labelText2 = new QLabel;
m_labelText3 = new QLabel;
m_btnSoft1 = new CButton;
m_btnSoft2 = new CButton;
m_btnSoft3 = new CButton;
m_btnSoft4 = new CButton;
QHBoxLayout *btnLayout = new QHBoxLayout;
QVBoxLayout *mLayout = new QVBoxLayout(this);
btnLayout->addWidget(m_btnSoft1, 25);
btnLayout->addWidget(m_btnSoft2, 25);
btnLayout->addWidget(m_btnSoft3, 25);
btnLayout->addWidget(m_btnSoft4, 25);
mLayout->addWidget(m_labelText1, 24);
mLayout->addWidget(m_labelText2, 24);
mLayout->addWidget(m_labelText3, 24);
mLayout->addLayout(btnLayout, 23);
mLayout->addStretch(5);
mLayout->setMargin(0);
connect(m_btnSoft1, SIGNAL(clicked()), this, SLOT(onButtonSaveClicked()));
connect(m_btnSoft2, SIGNAL(clicked()), this, SLOT(onMoveLeftSlot()));
connect(m_btnSoft3, SIGNAL(clicked()), this, SLOT(onMoveRightSlot()));
connect(m_btnSoft4, SIGNAL(clicked()), this, SLOT(onButtonCancelClicked()));
// m_labelBackground.setGeometry((this->width() - iW) / 2, 0.85 * this->height() - iH, iW, iH);
// m_labelFrame.setGeometry((this->width() - iW) / 2, 0.85 * this->height() - iH, iW, iH);
m_labelText1->setStyleSheet("border:0px;font: 45px \"Liberation Serif\";color:rgb(255,255,254)");
m_labelText2->setStyleSheet("border:0px;font: 45px \"Liberation Serif\";color:rgb(255,255,254)");
m_labelText3->setStyleSheet("border:0px;font: 45px \"Liberation Serif\";color:rgb(255,255,254)");
m_labelText1->setAlignment(Qt::AlignCenter);
m_labelText2->setAlignment(Qt::AlignCenter);
m_labelText3->setAlignment(Qt::AlignCenter);
// //test
// QString tmp[5] = {"Hello", "Jack", "Moky", "Luckey", "Mono"};
// setSliderStrings(tmp, 5, 1);
// setSliderTitle("Test string.");
// setPosition(3);
m_btnSoft1->setTextStyle("border:0px;font: 42px \"Liberation Serif\";color:rgb(255,255,254)");
m_btnSoft2->setTextStyle("border:0px;font: 42px \"Liberation Serif\";color:rgb(255,255,254)");
m_btnSoft3->setTextStyle("border:0px;font: 42px \"Liberation Serif\";color:rgb(255,255,254)");
m_btnSoft4->setTextStyle("border:0px;font: 42px \"Liberation Serif\";color:rgb(255,255,254)");
m_btnSoft1->initParameter(ui_aler_width, ui_aler_height, ":/images/softbutton_alert.png", ":/images/softbutton_alert.png");
m_btnSoft2->initParameter(ui_aler_width, ui_aler_height, ":/images/softbutton_alert_left.png", ":/images/softbutton_alert_left.png", "", "");
m_btnSoft2->setIconExtra(":/images/leftarrow.png");
m_btnSoft3->initParameter(ui_aler_width, ui_aler_height, ":/images/softbutton_alert_right.png", ":/images/softbutton_alert_right.png", "", "");
m_btnSoft3->setIconExtra(":/images/rightarrow.png");
m_btnSoft4->initParameter(ui_aler_width, ui_aler_height, ":/images/softbutton_alert.png", ":/images/softbutton_alert.png");
// m_labelFrame.setLayout(mLayout);
//this->setLayout(mLayout);
m_btnSoft1->setText("-");
m_btnSoft4->setText("-");
}
void Slider::sliderClickedSlots( int code, int sliderPosition)
{
if(AppControl)
{
AppControl->OnSliderResponse(code, sliderPosition+1);
}
}
void Slider::onMoveLeftSlot()
{
if (m_iPos > 0)
{
m_iPos--;
updateScreen();
}
}
void Slider::onMoveRightSlot()
{
if (m_iPos < m_Strings.size() - 1)
{
m_iPos++;
updateScreen();
}
}
void Slider::setSliderTitle(QString text)
{
SetEdlidedText(m_labelText1,text,width());
}
//void Slider::setSliderStrings(QString* pStr, int iCnt, int iPos)
void Slider::setSliderStrings(std::vector<std::string> vec_strSliter, int iPos)
{
m_Strings.clear();
for (int i = 0; i < vec_strSliter.size(); i++)
{
m_Strings.push_back(vec_strSliter.at(i).data());
}
m_iPos = iPos-1;
updateScreen();
}
bool Slider::setPosition(int iPos)
{
if (iPos < 0 || iPos >= m_Strings.size())
{
return false;
}
m_iPos = iPos;
updateScreen();
return true;
}
void Slider::updateScreen()
{
m_timer.stop();
m_timer.start();
m_EditText.clear();
for (int i = 0; i < m_Strings.size(); i++)
{
if (i == m_iPos)
{
m_EditText.push_back("|");
}
else
{
m_EditText.push_back(".");
}
}
m_labelText2->setText("<" + m_EditText + ">");
if(m_bDynamic)
{
SetEdlidedText(m_labelText3,m_Strings[m_iPos],width());
}
else
{
SetEdlidedText(m_labelText3,m_Strings[0],width());
}
}
void Slider::setTimeOut(int duration)
{
m_timer.setInterval(duration);
m_timer.start();
}
void Slider::timeoutSlots()
{
m_timer.stop();
emit sliderClicked(SLIDER_TIMEOUT, m_iPos);
}
void Slider::onButtonSaveClicked()
{
m_timer.stop();
emit sliderClicked(SLIDER_OK, m_iPos);
}
void Slider::onButtonCancelClicked()
{
m_timer.stop();
emit sliderClicked(SLIDER_ABORTED, m_iPos);
}
void Slider::showEvent(QShowEvent * e)
{
if (AppControl)
{
m_btnSoft1->setText("Save");
m_btnSoft4->setText("Cancel");
Json::Value m_jsonData = AppControl->getSlider();
// this->setAppID(m_jsonData["params"]["appID"].asInt());
this->setTimeOut(m_jsonData["params"]["timeout"].asInt());
int numTicks = m_jsonData["params"]["numTicks"].asInt();
int position = m_jsonData["params"]["position"].asInt();
this->setSliderTitle(m_jsonData["params"]["sliderHeader"].asString().data());
std::vector <std::string > vec_strSliter;
vec_strSliter.clear();
if (m_jsonData["params"].isMember("sliderFooter"))
{
for(int i = 0; i < m_jsonData["params"]["sliderFooter"].size(); i++)
{
vec_strSliter.push_back(m_jsonData["params"]["sliderFooter"][i].asString());
}
}
if(vec_strSliter.size() == 1)
{
m_bDynamic = false;
}
else if(vec_strSliter.size() == numTicks)
{
m_bDynamic = true;
}
while(vec_strSliter.size() < numTicks)
{
vec_strSliter.push_back("-");
}
this->setSliderStrings(vec_strSliter,position);
}
}
| 29.769547
| 148
| 0.621371
|
APCVSRepo
|
60d8989a920e906e24ec3684360cf394dfcf6513
| 47,612
|
cpp
|
C++
|
src/cpu/x64/matmul/brgemm_matmul.cpp
|
cfRod/oneDNN
|
7981216b8341b8603e54472f5a0dd7a12ef9cf67
|
[
"Apache-2.0"
] | 1,327
|
2018-01-25T21:23:47.000Z
|
2020-04-03T09:39:30.000Z
|
src/cpu/x64/matmul/brgemm_matmul.cpp
|
cfRod/oneDNN
|
7981216b8341b8603e54472f5a0dd7a12ef9cf67
|
[
"Apache-2.0"
] | 498
|
2018-01-25T00:14:48.000Z
|
2020-04-03T16:21:44.000Z
|
src/cpu/x64/matmul/brgemm_matmul.cpp
|
cfRod/oneDNN
|
7981216b8341b8603e54472f5a0dd7a12ef9cf67
|
[
"Apache-2.0"
] | 365
|
2018-01-29T16:12:36.000Z
|
2020-04-03T08:32:27.000Z
|
/*******************************************************************************
* Copyright 2021-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "common/c_types_map.hpp"
#include "common/dnnl_thread.hpp"
#include "common/memory_tracking.hpp"
#include "common/tag_traits.hpp"
#include "common/type_helpers.hpp"
#include "common/utils.hpp"
#include "cpu/cpu_primitive.hpp"
#include "cpu/x64/amx_tile_configure.hpp"
#include "cpu/x64/injectors/jit_uni_binary_injector.hpp"
#include "cpu/x64/matmul/brgemm_matmul.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
namespace x64 {
namespace matmul {
using namespace dnnl::impl::memory_tracking::names;
using namespace dnnl::impl::utils;
using namespace nstl;
using namespace data_type;
template <cpu_isa_t isa>
status_t brgemm_matmul_t<isa>::pd_t::init(engine_t *engine) {
const auto src_dt = src_md_.data_type;
const auto wei_dt = weights_md_.data_type;
const auto dst_dt = dst_md_.data_type;
const bool is_f32 = everyone_is(f32, src_dt, wei_dt, dst_dt);
const bool is_int8 = one_of(src_dt, u8, s8) && wei_dt == s8
&& one_of(dst_dt, u8, s8, s32, f32, bf16);
const bool is_bf16
= everyone_is(bf16, src_dt, wei_dt) && one_of(dst_dt, bf16, f32);
auto check_bias = [&]() -> bool {
const bool is_bia_dt_correct
= (is_int8
&& one_of(weights_md(1)->data_type, f32, s32, s8, u8,
bf16))
|| (is_bf16 && one_of(weights_md(1)->data_type, f32, bf16))
|| (is_f32 && weights_md(1)->data_type == f32);
return IMPLICATION(with_bias(), is_bia_dt_correct && is_bias_1xN());
};
auto check_attr_oscale = [&]() -> bool {
const auto &oscale = attr()->output_scales_;
return IMPLICATION(
oscale.mask_ != 0, oscale.mask_ == (1 << (dst_md_.ndims - 1)));
};
auto check_attr_zero_points
= [&]() -> bool { return attr()->zero_points_.common(); };
const bool problem_dt_correct = is_int8 || is_bf16 || is_f32;
bool ok = mayiuse(isa) && problem_dt_correct
&& !has_runtime_dims_or_strides()
&& attr()->has_default_values(
primitive_attr_t::skip_mask_t::oscale_runtime
| primitive_attr_t::skip_mask_t::zero_points_runtime
| primitive_attr_t::skip_mask_t::post_ops
| primitive_attr_t::skip_mask_t::sum_dt,
dst_dt)
&& attr()->post_ops_.check_sum_consistent_dt(dst_dt)
&& check_attr_oscale() && check_attr_zero_points() && check_bias();
if (!ok) return status::unimplemented;
CHECK(init_brgemm_matmul_conf(isa, bgmmc_, *desc(), src_md_, weights_md_,
dst_md_, bias_md_, attr_));
const float alpha = 1.0;
const float beta = 1.0;
const float beta_init = 0.0;
for_(int i_bs = 0; i_bs < 2; i_bs++)
for_(int i_init = 0; i_init < 2; i_init++)
for_(int i_M = 0; i_M < 2; i_M++)
for_(int i_N = 0; i_N < 2; i_N++)
for (int i_K = 0; i_K < 2; i_K++) {
auto vbeta = (i_init) ? beta_init : beta;
auto vM = (i_M) ? bgmmc_.M_tail : bgmmc_.M_blk;
auto vN = (i_N) ? bgmmc_.N_tail : bgmmc_.N_blk;
auto vK = (i_K) ? bgmmc_.K_tail : bgmmc_.K_blk;
int bs = get_brg_batchsize(bgmmc_, i_bs, i_K);
int idx = get_brg_kernel_idx(i_bs, i_init, i_M, i_N, i_K);
if (idx < 0) continue;
brgemm_t &brg = brg_descs_[idx];
auto LDA = i_K && bgmmc_.use_buffer_a_tail_only
? (dim_t)bgmmc_.wei_k_blk
: bgmmc_.LDA;
CHECK(brgemm_desc_init(&brg, isa, bgmmc_.brg_type, bgmmc_.src_dt,
bgmmc_.wei_dt, false, false, brgemm_row_major, alpha, vbeta,
LDA, bgmmc_.LDB, bgmmc_.LDC, vM, vN, vK));
auto LDD = bgmmc_.LDD;
CHECK(brgemm_desc_set_postops(
&brg, attr(), &dst_md_, LDD, bgmmc_.bia_dt));
brgemm_attr_t brgattr;
brgattr.generate_skip_accumulation
= bgmmc_.post_ops_applicable && bgmmc_.nthr_k > 1;
constexpr bool is_amx = one_of(
isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16);
if (is_amx) {
if (!brgattr.generate_skip_accumulation) {
// TODO: uker doesn't yet support generate_skip_accumulation
brgattr.use_uker = true;
brgattr.use_interleave_stores = true;
}
brgattr.max_bs = bs;
brgattr.wary_tail_read = false;
// TODO: change expected sizes to local chunks wrt L2 blocking
brgattr.hint_expected_A_size = vM * vK * bs;
brgattr.hint_expected_B_size = vN * vK * bs;
brgattr.hint_expected_C_size = vM * vN * bs;
brgattr.hint_innermost_loop = brgemm_ld_loop_innermost;
brgattr.hint_prefetching
= brgemm_kernel_prefetching_t::brgemm_prf_output1;
}
CHECK(brgemm_desc_set_attr(&brg, brgattr));
bgmmc_.wsp_tile_per_thr_bytes = nstl::max(
brg.get_wsp_buffer_size(), bgmmc_.wsp_tile_per_thr_bytes);
}
auto scratchpad = scratchpad_registry().registrar();
init_scratchpad(scratchpad, bgmmc_);
return status::success;
}
template <cpu_isa_t isa>
status_t brgemm_matmul_t<isa>::init(engine_t *engine) {
for_(int i_bs = 0; i_bs < 2; i_bs++)
for_(int i_M = 0; i_M < 2; i_M++)
for_(int i_N = 0; i_N < 2; i_N++)
for_(int i_K = 0; i_K < 2; i_K++)
for (int i_init = 0; i_init < 2; i_init++) {
int idx = pd()->get_brg_kernel_idx(i_bs, i_init, i_M, i_N, i_K);
if (idx < 0) continue;
brgemm_kernel_t *ker = nullptr;
CHECK(brgemm_kernel_create(&ker, pd()->get_brg_desc(idx)));
CHECK(safe_ptr_assign(brg_kernels_[idx], ker));
if (one_of(isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16))
CHECK(brgemm_init_tiles(
pd()->get_brg_desc(idx), &brg_kernel_palettes_[idx][0]));
}
const auto &bgmmc = pd()->get_brgemm_matmul_conf();
if (bgmmc.use_buffer_b)
CHECK(create_brgemm_matmul_copy_b(copy_B_kernel_, &bgmmc));
if (bgmmc.use_buffer_a || bgmmc.use_buffer_a_tail_only)
CHECK(create_brgemm_matmul_copy_a(copy_A_kernel_, &bgmmc));
if (bgmmc.nthr_k > 1 && bgmmc.acc_dt == f32) {
CHECK(safe_ptr_assign(
acc_ker_f32_, new cpu_accumulator_1d_t<data_type::f32>()));
CHECK(acc_ker_f32_->create_kernel());
} else if (bgmmc.nthr_k > 1 && bgmmc.acc_dt == s32) {
CHECK(safe_ptr_assign(
acc_ker_s32_, new cpu_accumulator_1d_t<data_type::s32>()));
CHECK(acc_ker_s32_->create_kernel());
}
return status::success;
}
template <cpu_isa_t isa>
status_t brgemm_matmul_t<isa>::execute_body(const exec_ctx_t &ctx) const {
DEFINE_ZERO_POINT_VALUE(src_zero_point, DNNL_ARG_SRC);
DEFINE_ZERO_POINT_VALUE(wei_zero_point, DNNL_ARG_WEIGHTS);
DEFINE_ZERO_POINT_VALUE(dst_zero_point, DNNL_ARG_DST);
DEFINE_SCALES_BUFFER(oscales);
brg_matmul_exec_ctx_t brgmm_ctx(
ctx, pd(), oscales, src_zero_point, wei_zero_point, dst_zero_point);
const auto &bgmmc = pd()->get_brgemm_matmul_conf();
const bool use_buffer_a
= bgmmc.use_buffer_a || bgmmc.use_buffer_a_tail_only;
constexpr bool is_amx
= one_of(isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16);
const int num_threads = brgmm_ctx.get_num_threads_for_parallelization();
parallel(num_threads, [&](const int ithr, const int nthr) {
const int ithr_bmn = brgmm_ctx.get_thread_idx_for_bmn(ithr);
const int ithr_k = brgmm_ctx.get_thread_idx_for_k(ithr);
if (ithr_bmn < 0 || ithr_k < 0) return;
int start {0}, end {0};
balance211(brgmm_ctx.get_parallel_work_amount(),
brgmm_ctx.get_num_threads_for_bmn(), ithr_bmn, start, end);
int kc_start {0}, kc_end {bgmmc.K_chunks};
if (brgmm_ctx.parallel_reduction_is_used())
balance211((int)bgmmc.K_chunks, brgmm_ctx.get_num_threads_for_k(),
ithr_k, kc_start, kc_end);
if (is_amx) {
const auto base_ker_idx = brgmm_ctx.get_base_brgemm_kernel_idx();
amx_tile_configure(&brg_kernel_palettes_[base_ker_idx][0]);
}
int b {0}, mc {0}, nc {0};
nd_iterator_init(
start, b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks);
while (start < end) {
auto m_start = mc * bgmmc.M_chunk_size;
auto m_end = nstl::min(
(mc + 1) * bgmmc.M_chunk_size, bgmmc.num_M_blocks);
auto n_start = nc * bgmmc.N_chunk_size;
auto n_end = nstl::min(
(nc + 1) * bgmmc.N_chunk_size, bgmmc.num_N_blocks);
for_(int kc = kc_start; kc < kc_end; kc++)
for (int nb = n_start; nb < n_end; nb++) {
if (bgmmc.use_buffer_b)
copy_b_chunk_in_buffer(brgmm_ctx, ithr, b, nb, kc);
for (int mb = m_start; mb < m_end; mb++) {
if (use_buffer_a && nb == n_start)
copy_a_chunk_in_buffer(brgmm_ctx, ithr, b, mb, kc);
compute_kernel(
brgmm_ctx, ithr, b, mb, nb, kc, kc == kc_start);
}
}
++start;
nd_iterator_step(
b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks);
}
if (is_amx) { amx_tile_release(); }
});
maybe_reduce_partial_results_and_apply_postops(brgmm_ctx);
return status::success;
}
template <cpu_isa_t isa>
void brgemm_matmul_t<isa>::compute_kernel(
const brg_matmul_exec_ctx_t &brgmm_ctx, int ithr, int b_idx,
int m_blk_idx, int n_blk_idx, int k_chunk_idx, bool do_init) const {
constexpr bool is_amx
= one_of(isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16);
const auto &bgmmc = pd()->get_brgemm_matmul_conf();
const auto addr_batch = brgmm_ctx.get_batch_elem_ptr(ithr);
const int base_brg_ker_idx = brgmm_ctx.get_base_brgemm_kernel_idx();
const auto wsp_tile = brgmm_ctx.get_tile_workspace(ithr);
const int m = m_blk_idx * bgmmc.M_blk;
const int n = n_blk_idx * bgmmc.N_blk;
const int k_blk_idx = k_chunk_idx * bgmmc.brgemm_batch_size;
const bool is_M_tail = (bgmmc.M - m < bgmmc.M_blk);
const bool is_N_tail = (bgmmc.N - n < bgmmc.N_blk);
const bool is_last_K_chunk = brgmm_ctx.is_last_K_chunk(k_chunk_idx);
const int remaining_k_blks
= (bgmmc.use_buffer_a ? utils::rnd_up(bgmmc.K, bgmmc.K_blk)
: bgmmc.K)
- k_chunk_idx * bgmmc.K_chunk_elems;
const int gemm_batch = brgmm_ctx.get_brgemm_batch_size(k_chunk_idx);
const bool is_K_tail
= is_last_K_chunk && (gemm_batch * bgmmc.K_blk) != remaining_k_blks;
auto is_bs_tail = (gemm_batch != bgmmc.brgemm_batch_size);
const int brg_ker_idx = pd()->get_brg_kernel_idx(
is_bs_tail, do_init, is_M_tail, is_N_tail, false);
const auto ptr_bias = brgmm_ctx.get_bias_ptr(n);
auto ptr_D = brgmm_ctx.get_data_C_ptr(b_idx, m, n);
auto ptr_C = (bgmmc.use_buffer_c)
? brgmm_ctx.get_buf_C_ptr(ithr, m_blk_idx, n_blk_idx)
: ptr_D;
const auto zp_comp_a = brgmm_ctx.get_zp_a_compensation_ptr(ithr, n_blk_idx);
const auto zp_comp_b
= brgmm_ctx.get_zp_b_compensation_result_ptr(ithr, m_blk_idx);
const auto zp_c_val_ptr = brgmm_ctx.get_zp_c_val_ptr();
const auto &post_ops_binary_rhs_arg_vec
= brgmm_ctx.get_post_ops_binary_rhs_arg_vec();
const bool post_ops_applicable = bgmmc.post_ops_applicable
&& (bgmmc.nthr_k <= 1 || bgmmc.K_chunks == 1);
if (gemm_batch > 0 && brg_ker_idx >= 0) {
const auto brg_kernel = brg_kernels_[brg_ker_idx].get();
assert(brg_kernel != nullptr);
const bool is_tile_reconf_required = is_amx && (is_M_tail || is_N_tail);
if (is_tile_reconf_required)
amx_tile_configure(&brg_kernel_palettes_[brg_ker_idx][0]);
brgmm_ctx.init_brgemm_batch_elements_values(
ithr, 0, gemm_batch, b_idx, m_blk_idx, k_blk_idx, n_blk_idx);
if (post_ops_applicable && is_last_K_chunk && !is_K_tail) {
void *scratch = is_amx
? static_cast<void *>(wsp_tile)
: static_cast<void *>(brgmm_ctx.get_s8s8_comp_ptr(
ithr, b_idx, n_blk_idx));
const size_t dst_row_logical_off = m_blk_idx * bgmmc.M_blk;
const size_t batch_first_dim_idx = bgmmc.batch_ndims > 1
? b_idx / bgmmc.batch_without_first_dim
: 0;
const size_t first_mb_matrix_addr_off
= batch_first_dim_idx * (bgmmc.M * bgmmc.N)
+ (m * bgmmc.N + n);
const brgemm_post_ops_data_t post_ops_data {
static_cast<const void *>(ptr_bias),
brgmm_ctx.get_oscales_ptr(n),
post_ops_binary_rhs_arg_vec.data(), static_cast<size_t>(n),
dst_row_logical_off, brgmm_ctx.get_data_C_ptr(0, 0, 0),
first_mb_matrix_addr_off,
static_cast<const void *>(zp_comp_a),
static_cast<const void *>(zp_comp_b),
static_cast<const void *>(zp_c_val_ptr)};
brgemm_kernel_execute_postops(brg_kernel, gemm_batch, addr_batch,
(void *)ptr_C, (void *)ptr_D, post_ops_data, scratch);
} else {
brgemm_kernel_execute(brg_kernel, gemm_batch, addr_batch,
(void *)ptr_C, is_amx ? (void *)wsp_tile : nullptr);
}
if (is_tile_reconf_required)
amx_tile_configure(&brg_kernel_palettes_[base_brg_ker_idx][0]);
}
if (is_K_tail) {
brgmm_ctx.init_brgemm_batch_elements_values(
ithr, gemm_batch, 1, b_idx, m_blk_idx, k_blk_idx, n_blk_idx);
const bool use_init_ker = (do_init && gemm_batch == 0);
const int brg_ker_idx = pd()->get_brg_kernel_idx(
false, use_init_ker, is_M_tail, is_N_tail, true);
const auto brg_kernel_k_tail = brg_kernels_[brg_ker_idx].get();
const bool is_tile_reconf_required
= is_amx && bgmmc.K_tail != bgmmc.K_blk;
if (is_tile_reconf_required)
amx_tile_configure(&brg_kernel_palettes_[brg_ker_idx][0]);
if (post_ops_applicable) {
void *scratch = is_amx
? static_cast<void *>(wsp_tile)
: static_cast<void *>(brgmm_ctx.get_s8s8_comp_ptr(
ithr, b_idx, n_blk_idx));
const size_t dst_row_logical_off = m_blk_idx * bgmmc.M_blk;
const size_t batch_first_dim_idx = bgmmc.batch_ndims > 1
? b_idx / bgmmc.batch_without_first_dim
: 0;
const size_t first_mb_matrix_addr_off
= batch_first_dim_idx * (bgmmc.M * bgmmc.N)
+ (m * bgmmc.N + n);
const brgemm_post_ops_data_t post_ops_data {
static_cast<const void *>(ptr_bias),
brgmm_ctx.get_oscales_ptr(n),
post_ops_binary_rhs_arg_vec.data(), static_cast<size_t>(n),
dst_row_logical_off, brgmm_ctx.get_data_C_ptr(0, 0, 0),
first_mb_matrix_addr_off,
static_cast<const void *>(zp_comp_a),
static_cast<const void *>(zp_comp_b),
static_cast<const void *>(zp_c_val_ptr)};
brgemm_kernel_execute_postops(brg_kernel_k_tail, 1, addr_batch,
(void *)ptr_C, (void *)ptr_D, post_ops_data, scratch);
} else {
brgemm_kernel_execute(brg_kernel_k_tail, 1, addr_batch,
(void *)ptr_C, is_amx ? (void *)wsp_tile : nullptr);
}
if (is_tile_reconf_required)
amx_tile_configure(&brg_kernel_palettes_[base_brg_ker_idx][0]);
}
}
template <cpu_isa_t isa>
void brgemm_matmul_t<isa>::maybe_reduce_partial_results_and_apply_postops(
const brg_matmul_exec_ctx_t &brgmm_ctx) const {
if (!brgmm_ctx.parallel_reduction_is_used()) return;
const auto &bgmmc = pd()->get_brgemm_matmul_conf();
const int num_threads = brgmm_ctx.get_num_threads_for_parallelization();
parallel(num_threads, [&](const int ithr, const int nthr) {
const int nthr_k = brgmm_ctx.get_num_threads_for_k();
const int ithr_bmn = brgmm_ctx.get_thread_idx_for_bmn(ithr);
const int ithr_k = brgmm_ctx.get_thread_idx_for_k(ithr);
if (ithr_bmn < 0 || ithr_k < 0) return;
const int num_reduction_buffers = nstl::min(nthr_k, bgmmc.K_chunks);
int bmn_start {0}, bmn_end {0};
int start {0}, end {0};
balance211(brgmm_ctx.get_parallel_work_amount(),
brgmm_ctx.get_num_threads_for_bmn(), ithr_bmn, bmn_start,
bmn_end);
balance211(bmn_end - bmn_start, nthr_k, ithr_k, start, end);
int b {0}, mc {0}, nc {0};
assert(bgmmc.batch == 1);
nd_iterator_init(bmn_start + start, b, bgmmc.batch, mc, bgmmc.M_chunks,
nc, bgmmc.N_chunks);
while (start < end) {
auto mb_start = mc * bgmmc.M_chunk_size;
auto mb_end = nstl::min(
(mc + 1) * bgmmc.M_chunk_size, bgmmc.num_M_blocks);
auto nb_start = nc * bgmmc.N_chunk_size;
auto nb_end = nstl::min(
(nc + 1) * bgmmc.N_chunk_size, bgmmc.num_N_blocks);
for (int mb = mb_start; mb < mb_end; mb++) {
const int curr_M_blk
= nstl::min(bgmmc.M - mb * bgmmc.M_blk, bgmmc.M_blk);
const bool is_M_tail = curr_M_blk < bgmmc.M_blk;
const int curr_N_chunk_size
= nstl::min(bgmmc.N, nb_end * bgmmc.N_blk)
- nb_start * bgmmc.N_blk;
char *buf_reduced_base = brgmm_ctx.get_buf_C_par_reduction_ptr(
0, mb, nb_start);
const size_t m_offset = bgmmc.LDC * bgmmc.acc_dt_sz;
for (int r = 1; r < num_reduction_buffers; r++) {
const char *buf_to_reduce_base
= brgmm_ctx.get_buf_C_par_reduction_ptr(
r, mb, nb_start);
for (int m = 0; m < curr_M_blk; m++) {
accumulate(buf_reduced_base + m * m_offset,
buf_to_reduce_base + m * m_offset,
curr_N_chunk_size);
}
}
if (bgmmc.post_ops_applicable) {
for (int nb = nb_start; nb < nb_end; nb++) {
const bool is_N_tail
= (bgmmc.N - nb * bgmmc.N_blk < bgmmc.N_blk);
const int brg_ker_idx = pd()->get_brg_kernel_idx(
false, false, is_M_tail, is_N_tail, false);
const auto brg_kernel = brg_kernels_[brg_ker_idx].get();
const int m = mb * bgmmc.M_blk;
const int n = nb * bgmmc.N_blk;
const auto ptr_bias = brgmm_ctx.get_bias_ptr(n);
auto ptr_D = brgmm_ctx.get_data_C_ptr(b, m, n);
auto ptr_C = brgmm_ctx.get_buf_C_par_reduction_ptr(
0, mb, nb);
// TODO: support reduction for zp/s8s8 compensations
// computed in copy routines
const auto zp_comp_a
= brgmm_ctx.get_zp_a_compensation_ptr(ithr, nb);
const auto zp_comp_b
= brgmm_ctx.get_zp_b_compensation_result_ptr(
ithr, mb);
const auto zp_c_val_ptr = brgmm_ctx.get_zp_c_val_ptr();
const auto &post_ops_binary_rhs_arg_vec
= brgmm_ctx.get_post_ops_binary_rhs_arg_vec();
const size_t dst_row_logical_off = mb * bgmmc.M_blk;
const size_t batch_first_dim_idx = bgmmc.batch_ndims > 1
? b / bgmmc.batch_without_first_dim
: 0;
const size_t first_mb_matrix_addr_off
= batch_first_dim_idx * (bgmmc.M * bgmmc.N)
+ (m * bgmmc.N + n);
// apply post-ops and convert to dst data type only
constexpr bool skip_accumulation = true;
const brgemm_post_ops_data_t post_ops_data {
static_cast<const void *>(ptr_bias),
brgmm_ctx.get_oscales_ptr(n),
post_ops_binary_rhs_arg_vec.data(),
static_cast<size_t>(n), dst_row_logical_off,
brgmm_ctx.get_data_C_ptr(0, 0, 0),
first_mb_matrix_addr_off,
static_cast<const void *>(zp_comp_a),
static_cast<const void *>(zp_comp_b),
static_cast<const void *>(zp_c_val_ptr),
skip_accumulation};
brgemm_kernel_execute_postops(brg_kernel, 0, nullptr,
(void *)ptr_C, (void *)ptr_D, post_ops_data,
nullptr);
}
}
}
++start;
nd_iterator_step(
b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks);
}
});
}
template <cpu_isa_t isa>
void brgemm_matmul_t<isa>::copy_a_chunk_in_buffer(
const brg_matmul_exec_ctx_t &brgmm_ctx, int ithr, int b_idx,
int m_blk_idx, int k_chunk_idx) const {
const auto &bgmmc = pd()->get_brgemm_matmul_conf();
auto ctx = jit_brgemm_matmul_copy_a_t::ctx_t();
const int k_start = k_chunk_idx * bgmmc.K_chunk_elems;
const bool is_K_tail
= brgmm_ctx.is_last_K_chunk(k_chunk_idx) && bgmmc.K_tail > 0;
const int gemm_batch = brgmm_ctx.get_brgemm_batch_size(k_chunk_idx);
const int gemm_batch_iters = bgmmc.use_buffer_a_tail_only ? 0 : gemm_batch;
const int m = m_blk_idx * bgmmc.M_blk;
const bool is_M_tail = (bgmmc.M - m < bgmmc.M_blk);
ctx.current_M_blk = is_M_tail ? bgmmc.M_tail : bgmmc.M_blk;
ctx.zp_b_compensation_buffer_ptr
= (void *)brgmm_ctx.get_zp_b_compensation_buffer_ptr(
ithr, m_blk_idx);
ctx.zp_a_compensation_result_ptr
= (void *)brgmm_ctx.get_zp_b_compensation_result_ptr(
ithr, m_blk_idx);
ctx.zp_b_neg_value_ptr = (void *)brgmm_ctx.get_zp_b_neg_val_ptr();
ctx.zp_ab_comp_ptr = (void *)brgmm_ctx.get_zp_ab_mixed_comp_ptr();
for (int gb = 0; gb < gemm_batch_iters; gb++) {
const int k = k_start + gb * bgmmc.K_blk;
ctx.src = (void *)brgmm_ctx.get_data_A_ptr(b_idx, m, k);
ctx.tr_src = (void *)brgmm_ctx.get_buf_A_ptr(ithr, m_blk_idx, gb);
ctx.current_K_blk = nstl::min(bgmmc.K_blk, bgmmc.K);
ctx.current_K_start = k;
(*copy_A_kernel_)(&ctx);
}
if (is_K_tail) {
const auto K_tail = bgmmc.K % bgmmc.K_blk;
const int k = k_start + gemm_batch * bgmmc.K_blk;
ctx.src = (void *)brgmm_ctx.get_data_A_ptr(b_idx, m, k);
ctx.tr_src = (void *)brgmm_ctx.get_buf_A_ptr(
ithr, m_blk_idx, gemm_batch_iters);
ctx.current_K_blk = K_tail;
ctx.current_K_start = k;
(*copy_A_kernel_)(&ctx);
}
}
template <cpu_isa_t isa>
void brgemm_matmul_t<isa>::copy_b_chunk_in_buffer(
const brg_matmul_exec_ctx_t &brgmm_ctx, int ithr, int b_idx,
int n_blk_idx, int k_chunk_idx) const {
const auto &bgmmc = pd()->get_brgemm_matmul_conf();
const int k_start = k_chunk_idx * bgmmc.K_chunk_elems;
const bool is_K_tail
= brgmm_ctx.is_last_K_chunk(k_chunk_idx) && bgmmc.K_tail > 0;
const int gemm_batch = brgmm_ctx.get_brgemm_batch_size(k_chunk_idx);
auto ctx = jit_brgemm_matmul_copy_b_t::ctx_t();
const int n = n_blk_idx * bgmmc.N_blk;
const bool is_N_tail = (bgmmc.N - n < bgmmc.N_blk);
ctx.current_N_blk = is_N_tail ? bgmmc.N_tail : bgmmc.N_blk;
ctx.zp_a_compensation_ptr
= (void *)brgmm_ctx.get_zp_a_compensation_ptr(ithr, n_blk_idx);
ctx.zp_a_neg_value_ptr = (void *)brgmm_ctx.get_zp_a_neg_val_ptr();
int gb = 0;
for (; gb < gemm_batch; gb++) {
const int k = k_start + gb * bgmmc.K_blk;
ctx.src = (void *)brgmm_ctx.get_data_B_ptr(b_idx, k, n);
ctx.tr_src = (void *)brgmm_ctx.get_buf_B_ptr(ithr, gb, n_blk_idx);
ctx.compensation_ptr
= (void *)brgmm_ctx.get_s8s8_comp_ptr(ithr, b_idx, n_blk_idx);
ctx.current_K_start = k;
ctx.current_K_iters = nstl::min(bgmmc.K_blk, bgmmc.K);
(*copy_B_kernel_)(&ctx);
}
if (is_K_tail) {
const int k = k_start + gb * bgmmc.K_blk;
ctx.src = (void *)brgmm_ctx.get_data_B_ptr(b_idx, k, n);
ctx.tr_src = (void *)brgmm_ctx.get_buf_B_ptr(ithr, gb, n_blk_idx);
ctx.compensation_ptr
= (void *)brgmm_ctx.get_s8s8_comp_ptr(ithr, b_idx, n_blk_idx);
ctx.current_K_start = k;
ctx.current_K_iters = bgmmc.K % bgmmc.K_blk;
(*copy_B_kernel_)(&ctx);
}
}
template <cpu_isa_t isa>
void brgemm_matmul_t<isa>::accumulate(
char *result_ptr, const char *reduce_ptr, size_t size) const {
if (pd()->get_brgemm_matmul_conf().acc_dt == f32)
acc_ker_f32_->accumulate(
(float *)result_ptr, (const float *)reduce_ptr, size);
else if (pd()->get_brgemm_matmul_conf().acc_dt == s32)
acc_ker_s32_->accumulate(
(int32_t *)result_ptr, (const int32_t *)reduce_ptr, size);
else
assert(!"unsupported accumulation data type");
}
template <cpu_isa_t isa>
struct brgemm_matmul_t<isa>::brg_matmul_exec_ctx_t {
brg_matmul_exec_ctx_t(const exec_ctx_t &ctx, const pd_t *pd,
const float *oscales, int32_t src_zp, int32_t wei_zp,
int32_t dst_zp)
: bgmmc_(pd->get_brgemm_matmul_conf()) {
data_A_ptr_ = CTX_IN_MEM(const char *, DNNL_ARG_SRC);
data_B_ptr_ = CTX_IN_MEM(const char *, DNNL_ARG_WEIGHTS);
data_C_ptr_ = CTX_OUT_MEM(char *, DNNL_ARG_DST);
bias_ptr_ = CTX_IN_MEM(const char *, DNNL_ARG_BIAS);
oscales_ptr_ = oscales;
memory_tracking::grantor_t scratchpad = ctx.get_scratchpad_grantor();
const auto &bgmmc = pd->get_brgemm_matmul_conf();
batch_element_ptr_ = scratchpad.template get<brgemm_batch_element_t>(
key_brgemm_primitive_batch);
const bool use_buffer_a
= bgmmc.use_buffer_a || bgmmc.use_buffer_a_tail_only;
buf_A_ptr_ = (use_buffer_a)
? scratchpad.template get<char>(key_brgemm_primitive_buffer_a)
: nullptr;
buf_B_ptr_ = (bgmmc.use_buffer_b)
? scratchpad.template get<char>(key_brgemm_primitive_buffer_b)
: nullptr;
buf_C_ptr_ = (bgmmc.use_buffer_c)
? scratchpad.template get<char>(key_brgemm_primitive_buffer)
: nullptr;
is_amx_ = one_of(
isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16);
wsp_tile_ptr_ = is_amx_
? ctx.get_scratchpad_grantor().template get<char>(
key_conv_amx_tile_buffer)
: nullptr;
const memory_desc_wrapper weights_d(pd->weights_md(0));
const dim_t comp_offset = bgmmc_.b_dt_sz
* (weights_d.size() - weights_d.additional_buffer_size());
s8s8_compensation_ptr_ = (bgmmc.s8s8_compensation_required)
? ((bgmmc.use_buffer_b)
? scratchpad.template get<int32_t>(
key_brgemm_primitive_buffer_comp)
: const_cast<int32_t *>(
reinterpret_cast<const int32_t *>(
&data_B_ptr_[comp_offset])))
: nullptr;
assert(IMPLICATION(bgmmc.s8s8_compensation_required,
bgmmc_.b_dt_sz == bgmmc_.tr_b_dt_sz));
zero_point_a_compensations_ptr_ = bgmmc.has_zero_point_a
? scratchpad.template get<int32_t>(
key_brgemm_primitive_zp_comp_a)
: nullptr;
zero_point_b_compensations_ptr_ = bgmmc.has_zero_point_b
? scratchpad.template get<int32_t>(
key_brgemm_primitive_zp_comp_b)
: nullptr;
zero_point_a_negative_val_ = -src_zp;
zero_point_b_negative_val_ = -wei_zp;
zero_point_mixed_ab_compensation_component_
= bgmmc.K * zero_point_a_negative_val_;
zero_point_c_val_ = dst_zp;
post_ops_binary_rhs_arg_vec_ = binary_injector::prepare_binary_args(
pd->attr()->post_ops_, ctx);
base_brg_ker_idx_
= pd->get_brg_kernel_idx(false, true, false, false, false);
vnni_factor = isa == avx512_core_bf16_amx_int8
? 4
: isa == avx512_core_bf16_amx_bf16 ? 2 : 1;
reorder_zp_a_comp_ptr_ = nullptr;
if (bgmmc_.has_zero_point_a && bgmmc_.blocked_B) {
// Store the pointer to computed in reorder compensation values to
// scale them locally by zp_a value just before usage in post-ops.
// Using the single global scaling before parallel section might
// produce significant overhead for small problems running in
// multitreaded execution mode
const size_t reorder_zp_a_comp_offset
= weights_d.size() - weights_d.additional_buffer_size();
const size_t s8s8_buffer_sz = bgmmc.s8s8_compensation_required
? bgmmc.s8s8_comp_b_str * sizeof(int32_t)
: 0;
reorder_zp_a_comp_ptr_
= const_cast<int32_t *>(reinterpret_cast<const int32_t *>(
&data_B_ptr_[reorder_zp_a_comp_offset
+ s8s8_buffer_sz]));
}
// Set last_chunk_brgemm_batch_size_ to brgemm_batch_size
// when K_tail = 0 and brgemm_batch_tail_size = 0
last_chunk_brgemm_batch_size_ = bgmmc.brgemm_batch_tail_size;
if (bgmmc.K_tail == 0 && last_chunk_brgemm_batch_size_ == 0)
last_chunk_brgemm_batch_size_ = bgmmc.brgemm_batch_size;
// parallelization
parallel_work_amount_ = bgmmc.batch * bgmmc.M_chunks * bgmmc.N_chunks;
// The number of threads available during primitive execution may
// increase (ex. Eigen threadpool implementation) or decrease
// (ex. nested parallelism) compared to the
// number of threads available during primitive creation.
// So we limit the total number of threads to the
// minimum of these two values to prevent potential OOM issues.
nthr_ = nstl::min(dnnl_get_current_num_threads(), bgmmc.nthr);
nthr_k_ = bgmmc.nthr_k > 0 && bgmmc.nthr_k <= nthr_ ? bgmmc.nthr_k : 1;
nthr_bmn_ = nthr_ / nthr_k_;
num_threads_used_ = nthr_k_ * nthr_bmn_;
// If parallel_work_amount_ == 1 and parallel reduction is not used, we
// limit num threads to 1 as parallel(1, ...) does not create parallel
// section at all. We do not limit number of threads for case
// 1 < parallel_work_amount_ < dnnl_get_max_threads() to avoid potential
// overhead on spawning different number of OMP threads from layer to
// layer.
if (parallel_work_amount_ == 1 && !parallel_reduction_is_used())
nthr_ = nthr_bmn_ = nthr_k_ = 1;
const bool need_to_calculate_compensation_for_a
= bgmmc.has_zero_point_b;
const bool need_to_calculate_compensation_for_b = !IMPLICATION(
(bgmmc.has_zero_point_a || bgmmc.s8s8_compensation_required),
bgmmc.blocked_B);
const bool calculate_compensations_in_copy_routines
= need_to_calculate_compensation_for_a
|| need_to_calculate_compensation_for_b;
// currently parallel reduction is supported only for case of
// non-batched problems without computation of any compensations in
// copy routines
assert(IMPLICATION(parallel_reduction_is_used(),
bgmmc.batch == 1 && !calculate_compensations_in_copy_routines));
MAYBE_UNUSED(need_to_calculate_compensation_for_a);
MAYBE_UNUSED(need_to_calculate_compensation_for_b);
MAYBE_UNUSED(calculate_compensations_in_copy_routines);
}
// NOTE: gb --> generalized batch, bb --> broadcast batch
int get_bb_idx(int gb_idx, const brgemm_matmul_bcast_desc_t &bd) const {
if (!bd.bcast_mask) // no broadcast
return gb_idx;
int gb_off_before_bcast = utils::rnd_dn(
gb_idx, bd.first_bcast_dim_to_last_batch_dim_prod);
int bb_idx = gb_off_before_bcast / (bd.bcast_dims_prod);
dim_t cur_bcast_dims_prod = bd.bcast_dims_prod;
int mask = 1 << (bgmmc_.batch_ndims - bd.first_bcast_dim - 1);
for (int d = bd.first_bcast_dim; d < bd.last_bcast_dim; ++d) {
if (bd.bcast_mask & mask) // broadcast
cur_bcast_dims_prod /= bd.batch_dims[d];
else {
int cur_b = (gb_idx / bd.gb_off[d]) % bd.batch_dims[d];
bb_idx += cur_b * (bd.gb_off[d] / cur_bcast_dims_prod);
}
mask >>= 1;
}
bb_idx += gb_idx % bd.gb_off[bd.last_bcast_dim];
return bb_idx;
}
const char *get_data_A_ptr(int b, int m, int k) const {
int cur_b = get_bb_idx(b, bgmmc_.bcast_A_desc);
return data_A_ptr_ + get_data_A_off(cur_b, m, k);
}
const char *get_data_B_ptr(int b, int k, int n) const {
int cur_b = get_bb_idx(b, bgmmc_.bcast_B_desc);
return data_B_ptr_ + get_data_B_off(cur_b, k, n);
}
char *get_data_C_ptr(int b, int m, int n) const {
return data_C_ptr_ + get_data_C_off(b, m, n);
}
brgemm_batch_element_t *get_batch_elem_ptr(int ithr) const {
return batch_element_ptr_
+ ithr * bgmmc_.brgemm_batch_element_per_thr_sz;
}
void init_brgemm_batch_elements_values(int ithr, int brg_batch_start,
int brg_batch_iters, int b_idx, int m_blk_idx, int k_blk_idx,
int n_blk_idx) const {
auto addr_batch = get_batch_elem_ptr(ithr);
const int m = m_blk_idx * bgmmc_.M_blk;
const int n = n_blk_idx * bgmmc_.N_blk;
for (int b_iter = 0; b_iter < brg_batch_iters; b_iter++) {
const int brg_batch_idx = brg_batch_start + b_iter;
const int k = (k_blk_idx + brg_batch_idx) * bgmmc_.K_blk;
addr_batch[b_iter].ptr.A = bgmmc_.use_buffer_a
? get_buf_A_ptr(ithr, m_blk_idx, brg_batch_idx)
: get_data_A_ptr(b_idx, m, k);
addr_batch[b_iter].ptr.B = (bgmmc_.use_buffer_b)
? get_buf_B_ptr(ithr, brg_batch_idx, n_blk_idx)
: get_data_B_ptr(b_idx, k, n);
}
}
char *get_buf_A_ptr(int ithr, int m_blk_idx, int k_blk_idx) const {
if (!bgmmc_.use_buffer_a && !bgmmc_.use_buffer_a_tail_only)
return nullptr;
const int k_blk_local = bgmmc_.use_buffer_a_tail_only ? 0 : k_blk_idx;
const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size;
return buf_A_ptr_ + ithr * bgmmc_.buffer_a_per_thread_sz
+ m_blk_local * bgmmc_.buffer_a_chunk_shift_along_m
+ k_blk_local * bgmmc_.buffer_a_chunk_sz;
}
char *get_buf_B_ptr(int ithr, int k_blk_idx, int n_blk_idx) const {
UNUSED(n_blk_idx);
if (!bgmmc_.use_buffer_b) return nullptr;
return buf_B_ptr_ + ithr * bgmmc_.buffer_b_per_thread_sz
+ k_blk_idx * bgmmc_.buffer_b_chunk_sz;
}
char *get_buf_C_ptr(int ithr, int m_blk_idx, int n_blk_idx) const {
if (!bgmmc_.use_buffer_c) return nullptr;
if (bgmmc_.nthr_k > 1) {
const int nthr_k = bgmmc_.nthr_k <= nthr_ ? bgmmc_.nthr_k : 1;
const int nthr_bmn = nthr_ / nthr_k;
const int ithr_k = ithr / nthr_bmn;
return get_buf_C_par_reduction_ptr(ithr_k, m_blk_idx, n_blk_idx);
}
const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size;
const int n_blk_local = n_blk_idx % bgmmc_.N_chunk_size;
const int buf_idx = bgmmc_.N_chunk_size * m_blk_local + n_blk_local;
return buf_C_ptr_ + ithr * bgmmc_.buffer_c_per_thread_sz
+ buf_idx * bgmmc_.buffer_c_chunk_sz;
}
char *get_buf_C_par_reduction_ptr(
int ithr_k, int m_blk_idx, int n_blk_idx) const {
if (bgmmc_.nthr_k <= 1) return nullptr;
const int m = m_blk_idx * bgmmc_.M_blk;
const int n = n_blk_idx * bgmmc_.N_blk;
if (!bgmmc_.post_ops_applicable && ithr_k == 0)
return get_data_C_ptr(0, m, n);
int k_buf_idx = ithr_k - (!bgmmc_.post_ops_applicable ? 1 : 0);
return buf_C_ptr_ + k_buf_idx * bgmmc_.buffer_c_per_thread_sz
+ get_data_C_off(0, m, n) * bgmmc_.acc_dt_sz / bgmmc_.c_dt_sz;
}
// Auxiliary functions for getting offsets with pre-calculated memory
// strides for each tensor to get general sulution for all possible
// dimension without significant overhead
dim_t get_data_A_off(int b, int m, int k) const {
using namespace format_tag;
if (bgmmc_.src_tag == acbd || bgmmc_.src_tag == adbc) {
dim_t b_off = 0;
if (!bgmmc_.bcast_A_desc.bcast_mask) { // no broadcast
const dim_t batch_dim1 = bgmmc_.bcast_A_desc.batch_dims[1];
b_off = bgmmc_.A_strides[2] * (b % batch_dim1)
+ (b / batch_dim1) * bgmmc_.A_ptr_shift_b;
} else {
b_off = b * bgmmc_.A_ptr_shift_b;
}
return b_off + bgmmc_.A_strides[1] * m + bgmmc_.A_strides[0] * k;
} else {
return bgmmc_.A_strides[2] * b + bgmmc_.A_strides[1] * m
+ bgmmc_.A_strides[0] * k;
}
}
dim_t get_data_B_off(int b, int k, int n) const {
using namespace format_tag;
if (bgmmc_.wei_tag == acbd || bgmmc_.wei_tag == adbc) {
dim_t b_off = 0;
if (!bgmmc_.bcast_B_desc.bcast_mask) { // no broadcast
const dim_t batch_dim1 = bgmmc_.bcast_B_desc.batch_dims[1];
b_off = bgmmc_.B_strides[2] * (b % batch_dim1)
+ (b / batch_dim1) * bgmmc_.B_ptr_shift_b;
} else {
b_off = b * bgmmc_.B_ptr_shift_b;
}
return b_off + bgmmc_.B_strides[1] * k + bgmmc_.B_strides[0] * n;
} else {
int dt_b_k_blk = bgmmc_.is_bf32
? data_type_vnni_simd_elems<avx512_core>(f32)
: bgmmc_.wei_k_blk;
int k_idx = bgmmc_.blocked_B ? k / dt_b_k_blk : k;
int n_idx = bgmmc_.blocked_B ? n / bgmmc_.wei_n_blk : n;
return bgmmc_.B_strides[2] * b + bgmmc_.B_strides[1] * k_idx
+ bgmmc_.B_strides[0] * n_idx
+ get_data_B_off_within_block(k, n);
}
}
dim_t get_data_B_off_within_block(int k, int n) const {
using namespace format_tag;
if (!bgmmc_.blocked_B) return 0;
int x0 = k % bgmmc_.wei_k_blk;
int x1 = n % bgmmc_.wei_n_blk;
dim_t offset = (x0 / vnni_factor) * vnni_factor * bgmmc_.wei_n_blk
+ x1 * vnni_factor + x0 % vnni_factor;
return bgmmc_.b_dt_sz * offset;
}
dim_t get_data_C_off(int b, int m, int n) const {
using namespace format_tag;
assert(bgmmc_.dst_tag != adbc);
if (bgmmc_.dst_tag == acbd) {
const dim_t batch_dim1 = bgmmc_.bcast_A_desc.batch_dims[1];
dim_t b_off = bgmmc_.C_strides[2] * (b % batch_dim1)
+ (b / batch_dim1) * bgmmc_.C_ptr_shift_b;
return b_off + bgmmc_.C_strides[1] * m + bgmmc_.C_strides[0] * n;
} else {
return bgmmc_.C_strides[2] * b + bgmmc_.C_strides[1] * m
+ bgmmc_.C_strides[0] * n;
}
}
const char *get_bias_ptr(int n) const {
if (!bgmmc_.with_bias) return nullptr;
return bias_ptr_ + n * bgmmc_.bias_dt_sz;
}
int32_t *get_s8s8_comp_ptr(int ithr, int b, int n_blk_idx) const {
if (!bgmmc_.s8s8_compensation_required) return nullptr;
const int n_blk_local = bgmmc_.use_buffer_b
? n_blk_idx % bgmmc_.N_chunk_size
: n_blk_idx;
return s8s8_compensation_ptr_ + ithr * bgmmc_.s8s8_comp_ithr_str
+ b * bgmmc_.s8s8_comp_b_str
+ n_blk_local * bgmmc_.s8s8_comp_n_str;
}
const float *get_oscales_ptr(int n) const {
return oscales_ptr_ + bgmmc_.is_oscale_per_n * n;
}
const int32_t *get_zp_a_neg_val_ptr() const {
return &zero_point_a_negative_val_;
}
const int32_t *get_zp_b_neg_val_ptr() const {
return &zero_point_b_negative_val_;
}
const int32_t *get_zp_ab_mixed_comp_ptr() const {
return &zero_point_mixed_ab_compensation_component_;
}
const int32_t *get_zp_c_val_ptr() const { return &zero_point_c_val_; }
int32_t *get_zp_a_compensation_ptr(int ithr, int n_blk_idx) const {
if (!bgmmc_.has_zero_point_a) return nullptr;
const int n_blk_local = n_blk_idx % bgmmc_.N_chunk_size;
int32_t *zp_comp = zero_point_a_compensations_ptr_
+ ithr * bgmmc_.zp_a_comp_elems_per_thr
+ n_blk_local * bgmmc_.zp_a_comp_shift_n;
if (bgmmc_.blocked_B) {
// Scale computed in reorder compensation values by zp_a value
// locally just before usage. Using the single global scaling before
// parallel section might produce significant overhead for small
// problems running in multitreaded execution mode
const int base_offset = n_blk_idx * bgmmc_.wei_n_blk;
PRAGMA_OMP_SIMD()
for (int b = 0; b < bgmmc_.wei_n_blk; b++)
zp_comp[b] = -zero_point_a_negative_val_
* reorder_zp_a_comp_ptr_[base_offset + b];
}
return zp_comp;
}
int32_t *get_zp_b_compensation_result_ptr(int ithr, int m_blk_idx) const {
if (!bgmmc_.has_zero_point_b) return nullptr;
const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size;
return zero_point_b_compensations_ptr_
+ ithr * bgmmc_.zp_b_comp_elems_per_thr
+ m_blk_local * bgmmc_.zp_b_comp_result_shift_m;
}
int32_t *get_zp_b_compensation_buffer_ptr(int ithr, int m_blk_idx) const {
if (!bgmmc_.has_zero_point_b) return nullptr;
const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size;
return get_zp_b_compensation_result_ptr(ithr, 0)
+ bgmmc_.zp_b_comp_buffer_start
+ m_blk_local * bgmmc_.zp_b_comp_buffer_shift_m;
}
char *get_tile_workspace(int ithr) const {
return is_amx_ ? wsp_tile_ptr_ + ithr * bgmmc_.wsp_tile_per_thr_bytes
: nullptr;
}
const std::vector<const void *> &get_post_ops_binary_rhs_arg_vec() const {
return post_ops_binary_rhs_arg_vec_;
}
int get_base_brgemm_kernel_idx() const { return base_brg_ker_idx_; }
bool is_last_K_chunk(int k_chunk_idx) const {
return k_chunk_idx == bgmmc_.K_chunks - 1;
}
int get_brgemm_batch_size(int k_chunk_idx) const {
return is_last_K_chunk(k_chunk_idx) ? last_chunk_brgemm_batch_size_
: bgmmc_.brgemm_batch_size;
}
int get_parallel_work_amount() const { return parallel_work_amount_; }
int get_num_threads_for_k() const { return nthr_k_; }
bool parallel_reduction_is_used() const {
return nthr_k_ > 1 && bgmmc_.K_chunks > 1;
}
int get_num_threads_for_bmn() const { return nthr_bmn_; }
// ithr = ithr_k * nthr_bmn + ithr_bmn
int get_thread_idx_for_k(int ithr) const {
if (ithr >= num_threads_used_) return -1;
const int ithr_k = ithr / nthr_bmn_;
return ithr_k < bgmmc_.K_chunks ? ithr_k : -1;
}
int get_thread_idx_for_bmn(int ithr) const {
if (ithr >= num_threads_used_) return -1;
const int ithr_bmn = ithr % nthr_bmn_;
return ithr_bmn < parallel_work_amount_ ? ithr_bmn : -1;
}
int get_num_threads_for_parallelization() const { return nthr_; }
private:
bool is_amx_;
const brgemm_matmul_conf_t &bgmmc_;
const char *data_A_ptr_;
const char *data_B_ptr_;
char *data_C_ptr_;
brgemm_batch_element_t *batch_element_ptr_;
char *buf_A_ptr_;
char *buf_B_ptr_;
char *buf_C_ptr_;
char *wsp_tile_ptr_;
const char *bias_ptr_;
const float *oscales_ptr_;
int32_t *s8s8_compensation_ptr_;
int32_t *zero_point_a_compensations_ptr_;
int32_t *zero_point_b_compensations_ptr_;
int32_t *reorder_zp_a_comp_ptr_;
int32_t zero_point_a_negative_val_;
int32_t zero_point_b_negative_val_;
int32_t zero_point_mixed_ab_compensation_component_;
int32_t zero_point_c_val_;
std::vector<const void *> post_ops_binary_rhs_arg_vec_;
int base_brg_ker_idx_;
int vnni_factor;
// parallelization parameters
int parallel_work_amount_;
int nthr_, nthr_k_, nthr_bmn_, num_threads_used_;
int last_chunk_brgemm_batch_size_;
};
template struct brgemm_matmul_t<avx512_core_bf16_amx_int8>;
template struct brgemm_matmul_t<avx512_core_bf16_amx_bf16>;
template struct brgemm_matmul_t<avx512_core_bf16>;
template struct brgemm_matmul_t<avx512_core_vnni>;
template struct brgemm_matmul_t<avx512_core>;
} // namespace matmul
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace dnnl
| 43.205082
| 80
| 0.608943
|
cfRod
|
60d9059ece51cd24e336ac5ee1826e2a584293f4
| 307
|
hxx
|
C++
|
src/mod/pub/tst/sws/sws-drop-down-list-tst/mod-sws-drop-down-list-tst.hxx
|
indigoabstract/appplex
|
83c3b903db6c6ea83690ccffbd533ff6ab01d246
|
[
"MIT"
] | 1
|
2017-12-26T14:29:37.000Z
|
2017-12-26T14:29:37.000Z
|
src/mod/pub/tst/sws/sws-drop-down-list-tst/mod-sws-drop-down-list-tst.hxx
|
indigoabstract/appplex
|
83c3b903db6c6ea83690ccffbd533ff6ab01d246
|
[
"MIT"
] | null | null | null |
src/mod/pub/tst/sws/sws-drop-down-list-tst/mod-sws-drop-down-list-tst.hxx
|
indigoabstract/appplex
|
83c3b903db6c6ea83690ccffbd533ff6ab01d246
|
[
"MIT"
] | null | null | null |
#pragma once
#include "appplex-conf.hxx"
#ifdef MOD_SWS_DROP_DOWN_LIST_TST
#include "mws-mod.hxx"
class mod_sws_drop_down_list_tst : public mws_mod
{
public:
static mws_sp<mod_sws_drop_down_list_tst> nwi();
virtual void build_sws() override;
private:
mod_sws_drop_down_list_tst();
};
#endif
| 14.619048
| 51
| 0.765472
|
indigoabstract
|
60db821a92f86bbc26237642c9e518a42ace9403
| 5,349
|
cpp
|
C++
|
FECore/FEModelParam.cpp
|
Scriptkiddi/FEBioStudio
|
b4cafde6b2761c9184e7e66451a9555b81a8a3dc
|
[
"MIT"
] | null | null | null |
FECore/FEModelParam.cpp
|
Scriptkiddi/FEBioStudio
|
b4cafde6b2761c9184e7e66451a9555b81a8a3dc
|
[
"MIT"
] | null | null | null |
FECore/FEModelParam.cpp
|
Scriptkiddi/FEBioStudio
|
b4cafde6b2761c9184e7e66451a9555b81a8a3dc
|
[
"MIT"
] | null | null | null |
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEModelParam.h"
#include "MObjBuilder.h"
#include "FEDataArray.h"
#include "DumpStream.h"
#include "FEConstValueVec3.h"
//---------------------------------------------------------------------------------------
FEModelParam::FEModelParam()
{
m_scl = 1.0;
m_dom = 0;
}
FEModelParam::~FEModelParam()
{
}
// serialization
void FEModelParam::Serialize(DumpStream& ar)
{
ar & m_scl;
}
//---------------------------------------------------------------------------------------
FEParamDouble::FEParamDouble()
{
m_val = fecore_new<FEScalarValuator>("const", nullptr);
}
FEParamDouble::~FEParamDouble()
{
delete m_val;
}
FEParamDouble::FEParamDouble(const FEParamDouble& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamDouble::operator = (double v)
{
FEConstValue* val = fecore_new<FEConstValue>("const", nullptr);
*val->constValue() = v;
setValuator(val);
}
// set the valuator
void FEParamDouble::setValuator(FEScalarValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
// get the valuator
FEScalarValuator* FEParamDouble::valuator()
{
return m_val;
}
// is this a const value
bool FEParamDouble::isConst() const { return m_val->isConst(); };
// get the const value (returns 0 if param is not const)
double& FEParamDouble::constValue() { assert(isConst()); return *m_val->constValue(); }
double FEParamDouble::constValue() const { assert(isConst()); return *m_val->constValue(); }
void FEParamDouble::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
bool FEParamDouble::Init()
{
return (m_val ? m_val->Init() : true);
}
//---------------------------------------------------------------------------------------
FEParamVec3::FEParamVec3()
{
m_val = fecore_new<FEVec3dValuator>("vector", nullptr);
}
FEParamVec3::~FEParamVec3()
{
delete m_val;
}
FEParamVec3::FEParamVec3(const FEParamVec3& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamVec3::operator = (const vec3d& v)
{
FEConstValueVec3* val = fecore_new<FEConstValueVec3>("vector", nullptr);
val->value() = v;
setValuator(val);
}
// set the valuator
void FEParamVec3::setValuator(FEVec3dValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
void FEParamVec3::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
//==========================================================================
FEParamMat3d::FEParamMat3d()
{
m_val = fecore_new<FEMat3dValuator>("const", nullptr);
}
FEParamMat3d::~FEParamMat3d()
{
delete m_val;
}
FEParamMat3d::FEParamMat3d(const FEParamMat3d& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamMat3d::operator = (const mat3d& v)
{
FEConstValueMat3d* val = fecore_new<FEConstValueMat3d>("const", nullptr);
val->value() = v;
setValuator(val);
}
// set the valuator
void FEParamMat3d::setValuator(FEMat3dValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
// get the valuator
FEMat3dValuator* FEParamMat3d::valuator()
{
return m_val;
}
void FEParamMat3d::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
//==========================================================================
FEParamMat3ds::FEParamMat3ds()
{
m_val = fecore_new<FEMat3dsValuator>("const", nullptr);
}
FEParamMat3ds::~FEParamMat3ds()
{
delete m_val;
}
FEParamMat3ds::FEParamMat3ds(const FEParamMat3ds& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamMat3ds::operator = (const mat3ds& v)
{
FEConstValueMat3ds* val = fecore_new<FEConstValueMat3ds>("const", nullptr);
val->value() = v;
setValuator(val);
}
// set the valuator
void FEParamMat3ds::setValuator(FEMat3dsValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
void FEParamMat3ds::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
| 22.56962
| 92
| 0.673584
|
Scriptkiddi
|
60dc323d8adce98e1d3c9d35cc26ada21b77c606
| 1,722
|
cc
|
C++
|
atom/browser/net/url_request_string_job.cc
|
Jeket/electron
|
f41cce96a3afa8c4cf6fe57f9ec904502abed524
|
[
"MIT"
] | 7
|
2018-02-05T11:43:49.000Z
|
2022-02-09T20:28:20.000Z
|
atom/browser/net/url_request_string_job.cc
|
Jeket/electron
|
f41cce96a3afa8c4cf6fe57f9ec904502abed524
|
[
"MIT"
] | 1
|
2018-04-03T23:04:37.000Z
|
2018-04-03T23:04:37.000Z
|
atom/browser/net/url_request_string_job.cc
|
Jeket/electron
|
f41cce96a3afa8c4cf6fe57f9ec904502abed524
|
[
"MIT"
] | 2
|
2017-08-25T18:58:44.000Z
|
2019-10-22T14:59:04.000Z
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/url_request_string_job.h"
#include <string>
#include "atom/common/atom_constants.h"
#include "net/base/net_errors.h"
namespace atom {
URLRequestStringJob::URLRequestStringJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate)
: JsAsker<net::URLRequestSimpleJob>(request, network_delegate) {
}
void URLRequestStringJob::StartAsync(std::unique_ptr<base::Value> options) {
if (options->IsType(base::Value::Type::DICTIONARY)) {
base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(options.get());
dict->GetString("mimeType", &mime_type_);
dict->GetString("charset", &charset_);
dict->GetString("data", &data_);
} else if (options->IsType(base::Value::Type::STRING)) {
options->GetAsString(&data_);
}
net::URLRequestSimpleJob::Start();
}
void URLRequestStringJob::GetResponseInfo(net::HttpResponseInfo* info) {
std::string status("HTTP/1.1 200 OK");
auto* headers = new net::HttpResponseHeaders(status);
headers->AddHeader(kCORSHeader);
if (!mime_type_.empty()) {
std::string content_type_header(net::HttpRequestHeaders::kContentType);
content_type_header.append(": ");
content_type_header.append(mime_type_);
headers->AddHeader(content_type_header);
}
info->headers = headers;
}
int URLRequestStringJob::GetData(
std::string* mime_type,
std::string* charset,
std::string* data,
const net::CompletionCallback& callback) const {
*mime_type = mime_type_;
*charset = charset_;
*data = data_;
return net::OK;
}
} // namespace atom
| 28.7
| 76
| 0.713705
|
Jeket
|
60dc566e97861e559e5f744a595e973d2fd05a11
| 7,141
|
cc
|
C++
|
tensorflow/compiler/mlir/xla/transforms/legalize_tf_control_flow.cc
|
5GApp/tensorflow
|
ca87089f9e0073bad9fc999ce9c318f661d2e425
|
[
"Apache-2.0"
] | 1
|
2019-12-23T20:23:43.000Z
|
2019-12-23T20:23:43.000Z
|
tensorflow/compiler/mlir/xla/transforms/legalize_tf_control_flow.cc
|
5GApp/tensorflow
|
ca87089f9e0073bad9fc999ce9c318f661d2e425
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/compiler/mlir/xla/transforms/legalize_tf_control_flow.cc
|
5GApp/tensorflow
|
ca87089f9e0073bad9fc999ce9c318f661d2e425
|
[
"Apache-2.0"
] | 1
|
2020-04-22T01:47:46.000Z
|
2020-04-22T01:47:46.000Z
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file implements logic for lowering TensorFlow dialect's control flow to
// the XLA dialect.
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <numeric>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/iterator_range.h"
#include "mlir/Dialect/StandardOps/Ops.h" // TF:local_config_mlir
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/BlockAndValueMapping.h" // TF:local_config_mlir
#include "mlir/IR/Function.h" // TF:local_config_mlir
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Module.h" // TF:local_config_mlir
#include "mlir/IR/Operation.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "mlir/IR/TypeUtilities.h" // TF:local_config_mlir
#include "mlir/IR/Types.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Pass/PassRegistry.h" // TF:local_config_mlir
#include "mlir/Transforms/DialectConversion.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h"
#include "tensorflow/compiler/mlir/xla/transforms/passes.h"
#include "tensorflow/core/util/tensor_format.h"
using mlir::PassRegistration;
namespace mlir {
namespace xla_hlo {
namespace {
class LegalizeTFControlFlow : public ModulePass<LegalizeTFControlFlow> {
public:
void runOnModule() override;
};
} // namespace
std::unique_ptr<mlir::OpPassBase<mlir::ModuleOp>>
createLegalizeTFControlFlowPass() {
return std::make_unique<LegalizeTFControlFlow>();
}
namespace {
void Detuple(ValuePtr tuple, Operation::result_range replace,
OpBuilder* builder) {
// De-tuple the results of the xla hlo conditional result.
for (auto result_it : llvm::enumerate(replace)) {
auto get_tuple_value = builder->create<xla_hlo::GetTupleElementOp>(
result_it.value()->getLoc(), tuple, result_it.index());
result_it.value()->replaceAllUsesWith(get_tuple_value);
}
}
// Imports the source region into the destination region. The XLA conditional
// operation only supports one argument per branch. Therefore any branch that
// requires additional arguments requires their values be tupled together. Then,
// to support multiple returns (as XLA only supports a single return value) the
// results of the conditional are tupled together.
void ImportXlaRegion(mlir::FuncOp func, Region* dest_region, Location loc,
bool tuple_return = true) {
BlockAndValueMapping mapper;
OpBuilder builder(dest_region);
auto entry_block = builder.createBlock(dest_region);
auto tuple_arg = entry_block->addArgument(
builder.getTupleType(func.getType().getInputs()));
llvm::SmallVector<ValuePtr, 4> detupled_args;
detupled_args.reserve(func.getNumArguments());
for (int64_t i = 0, s = func.getNumArguments(); i < s; i++) {
auto extract = builder.create<GetTupleElementOp>(loc, tuple_arg, i);
detupled_args.push_back(extract);
}
auto result = builder.create<CallOp>(loc, func, detupled_args).getResults();
if (!tuple_return) {
builder.create<xla_hlo::ReturnOp>(loc, result);
} else {
auto tuple_op = builder.create<TupleOp>(loc, result);
builder.create<xla_hlo::ReturnOp>(loc, tuple_op.getResult());
}
}
void LowerIf(TF::IfOp op, ModuleOp module) {
Location loc = op.getLoc();
OpBuilder builder(op);
// XLA prefers tuple arguments for control flow due to XLA not supporting
// multiple return values.
SmallVector<ValuePtr, 3> inputs(op.input());
builder.setInsertionPoint(op);
auto tuple_input = builder.create<xla_hlo::TupleOp>(loc, inputs);
// Create the new conditional op with tuple inputs.
SmallVector<ValuePtr, 3> operands(op.getOperands());
SmallVector<Type, 4> types(op.getResultTypes());
auto result_type = builder.getTupleType(types);
auto conditional = builder.create<xla_hlo::ConditionalOp>(
loc, result_type, op.cond(), tuple_input, tuple_input);
// Import the regions for both the true and false cases. These regions
// must be updated to tuple the return results together and use the xla hlo
// return op.
BlockAndValueMapping mapper;
auto then_branch = module.lookupSymbol<mlir::FuncOp>(op.then_branch());
auto else_branch = module.lookupSymbol<mlir::FuncOp>(op.else_branch());
ImportXlaRegion(then_branch, &conditional.true_branch(), loc);
ImportXlaRegion(else_branch, &conditional.false_branch(), loc);
// De-tuple the results of the xla hlo conditional result.
builder.setInsertionPointAfter(op);
Detuple(conditional.getResult(), op.getResults(), &builder);
op.erase();
}
void LowerWhile(TF::WhileOp op, ModuleOp module) {
Location loc = op.getLoc();
OpBuilder builder(op);
// XLA prefers tuple arguments for control flow due to XLA not supporting
// multiple return values.
SmallVector<ValuePtr, 3> inputs(op.input());
builder.setInsertionPoint(op);
ValuePtr tuple_input = builder.create<xla_hlo::TupleOp>(loc, inputs);
// Create the new while op with tuple inputs.
SmallVector<ValuePtr, 3> operands(op.getOperands());
SmallVector<Type, 4> types(op.getResultTypes());
auto while_op = builder.create<xla_hlo::WhileOp>(
loc, builder.getTupleType(types), tuple_input);
// Import the regions for both the cond and body. These regions must be
// updated to tuple the return results together and use the xla hlo return op.
auto body_branch = module.lookupSymbol<mlir::FuncOp>(op.body());
auto cond_branch = module.lookupSymbol<mlir::FuncOp>(op.cond());
ImportXlaRegion(body_branch, &while_op.body(), loc);
ImportXlaRegion(cond_branch, &while_op.cond(), loc, /*tuple_return=*/false);
// De-tuple the results of the xla hlo while.
builder.setInsertionPointAfter(op);
Detuple(while_op.getResult(), op.getResults(), &builder);
op.erase();
}
} // namespace
void LegalizeTFControlFlow::runOnModule() {
auto module = getModule();
module.walk([&](TF::WhileOp op) -> void { LowerWhile(op, module); });
module.walk([&](TF::IfOp op) -> void { LowerIf(op, module); });
}
} // namespace xla_hlo
} // namespace mlir
static PassRegistration<mlir::xla_hlo::LegalizeTFControlFlow> cfpass(
"xla-legalize-tf-control-flow",
"Legalize TensorFlow control flow to the XLA dialect");
| 39.236264
| 80
| 0.734071
|
5GApp
|
60dccdae8ea56b5fd5247873927f82ccd820f6e7
| 3,650
|
cpp
|
C++
|
src/project 1/Venda.cpp
|
daviddias99/pharmacy-chain-feup-aeda
|
d4fa732570f3539828a4c4191d733661dfa4fb9c
|
[
"MIT"
] | null | null | null |
src/project 1/Venda.cpp
|
daviddias99/pharmacy-chain-feup-aeda
|
d4fa732570f3539828a4c4191d733661dfa4fb9c
|
[
"MIT"
] | null | null | null |
src/project 1/Venda.cpp
|
daviddias99/pharmacy-chain-feup-aeda
|
d4fa732570f3539828a4c4191d733661dfa4fb9c
|
[
"MIT"
] | null | null | null |
#include "Venda.h"
Venda::Venda(uint cID, string client, uint eID, string empreg, string farm, string time) : idCliente(cID), nomeCliente(client), idEmpregado(eID), nomeEmpregado(empreg), nomeFarmacia(farm) {
preco = 0;
if (time == "") {
this->timestamp_venda = Timestamp();
}
else {
this->timestamp_venda = Timestamp(time);
}
}
void Venda::addReceita(const Receita & receita) {
map<Produto*,uint> produtosReceita = receita.getProdutos();
map<Produto*, uint>::iterator it = produtosReceita.begin();
map<Produto*, uint>::iterator ite = produtosReceita.end();
while (it != ite) {
this->addProduto(it->first, it->second);
it++;
}
}
void Venda::setPreco(float pr) {
preco = pr;
}
void Venda::addProduto(Produto* prod, unsigned int quant, bool vemReceitado, bool vemDeFicheiro) {
map<Produto *, unsigned int>::iterator it;
for (it = produtos.begin(); it != produtos.end(); it++) {
if (*(it->first) == *prod) {
it->second += quant;
return;
}
}
if (!vemDeFicheiro) {
preco += prod->getPreco() * (1 + prod->getIVA()) * quant;
Medicamento* mediTemp = dynamic_cast<Medicamento*> (prod);
if (vemReceitado) {
preco -= mediTemp->descontoComReceita() * mediTemp->getPreco();
}
}
produtos[prod] = quant;
}
pair<Produto*,uint> Venda::getProd(uint prodId)
{
pair<Produto*, unsigned int> resultado = { NULL,0 };
map<Produto*, unsigned int>::iterator it = this->produtos.begin();
map<Produto*, unsigned int>::iterator ite = this->produtos.end();
while (it != ite) {
if (it->first->getCodigo() == prodId) {
return *it;
}
it++;
}
return resultado;
}
pair<Produto*, uint> Venda::getProd(string nome)
{
pair<Produto*, unsigned int> resultado = { NULL,0 };
map<Produto*, unsigned int>::iterator it = this->produtos.begin();
map<Produto*, unsigned int>::iterator ite = this->produtos.end();
while (it != ite) {
if (it->first->getNome() == nome) {
return *it;
}
}
return resultado;
}
void Venda::remProduto(string nome)
{
map<Produto*, unsigned int>::iterator it = this->produtos.begin();
map<Produto*, unsigned int>::iterator ite = this->produtos.end();
while (it != ite) {
if (it->first->getNome() == nome) {
preco -= it->first->getPreco() * (1 + it->first->getIVA()) * it->second;
produtos.erase(it);
return;
}
it++;
}
}
float Venda::getCusto() const {
return preco;
}
string Venda::getNomeFarm() const
{
return nomeFarmacia;
}
string Venda::getNomeCliente() const
{
return nomeCliente;
}
string Venda::getNomeEmp() const
{
return nomeEmpregado;
}
map<Produto*, uint>& Venda::getProdutos()
{
return this->produtos;
}
ostream & Venda::print(ostream & os) const
{
os << endl << "RECIBO VENDA" << endl << endl;
os << timestamp_venda << endl;
os << "Farmacia: " << nomeFarmacia << endl;
os << "Cliente - ID: " << idCliente << " Nome: " << nomeCliente << endl;
os << "Empregado - ID: " << idEmpregado << " Nome: " << nomeEmpregado << endl;
os << "Produtos: " << endl;
for (map<Produto *, uint>::const_iterator it = produtos.begin(); it != produtos.end(); it++) {
os << "-";
it->first->print(cout) << "#Quantidade: " << it->second << endl << endl;
}
os << "Preco final: " << setprecision(2) << preco;
return os;
}
ostream & Venda::printSimp(ostream & os) const
{
os << preco << "\\" << timestamp_venda << "\\" << nomeFarmacia << "\\" << idCliente << "\\" << nomeCliente << "\\" << idEmpregado << "\\" << nomeEmpregado << "\\";
for (map<Produto *, unsigned int>::const_iterator it = produtos.begin(); it != produtos.end(); it++) {
it->first->printSimp(os);
os << "#" << it->second << "!";
}
return os;
}
| 21.856287
| 189
| 0.62274
|
daviddias99
|
60de989362d80602f82c1e9ce89708866107e400
| 14,767
|
hxx
|
C++
|
Modules/Nonunit/Review/include/itkRegionBasedLevelSetFunction.hxx
|
arobert01/ITK
|
230d319fdeaa3877273fab5d409dd6c11f0a6874
|
[
"Apache-2.0"
] | 1
|
2021-08-19T14:33:55.000Z
|
2021-08-19T14:33:55.000Z
|
Modules/Nonunit/Review/include/itkRegionBasedLevelSetFunction.hxx
|
arobert01/ITK
|
230d319fdeaa3877273fab5d409dd6c11f0a6874
|
[
"Apache-2.0"
] | null | null | null |
Modules/Nonunit/Review/include/itkRegionBasedLevelSetFunction.hxx
|
arobert01/ITK
|
230d319fdeaa3877273fab5d409dd6c11f0a6874
|
[
"Apache-2.0"
] | 1
|
2022-02-16T08:20:20.000Z
|
2022-02-16T08:20:20.000Z
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 itkRegionBasedLevelSetFunction_hxx
#define itkRegionBasedLevelSetFunction_hxx
#include "itkRegionBasedLevelSetFunction.h"
#include "itkImageRegionIteratorWithIndex.h"
namespace itk
{
template <typename TInput, typename TFeature, typename TSharedData>
double RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::m_WaveDT = 1.0 / (2.0 * ImageDimension);
template <typename TInput, typename TFeature, typename TSharedData>
double RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::m_DT = 1.0 / (2.0 * ImageDimension);
template <typename TInput, typename TFeature, typename TSharedData>
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::RegionBasedLevelSetFunction()
{
m_Lambda1 = NumericTraits<ScalarValueType>::OneValue();
m_Lambda2 = NumericTraits<ScalarValueType>::OneValue();
m_OverlapPenaltyWeight = NumericTraits<ScalarValueType>::ZeroValue();
m_AreaWeight = NumericTraits<ScalarValueType>::ZeroValue();
m_VolumeMatchingWeight = NumericTraits<ScalarValueType>::ZeroValue();
m_ReinitializationSmoothingWeight = NumericTraits<ScalarValueType>::ZeroValue();
m_CurvatureWeight = m_AdvectionWeight = NumericTraits<ScalarValueType>::ZeroValue();
m_Volume = NumericTraits<ScalarValueType>::ZeroValue();
m_FunctionId = 0;
m_SharedData = nullptr;
m_InitialImage = nullptr;
m_FeatureImage = nullptr;
m_UpdateC = false;
for (unsigned int i = 0; i < ImageDimension; ++i)
{
m_InvSpacing[i] = 1;
}
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::VectorType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::InitializeZeroVectorConstant()
{
VectorType ans;
for (unsigned int i = 0; i < ImageDimension; ++i)
{
ans[i] = NumericTraits<ScalarValueType>::ZeroValue();
}
return ans;
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::VectorType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::m_ZeroVectorConstant =
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::InitializeZeroVectorConstant();
/* Computes the Heaviside function and stores it in
m_HeavisideFunctionOfLevelSetImage */
template <typename TInput, typename TFeature, typename TSharedData>
void
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeHImage()
{
// The phi function
InputImageConstPointer contourImage = this->m_InitialImage;
InputImagePointer hBuffer =
this->m_SharedData->m_LevelSetDataPointerVector[this->m_FunctionId]->m_HeavisideFunctionOfLevelSetImage;
// Iterator for the phi function
using ConstImageIteratorType = ImageRegionConstIteratorWithIndex<InputImageType>;
ConstImageIteratorType constIt(contourImage, contourImage->GetRequestedRegion());
using ImageIteratorType = ImageRegionIteratorWithIndex<InputImageType>;
ImageIteratorType It(hBuffer, hBuffer->GetRequestedRegion());
It.GoToBegin(), constIt.GoToBegin();
while (!constIt.IsAtEnd())
{
// Convention is inside of level-set function is negative
ScalarValueType hVal = m_DomainFunction->Evaluate(-constIt.Get());
It.Set(hVal);
++It;
++constIt;
}
}
template <typename TInput, typename TFeature, typename TSharedData>
void
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::UpdateSharedData(bool forceUpdate)
{
if (forceUpdate)
{
// Must update all H before updating C
this->ComputeHImage();
this->m_UpdateC = false;
}
else
{
if (!this->m_UpdateC)
{
this->ComputeParameters();
this->m_UpdateC = true;
}
this->UpdateSharedDataParameters();
}
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::TimeStepType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeGlobalTimeStep(void * GlobalData) const
{
/* Computing the time-step for stable curve evolution */
TimeStepType dt = 0.0;
auto * d = (GlobalDataStruct *)GlobalData;
if (itk::Math::abs(d->m_MaxCurvatureChange) > itk::Math::eps)
{
if (d->m_MaxAdvectionChange > itk::Math::eps)
{
dt = std::min((m_WaveDT / d->m_MaxAdvectionChange), (this->m_DT / d->m_MaxCurvatureChange));
}
else
{
dt = this->m_DT / d->m_MaxCurvatureChange;
}
}
else
{
if (d->m_MaxAdvectionChange > itk::Math::eps)
{
// NOTE: What's the difference between this->m_WaveDT and this->m_DT?
dt = this->m_WaveDT / d->m_MaxAdvectionChange;
}
}
// Reset the values
d->m_MaxCurvatureChange = NumericTraits<ScalarValueType>::ZeroValue();
d->m_MaxGlobalChange = NumericTraits<ScalarValueType>::ZeroValue();
d->m_MaxAdvectionChange = NumericTraits<ScalarValueType>::ZeroValue();
return dt;
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ScalarValueType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeCurvature(const NeighborhoodType & itkNotUsed(it),
const FloatOffsetType & itkNotUsed(offset),
GlobalDataStruct * gd)
{
// Calculate the mean curvature
ScalarValueType curvature = NumericTraits<ScalarValueType>::ZeroValue();
unsigned int i, j;
for (i = 0; i < ImageDimension; ++i)
{
for (j = 0; j < ImageDimension; ++j)
{
if (j != i)
{
curvature -= gd->m_dx[i] * gd->m_dx[j] * gd->m_dxy[i][j];
curvature += gd->m_dxy[j][j] * gd->m_dx[i] * gd->m_dx[i];
}
}
}
if (gd->m_GradMag > itk::Math::eps)
{
curvature /= gd->m_GradMag * gd->m_GradMag * gd->m_GradMag;
}
else
{
curvature /= 1 + gd->m_GradMagSqr;
}
return curvature;
}
// Compute the Hessian matrix and various other derivatives. Some of these
// derivatives may be used by overloaded virtual functions.
template <typename TInput, typename TFeature, typename TSharedData>
void
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeHessian(const NeighborhoodType & it,
GlobalDataStruct * gd)
{
const ScalarValueType inputValue = it.GetCenterPixel();
gd->m_GradMagSqr = 0.;
gd->m_GradMag = 0.;
unsigned int i, j;
for (i = 0; i < ImageDimension; ++i)
{
const auto positionA = static_cast<unsigned int>(this->m_Center + this->m_xStride[i]);
const auto positionB = static_cast<unsigned int>(this->m_Center - this->m_xStride[i]);
gd->m_dx[i] = 0.5 * (this->m_InvSpacing[i]) * (it.GetPixel(positionA) - it.GetPixel(positionB));
gd->m_dx_forward[i] = (this->m_InvSpacing[i]) * (it.GetPixel(positionA) - inputValue);
gd->m_dx_backward[i] = (this->m_InvSpacing[i]) * (inputValue - it.GetPixel(positionB));
gd->m_GradMagSqr += gd->m_dx[i] * gd->m_dx[i];
gd->m_dxy[i][i] = (this->m_InvSpacing[i]) * (gd->m_dx_forward[i] - gd->m_dx_backward[i]);
for (j = i + 1; j < ImageDimension; ++j)
{
const auto positionAa = static_cast<unsigned int>(this->m_Center - this->m_xStride[i] - this->m_xStride[j]);
const auto positionBa = static_cast<unsigned int>(this->m_Center - this->m_xStride[i] + this->m_xStride[j]);
const auto positionCa = static_cast<unsigned int>(this->m_Center + this->m_xStride[i] - this->m_xStride[j]);
const auto positionDa = static_cast<unsigned int>(this->m_Center + this->m_xStride[i] + this->m_xStride[j]);
gd->m_dxy[i][j] = gd->m_dxy[j][i] =
0.25 * (this->m_InvSpacing[i]) * (this->m_InvSpacing[j]) *
(it.GetPixel(positionAa) - it.GetPixel(positionBa) + it.GetPixel(positionDa) - it.GetPixel(positionCa));
}
}
gd->m_GradMag = std::sqrt(gd->m_GradMagSqr);
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::PixelType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeUpdate(const NeighborhoodType & it,
void * globalData,
const FloatOffsetType & offset)
{
// Access the neighborhood center pixel of phi
const ScalarValueType inputValue = it.GetCenterPixel();
ScalarValueType laplacian_term = NumericTraits<ScalarValueType>::ZeroValue();
ScalarValueType curvature_term = NumericTraits<ScalarValueType>::ZeroValue();
ScalarValueType curvature = NumericTraits<ScalarValueType>::ZeroValue();
ScalarValueType globalTerm = NumericTraits<ScalarValueType>::ZeroValue();
VectorType advection_field;
ScalarValueType x_energy, advection_term = NumericTraits<ScalarValueType>::ZeroValue();
// Access the global data structure
auto * gd = (GlobalDataStruct *)globalData;
ComputeHessian(it, gd);
ScalarValueType dh = m_DomainFunction->EvaluateDerivative(-inputValue);
// Computing the curvature term
// Used to regularized using the length of contour
if ((dh != 0.) && (this->m_CurvatureWeight != NumericTraits<ScalarValueType>::ZeroValue()))
{
curvature = this->ComputeCurvature(it, offset, gd);
curvature_term = this->m_CurvatureWeight * curvature * this->CurvatureSpeed(it, offset, gd) * dh;
gd->m_MaxCurvatureChange = std::max(gd->m_MaxCurvatureChange, itk::Math::abs(curvature_term));
}
// Computing the laplacian term
// Used in maintaining squared distance function
if (this->m_ReinitializationSmoothingWeight != NumericTraits<ScalarValueType>::ZeroValue())
{
laplacian_term = this->ComputeLaplacian(gd) - curvature;
laplacian_term *= this->m_ReinitializationSmoothingWeight * this->LaplacianSmoothingSpeed(it, offset, gd);
}
if ((dh != 0.) && (m_AdvectionWeight != NumericTraits<ScalarValueType>::ZeroValue()))
{
advection_field = this->AdvectionField(it, offset, gd);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
x_energy = m_AdvectionWeight * advection_field[i];
// TODO: Is this condition right ?
if (x_energy > NumericTraits<ScalarValueType>::ZeroValue())
{
advection_term += advection_field[i] * gd->m_dx_backward[i];
}
else
{
advection_term += advection_field[i] * gd->m_dx_forward[i];
}
gd->m_MaxAdvectionChange = std::max(gd->m_MaxAdvectionChange, itk::Math::abs(x_energy));
}
advection_term *= m_AdvectionWeight * dh;
}
/* Compute the globalTerm - rms difference of image with c_0 or c_1*/
if (dh != 0.)
{
globalTerm = dh * this->ComputeGlobalTerm(inputValue, it.GetIndex());
}
/* Final update value is the local terms of curvature lengths and laplacian
squared distances - global terms of rms differences of image and piecewise
constant regions*/
auto updateVal = static_cast<PixelType>(curvature_term + laplacian_term + globalTerm + advection_term);
/* If MaxGlobalChange recorded is lower than the current globalTerm */
if (itk::Math::abs(gd->m_MaxGlobalChange) < itk::Math::abs(globalTerm))
{
gd->m_MaxGlobalChange = globalTerm;
}
return updateVal;
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ScalarValueType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeLaplacian(GlobalDataStruct * gd)
{
ScalarValueType laplacian = 0.;
// Compute the laplacian using the existing second derivative values
for (unsigned int i = 0; i < ImageDimension; ++i)
{
laplacian += gd->m_dxy[i][i];
}
return laplacian;
}
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ScalarValueType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeVolumeRegularizationTerm()
{
return 2 *
(this->m_SharedData->m_LevelSetDataPointerVector[this->m_FunctionId]->m_WeightedNumberOfPixelsInsideLevelSet -
this->m_Volume);
}
/* Computes the fidelity term (eg: (intensity - mean)2 ).
Most of the code is concerned with using the appropriate combination
of Heaviside and dirac delta for each part of the fidelity term.
- the final dH is the dirac delta term corresponding to the current
level set we are updating. */
template <typename TInput, typename TFeature, typename TSharedData>
typename RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ScalarValueType
RegionBasedLevelSetFunction<TInput, TFeature, TSharedData>::ComputeGlobalTerm(
const ScalarValueType & itkNotUsed(inputPixel),
const InputIndexType & inputIndex)
{
// computes if it belongs to background
ScalarValueType product = 1;
// Assuming only 1 level set function to be present
auto featIndex = static_cast<FeatureIndexType>(inputIndex);
const FeaturePixelType featureVal = this->m_FeatureImage->GetPixel(inputIndex);
ScalarValueType overlapTerm = 0.;
// This conditional statement computes the amount of overlap s
// and the presence of background pr
if (this->m_SharedData->m_FunctionCount > 1)
{
featIndex = this->m_SharedData->m_LevelSetDataPointerVector[this->m_FunctionId]->GetFeatureIndex(inputIndex);
overlapTerm = this->m_OverlapPenaltyWeight * ComputeOverlapParameters(featIndex, product);
}
ScalarValueType interim = this->m_Lambda1 * this->ComputeInternalTerm(featureVal, featIndex);
ScalarValueType outTerm = this->m_Lambda2 * product * this->ComputeExternalTerm(featureVal, featIndex);
ScalarValueType regularizationTerm =
this->m_VolumeMatchingWeight * ComputeVolumeRegularizationTerm() - this->m_AreaWeight;
ScalarValueType globalTerm = +interim - outTerm + overlapTerm + regularizationTerm;
return globalTerm;
}
} // namespace itk
#endif
| 37.575064
| 120
| 0.707659
|
arobert01
|
60dee2530edceb806c0a2d4f9e00ec189021786d
| 9,708
|
cpp
|
C++
|
src/dev/btietz/tgRBString.cpp
|
wvat/NTRTsim
|
0443cbd542e12e23c04adf79ea0d8d003c428baa
|
[
"Apache-2.0"
] | 148
|
2015-01-08T22:44:00.000Z
|
2022-03-19T18:42:48.000Z
|
src/dev/btietz/tgRBString.cpp
|
wvat/NTRTsim
|
0443cbd542e12e23c04adf79ea0d8d003c428baa
|
[
"Apache-2.0"
] | 107
|
2015-01-02T16:41:42.000Z
|
2021-06-14T22:09:19.000Z
|
src/dev/btietz/tgRBString.cpp
|
wvat/NTRTsim
|
0443cbd542e12e23c04adf79ea0d8d003c428baa
|
[
"Apache-2.0"
] | 86
|
2015-01-06T07:02:36.000Z
|
2022-02-28T17:36:14.000Z
|
/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/
/**
* @file tgRBString.cpp
* @brief Contains the definition of class tgRBString. A string with
* small rigid bodies to create contact dynamics.
* @author Brian Tietz
* @copyright Copyright (C) 2014 NASA Ames Research Center
* $Id$
*/
#include "tgRBString.h"
#include "core/tgLinearString.h"
#include "core/tgCast.h"
// The C++ Standard Library
#include <cmath>
#include <stdexcept>
/**
* Dummy constructor to make the compiler happy.
* @todo remove this
*/
tgRBString::Config::Config()
{
throw std::invalid_argument("Failed to provide arguments to tgRBString::Config");
}
tgRBString::Config::Config( std::size_t segments,
const tgRod::Config& rodConf,
const tgLinearString::Config& stringConf,
double minTotalLength) :
m_segments(segments),
m_rodConfig(rodConf),
m_stringConfig(stringConf),
m_minTotalLength(minTotalLength)
{
}
// @todo consider storing other confing info as a member variable
tgRBString::tgRBString(const tgTags& tags,
tgRBString::Config& config,
double restLength) :
tgBaseString(tags, config.m_stringConfig, restLength, restLength),
m_config(config)
{
}
void tgRBString::setup(tgWorld& world)
{
// These occur after the build process
allSegments = tgCast::filter<tgModel, tgRod> (getDescendants());
assert(allSegments.size() == m_config.m_segments);
allMuscles = this->find<tgLinearString> ("muscle");
// Should we assert something here?
// Consider making this an assert since tensionMinLength also
// Depends on it
if (m_config.m_segments >= 2)
{
const double musclesPerSegment = (double) allMuscles.size() /
(double) (m_config.m_segments - 1);
/* True if all muscles are homogenous, which should be true
* given tgRBStringInfo's use of configs. Should this include
* RB segment mass?
*/
m_effectiveStiffness = m_config.m_stringConfig.stiffness *
musclesPerSegment /
(double) (m_config.m_segments - 1);
}
else
{
// Infinite stiffness means its a single RB, which has no tension
m_effectiveStiffness = 0;
}
// All the heavy lifting is done by info
tgModel::setup(world);
logHistory(0.0);
}
void tgRBString::teardown()
{
tgModel::teardown();
}
void tgRBString::step(double dt)
{
if (dt <= 0.0)
{
throw std::invalid_argument("dt is not positive.");
}
else
{
logHistory(dt);
tgModel::step(dt); // Step any children
#if (1)
std::cout << "Tension: " << getTension() <<
" Calculated Rest: " << getRestLength() <<
" Actual length: " << getCurrentLength() << std::endl;
#endif
}
}
//Does this make myModel an observer as well??
void tgRBString::changeMuscles (double lengthPercent, double dt)
{
if (dt <= 0.0)
{
throw std::invalid_argument("dt is not positive.");
}
else
{
assert(lengthPercent > 0.0);
for( int i = 0; i < allMuscles.size(); i++){
const double rl = allMuscles[i]->getRestLength();
assert(rl > 0.0);
#if (0)
std::cout << "Indiv Muscle " << rl * lengthPercent << std::endl;
#endif
allMuscles[i]->setRestLength(rl * lengthPercent, dt);
}
}
}
void tgRBString::moveMotors(double dt)
{
// @todo add functions from muscle2P Bounded
// Reverse the sign if restLength >= preferredLength
// Velocity limiter
double stepSize = m_config.m_stringConfig.targetVelocity * dt;
// Acceleration limiter
const double velChange = m_config.m_stringConfig.maxAcc * dt;
const double actualLength = getCurrentLength();
const double mostRecentVelocity = m_pHistory->lastVelocities.back();
m_restLength = getRestLength();
double diff = m_preferredLength - m_restLength;
const double fabsDiff = std::abs(diff);
// If below actual length, don't shorten any more
if ((actualLength > m_config.m_stringConfig.minActualLength) ||
(diff > 0))
{
if (abs(diff) > stepSize)
{
//Cap Velocity
if (std::abs((diff/fabsDiff) * m_config.m_stringConfig.targetVelocity -
mostRecentVelocity) >
velChange)
{
// Cap Acceleration
stepSize = velChange * dt;
}
m_restLength += (diff/fabsDiff)*stepSize;
}
else
{
if (std::abs(diff/dt - mostRecentVelocity) > velChange)
{
// Cap Acceleration
if (diff != 0)
{
diff = (diff/fabsDiff) * velChange * dt;
}
else
{
// If m_prevVelocity was zero, it would be smaller than
// velChange. Therefore preVelocity is valid for figuring
// out direction
diff = -(mostRecentVelocity / std::abs(mostRecentVelocity)) *
velChange * dt;
}
}
m_restLength += diff;
}
}
// Ensure we aren't going below min rest length
if(m_restLength >= m_config.m_stringConfig.minRestLength)
{
changeMuscles(m_restLength / getRestLength(), dt);
}
}
void tgRBString::tensionMinLengthController(const double targetTension,
float dt)
{
const double stiffness = m_effectiveStiffness;
// @todo: write invariant that checks this;
assert(stiffness > 0.0);
const double currentTension = getTension();
const double delta = targetTension - currentTension;
double diff = delta / stiffness;
m_restLength = getRestLength();
const double newLength = m_restLength - diff;
m_preferredLength =
(newLength > m_config.m_stringConfig.minRestLength) ?
newLength : m_config.m_stringConfig.minRestLength;
#if (0)
std::cout << "m_preferred: " << m_preferredLength << std::endl;
#endif
moveMotors(dt);
}
const double tgRBString::getStartLength() const
{
return m_pHistory->lastLengths.front();
}
const double tgRBString::getCurrentLength() const
{
double currLength = 0;
// This doesn't consider anchors
std::size_t n = allSegments.size() - 1;
for (std::size_t i = 0; i < n; i++)
{
const btVector3 rodCenterOfMass1 = allSegments[i]->centerOfMass();
const btVector3 rodCenterOfMass2 = allSegments[i + 1]->centerOfMass();
currLength += (rodCenterOfMass2 - rodCenterOfMass1).length();
}
// Add the distance from the COM to the ends of the rods
currLength += allSegments[0]->length();
return currLength;
}
const double tgRBString::getTension() const
{
const double tension = (getCurrentLength() - getRestLength())
* m_effectiveStiffness;
return (tension < 0) ? 0.0 : tension;
}
// How does this relate to m_restLength?
const double tgRBString::getRestLength() const
{
double muscleRest = 0;
double rodRest = 0;
std::size_t segSize = allSegments.size();
for (std::size_t i = 0; i < segSize; i++)
{
rodRest += allSegments[i]->length();
}
std::size_t mSize = allMuscles.size();
for (std::size_t i = 0; i < mSize; i++)
{
muscleRest += allMuscles[i]->getRestLength();
}
// This assumes all four muscles for a given segment have the
// same RL, or that averaging is appropreate
muscleRest /= ((double) mSize / (double) (segSize - 1));
return rodRest + muscleRest;
}
const double tgRBString::getVelocity() const
{
return m_pHistory->lastVelocities.back();
}
const double tgRBString::computeVelocity(const double dt) const
{
// Check to make sure we're calling this at the start of or after
// a log history step
assert (m_pHistory->lastLengths.size() == m_pHistory->lastVelocities.size());
double vel;
if (dt > 0.0)
{
vel = (getCurrentLength() - m_pHistory->lastLengths.back()) / dt;
}
else if (dt == 0.0)
{
// For zero velocity at startup.
vel = 0.0;
}
else
{
throw std::invalid_argument("dt is negitive.");
}
return vel;
}
// Private function, dt should have already been checked
void tgRBString::logHistory(const double dt)
{
const double currentVelocity = computeVelocity(dt);
// Needed for rendering, so not optional
m_pHistory->lastLengths.push_back(getCurrentLength());
// Needed for moveMotors
m_pHistory->lastVelocities.push_back(currentVelocity);
if (m_config.m_stringConfig.hist)
{
// Damping history is difficult to compute, so we're leaving it out
m_pHistory->restLengths.push_back(getRestLength());
m_pHistory->tensionHistory.push_back(getTension());
}
}
| 28.979104
| 85
| 0.626494
|
wvat
|
60e185b99620b37ab58388bc558cc2db494aaa54
| 7,909
|
cpp
|
C++
|
Libraries/Editor/PropertyView.cpp
|
RyanTylerRae/WelderEngineRevamp
|
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
|
[
"MIT"
] | 1
|
2019-07-13T03:36:11.000Z
|
2019-07-13T03:36:11.000Z
|
Libraries/Editor/PropertyView.cpp
|
RyanTylerRae/WelderEngineRevamp
|
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
|
[
"MIT"
] | null | null | null |
Libraries/Editor/PropertyView.cpp
|
RyanTylerRae/WelderEngineRevamp
|
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
|
[
"MIT"
] | null | null | null |
// MIT Licensed (see LICENSE.md).
#include "Precompiled.hpp"
namespace Zero
{
namespace PropertyViewUi
{
const cstr cLocation = "EditorUi/PropertyView";
Tweakable(float, ObjectSize, Pixels(24), cLocation); // Size of objects
Tweakable(float, PropertySize, Pixels(20),
cLocation); // Size of each property widget
Tweakable(float, PropertySpacing, Pixels(2),
cLocation); // Pixels in between each property
Tweakable(float, IndentSize, Pixels(10), cLocation); // Indent per level
} // namespace PropertyViewUi
namespace Events
{
DefineEvent(NameActivated);
DefineEvent(OpenAdd);
} // namespace Events
ZilchDefineType(PropertyView, builder, type)
{
ZilchBindOverloadedMethod(SetObject, ZilchInstanceOverload(void, Object*));
ZilchBindMethod(Refresh);
ZilchBindMethod(Invalidate);
ZilchBindMethod(ActivateAutoUpdate);
}
PropertyView::PropertyView(Composite* parent) : Composite(parent), mFixedHeight(false)
{
mScrollArea = new ScrollArea(this);
mScrollArea->SetClientSize(Pixels(10, 10));
mScrollArea->DisableScrollBar(0);
mMinSize = Vec2(100, 100);
mNamePercent = 0.42f;
mDefSet = parent->GetDefinitionSet()->GetDefinitionSet("PropertyGrid");
mRoot = nullptr;
mPropertyInterface = nullptr;
SetPropertyInterface(&mDefaultPropertyInterface);
ConnectThisTo(this, Events::KeyDown, OnKeyDown);
ConnectThisTo(MetaDatabase::GetInstance(), Events::MetaModified, OnMetaModified);
}
PropertyView::~PropertyView()
{
}
void PropertyView::DisconnectAllObjects()
{
// Disconnect from all old objects
forRange (HandleParam oldObject, mSelectedObjects.All())
{
// Disconnect if the handle is a valid Object
if (Object* object = oldObject.Get<Object*>())
if (EventDispatcher* dispatcher = object->GetDispatcherObject())
dispatcher->Disconnect(this);
}
}
Handle PropertyView::GetObject()
{
return mSelectedObject;
}
void PropertyView::Invalidate()
{
this->MarkAsNeedsUpdate();
// We need to release handles in case of meta changing. See the comment
// above ObjectPropertyNode::ReleaseHandles
if (mRoot)
mRoot->mNode->ReleaseHandles();
// Destroy the tree
SafeDestroy(mRoot);
mSelectedObjects.Clear();
// Clear the additional widgets
forRange (Widget* widget, mAddtionalWidgets.All())
widget->Destroy();
mAddtionalWidgets.Clear();
}
void PropertyView::Rebuild()
{
Handle instance = GetObject();
if (instance.IsNotNull())
{
// SafeDelete(mRootObjectNode);
auto rootObjectNode = mPropertyInterface->BuildObjectTree(nullptr, instance);
if (rootObjectNode == nullptr)
return;
PropertyWidgetInitializer initializer;
initializer.Instance = instance;
initializer.Grid = this;
initializer.Parent = mScrollArea->GetClientWidget();
initializer.Property = nullptr;
initializer.CurrentInterface = mPropertyInterface;
initializer.ObjectNode = rootObjectNode;
// Create and open the root node
PropertyWidgetObject* node = new PropertyWidgetObject(initializer, nullptr);
mRoot = node;
mRoot->OpenNode(false);
mRoot->UpdateTransformExternal();
}
Refresh();
}
void PropertyView::SetObject(HandleParam newObject, PropertyInterface* newInterface)
{
DisconnectAllObjects();
// We no longer care about the old objects
mSelectedObjects.Clear();
// If it's not a valid object, just rebuild the tree with nothing in it
if (newObject.IsNull())
{
// not a valid object clear the grid.
mSelectedObject = Handle();
Invalidate();
return;
}
// Store the handle
mSelectedObject = newObject;
// Set the property interface without rebuilding the tree (we're going
// to rebuild it again in a second)
SetPropertyInterface(newInterface);
// We need to know when a component has changed on one of the objects
// we have selected in order to properly rebuild the tree
mPropertyInterface->GetObjects(newObject, mSelectedObjects);
forRange (Handle object, mSelectedObjects.All())
{
// Connect if handle is a valid Object
if (Object* objectPointer = object.Get<Object*>())
{
if (EventDispatcher* dispatcher = objectPointer->GetDispatcherObject())
{
Connect(objectPointer, Events::ComponentsModified, this, &ZilchSelf::OnInvalidate, ConnectNotify::Ignore);
Connect(objectPointer, Events::ObjectStructureModified, this, &ZilchSelf::OnInvalidate, ConnectNotify::Ignore);
}
}
}
// Refresh and rebuild.
Invalidate();
}
void PropertyView::SetObject(Object* object)
{
PropertyView::SetObject(Handle(object));
}
void PropertyView::UpdateTransform()
{
mScrollArea->SetSize(mSize);
if (mDestroyed)
return;
if (mRoot == nullptr)
Rebuild();
if (mRoot)
{
float rootHeight = mRoot->GetSize().y;
// Subtract the width if the scroll bar is active
float width = mSize.x;
if (rootHeight > mSize.y)
width -= mScrollArea->GetScrollBarSize();
// If there is extra height use if for layouts
float height = Math::Max(mSize.y, rootHeight);
// Resize root widget with adjusted width
mRoot->SetSize(Vec2(width, rootHeight));
// Size client widget in case of layouts
mScrollArea->GetClientWidget()->SetSize(Vec2(width, height));
mScrollArea->SetClientSize(Vec2(width, height));
}
else
{
// Nothing selected reset the
mScrollArea->SetClientSize(Vec2(10, 10));
}
Composite::UpdateTransform();
}
void PropertyView::SizeToContents()
{
UpdateTransform();
ReturnIf(mRoot == nullptr, , "No valid on object selected on property grid. Size will be invalid");
Vec2 sizeNeeded = mRoot->GetSize();
this->SetSize(sizeNeeded);
}
Vec2 PropertyView::GetMinSize()
{
if (mRoot && mFixedHeight)
return Vec2(mMinSize.x, mRoot->GetSize().y);
else
return mMinSize;
}
void PropertyView::ActivateAutoUpdate()
{
ConnectThisTo(this->GetRootWidget(), Events::WidgetUpdate, OnWidgetUpdate);
}
void PropertyView::Refresh()
{
// Is the object still valid?
Handle instance = GetObject();
if (instance.IsNotNull())
{
if (mRoot == nullptr)
{
Rebuild();
}
else
{
mRoot->Refresh();
mRoot->MarkAsNeedsUpdate();
}
}
else
{
// Object is lost, clear the tree
if (mRoot != nullptr)
Invalidate();
}
}
void PropertyView::SetPropertyInterface(PropertyInterface* propInterface, bool rebuild)
{
mPropertyInterface = propInterface;
// Use the default if none was specified
if (mPropertyInterface == nullptr)
mPropertyInterface = &mDefaultPropertyInterface;
mPropertyInterface->mPropertyGrid = this;
if (rebuild)
Invalidate();
}
void PropertyView::AddCustomPropertyIcon(CustomIconCreatorFunction callback, void* clientData)
{
// If it's already in the array, no need to add it
if (mCustomIconCallbacks.Contains(callback))
return;
// Insert the client data
mCallbackClientData[(void*)callback] = clientData;
mCustomIconCallbacks.PushBack(callback);
Invalidate();
Rebuild();
}
void PropertyView::RemoveCustomPropertyIcon(CustomIconCreatorFunction callback)
{
if (!mCustomIconCallbacks.Contains(callback))
return;
mCustomIconCallbacks.EraseValueError(callback);
mCallbackClientData.Erase((void*)callback);
Invalidate();
Rebuild();
}
void PropertyView::OnWidgetUpdate(UpdateEvent* update)
{
// Only refresh if the property grid is active (could be hidden behind a tab)
if (GetGlobalActive())
Refresh();
}
void PropertyView::OnInvalidate(Event* e)
{
Invalidate();
}
void PropertyView::OnKeyDown(KeyboardEvent* e)
{
if (!e->CtrlPressed)
return;
if (e->Key == Keys::Z)
{
mPropertyInterface->Undo();
e->Handled = true;
}
else if (e->Key == Keys::Y)
{
mPropertyInterface->Redo();
e->Handled = true;
}
}
void PropertyView::OnMetaModified(MetaLibraryEvent* e)
{
Invalidate();
}
} // namespace Zero
| 24.335385
| 119
| 0.706916
|
RyanTylerRae
|
60e2788527ed01a599fa809c6a1f49167236d0aa
| 486
|
cpp
|
C++
|
app/comm/timer.cpp
|
ligavin/udt_server
|
c4a21497136bad53b915d3eb3d99f0ad07426e66
|
[
"BSD-3-Clause"
] | null | null | null |
app/comm/timer.cpp
|
ligavin/udt_server
|
c4a21497136bad53b915d3eb3d99f0ad07426e66
|
[
"BSD-3-Clause"
] | null | null | null |
app/comm/timer.cpp
|
ligavin/udt_server
|
c4a21497136bad53b915d3eb3d99f0ad07426e66
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* timer.cpp
*
* Created on: 2015年9月3日
* Author: gavinlli
*/
#include "timer.h"
#include <stdio.h>
timer::timer() {
// TODO Auto-generated constructor stub
start();
}
timer::~timer() {
// TODO Auto-generated destructor stub
}
void timer::start()
{
gettimeofday( &m_start, NULL);
}
int timer::get_time()
{
struct timeval end;
gettimeofday( &end, NULL);
int timeuse = (end.tv_sec - m_start.tv_sec ) * 1000000 + (end.tv_usec - m_start.tv_usec);
return timeuse;
}
| 15.1875
| 90
| 0.654321
|
ligavin
|
60e3e59bd360f21b7706c8e52dd1f38325b0eca2
| 8,220
|
cpp
|
C++
|
src/esp/gfx/PbrDrawable.cpp
|
vauduong/habitat-sim
|
08f5dcae8cb9e94e0985f8134affdb0e8ce1cc2c
|
[
"MIT"
] | 1
|
2021-03-03T22:17:53.000Z
|
2021-03-03T22:17:53.000Z
|
src/esp/gfx/PbrDrawable.cpp
|
vauduong/habitat-sim
|
08f5dcae8cb9e94e0985f8134affdb0e8ce1cc2c
|
[
"MIT"
] | 1
|
2021-12-20T20:36:46.000Z
|
2021-12-20T20:36:46.000Z
|
src/esp/gfx/PbrDrawable.cpp
|
vauduong/habitat-sim
|
08f5dcae8cb9e94e0985f8134affdb0e8ce1cc2c
|
[
"MIT"
] | 3
|
2021-06-16T19:42:39.000Z
|
2021-12-16T16:53:38.000Z
|
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "PbrDrawable.h"
#include <Corrade/Containers/ArrayViewStl.h>
#include <Corrade/Utility/FormatStl.h>
#include <Magnum/GL/Renderer.h>
namespace Mn = Magnum;
namespace esp {
namespace gfx {
PbrDrawable::PbrDrawable(scene::SceneNode& node,
Mn::GL::Mesh& mesh,
gfx::Drawable::Flags& meshAttributeFlags,
ShaderManager& shaderManager,
const Mn::ResourceKey& lightSetupKey,
const Mn::ResourceKey& materialDataKey,
DrawableGroup* group)
: Drawable{node, mesh, group},
shaderManager_{shaderManager},
lightSetup_{shaderManager.get<LightSetup>(lightSetupKey)},
materialData_{
shaderManager.get<MaterialData, PbrMaterialData>(materialDataKey)} {
if (materialData_->metallicTexture && materialData_->roughnessTexture) {
CORRADE_ASSERT(
materialData_->metallicTexture == materialData_->roughnessTexture,
"PbrDrawable::PbrDrawable(): if both the metallic and roughness "
"texture exist, they must be packed in the same texture based on glTF "
"2.0 Spec.", );
}
flags_ = PbrShader::Flag::ObjectId;
if (materialData_->textureMatrix != Mn::Matrix3{}) {
flags_ |= PbrShader::Flag::TextureTransformation;
}
if (materialData_->baseColorTexture) {
flags_ |= PbrShader::Flag::BaseColorTexture;
}
if (materialData_->roughnessTexture) {
flags_ |= PbrShader::Flag::RoughnessTexture;
}
if (materialData_->metallicTexture) {
flags_ |= PbrShader::Flag::MetallicTexture;
}
if (materialData_->normalTexture) {
flags_ |= PbrShader::Flag::NormalTexture;
if (meshAttributeFlags & gfx::Drawable::Flag::HasTangent) {
flags_ |= PbrShader::Flag::PrecomputedTangent;
}
if (materialData_->normalTextureScale != 1.0f) {
flags_ |= PbrShader::Flag::NormalTextureScale;
CORRADE_ASSERT(materialData_->normalTextureScale > 0.0f,
"PbrDrawable::PbrDrawable(): the normal texture scale "
"must be positive.", );
}
}
if (materialData_->emissiveTexture) {
flags_ |= PbrShader::Flag::EmissiveTexture;
}
if (materialData_->perVertexObjectId) {
// TODO: may be supported in the future
}
if (materialData_->doubleSided) {
flags_ |= PbrShader::Flag::DoubleSided;
}
// Defer the shader initialization because at this point, the lightSetup may
// not be done in the Simulator. Simulator itself is currently under
// construction in this case.
// updateShader().updateShaderLightParameters();
}
void PbrDrawable::setLightSetup(const Mn::ResourceKey& lightSetupKey) {
lightSetup_ = shaderManager_.get<LightSetup>(lightSetupKey);
}
void PbrDrawable::draw(const Mn::Matrix4& transformationMatrix,
Mn::SceneGraph::Camera3D& camera) {
updateShader()
.updateShaderLightParameters()
.updateShaderLightDirectionParameters(transformationMatrix, camera);
// Assume that in a model, double-sided meshes are significantly less than
// single-sided meshes.
// To reduce the usage of glIsEnabled, once a double-sided mesh is
// encountered, the FaceCulling is disabled, and will not be enabled again at
// least in this function.
// TODO:
// it should have a global GL state tracker in Magnum to track it.
if ((flags_ & PbrShader::Flag::DoubleSided) && glIsEnabled(GL_CULL_FACE)) {
Mn::GL::Renderer::disable(Mn::GL::Renderer::Feature::FaceCulling);
}
(*shader_)
// e.g., semantic mesh has its own per vertex annotation, which has been
// uploaded to GPU so simply pass 0 to the uniform "objectId" in the
// fragment shader
.setObjectId(
static_cast<RenderCamera&>(camera).useDrawableIds()
? drawableId_
: (materialData_->perVertexObjectId ? 0 : node_.getSemanticId()))
.setTransformationMatrix(transformationMatrix) // modelview matrix
.setProjectionMatrix(camera.projectionMatrix())
.setNormalMatrix(transformationMatrix.normalMatrix())
.setBaseColor(materialData_->baseColor)
.setRoughness(materialData_->roughness)
.setMetallic(materialData_->metallic)
.setEmissiveColor(materialData_->emissiveColor);
if ((flags_ & PbrShader::Flag::BaseColorTexture) &&
materialData_->baseColorTexture) {
shader_->bindBaseColorTexture(*materialData_->baseColorTexture);
}
if (flags_ &
(PbrShader::Flag::RoughnessTexture | PbrShader::Flag::MetallicTexture)) {
Magnum::GL::Texture2D* metallicRoughnessTexture =
materialData_->roughnessTexture;
if (!metallicRoughnessTexture) {
metallicRoughnessTexture = materialData_->metallicTexture;
}
CORRADE_ASSERT(metallicRoughnessTexture,
"PbrDrawable::draw(): texture pointer cannot be nullptr if "
"RoughnessTexture or MetallicTexture is enabled.", );
shader_->bindMetallicRoughnessTexture(*metallicRoughnessTexture);
}
if ((flags_ & PbrShader::Flag::NormalTexture) &&
materialData_->normalTexture) {
shader_->bindNormalTexture(*materialData_->normalTexture);
}
if ((flags_ & PbrShader::Flag::EmissiveTexture) &&
materialData_->emissiveTexture) {
shader_->bindEmissiveTexture(*materialData_->emissiveTexture);
}
if ((flags_ & PbrShader::Flag::TextureTransformation) &&
(materialData_->textureMatrix != Mn::Matrix3{})) {
shader_->setTextureMatrix(materialData_->textureMatrix);
}
shader_->draw(mesh_);
}
Mn::ResourceKey PbrDrawable::getShaderKey(Mn::UnsignedInt lightCount,
PbrShader::Flags flags) const {
return Corrade::Utility::formatString(
SHADER_KEY_TEMPLATE, lightCount,
static_cast<PbrShader::Flags::UnderlyingType>(flags));
}
PbrDrawable& PbrDrawable::updateShader() {
unsigned int lightCount = lightSetup_->size();
if (!shader_ || shader_->lightCount() != lightCount ||
shader_->flags() != flags_) {
// if the number of lights or flags have changed, we need to fetch a
// compatible shader
shader_ = shaderManager_.get<Mn::GL::AbstractShaderProgram, PbrShader>(
getShaderKey(lightCount, flags_));
// if no shader with desired number of lights and flags exists, create one
if (!shader_) {
shaderManager_.set<Mn::GL::AbstractShaderProgram>(
shader_.key(), new PbrShader{flags_, lightCount},
Mn::ResourceDataState::Final, Mn::ResourcePolicy::ReferenceCounted);
}
CORRADE_INTERNAL_ASSERT(shader_ && shader_->lightCount() == lightCount &&
shader_->flags() == flags_);
}
return *this;
}
// update every light's color, intensity, range etc.
PbrDrawable& PbrDrawable::updateShaderLightParameters() {
// light range has been initialized to Mn::Constants::inf()
// in the PbrShader's constructor.
// No need to reset it at this point.
std::vector<Mn::Color3> colors;
colors.reserve(lightSetup_->size());
for (unsigned int iLight = 0; iLight < lightSetup_->size(); ++iLight) {
// Note: the light color MUST take the intensity into account
colors.emplace_back((*lightSetup_)[iLight].color);
}
shader_->setLightColors(colors);
return *this;
}
// update light direction (or position) in *camera* space to the shader
PbrDrawable& PbrDrawable::updateShaderLightDirectionParameters(
const Magnum::Matrix4& transformationMatrix,
Magnum::SceneGraph::Camera3D& camera) {
std::vector<Mn::Vector4> lightPositions;
lightPositions.reserve(lightSetup_->size());
const Mn::Matrix4 cameraMatrix = camera.cameraMatrix();
for (unsigned int iLight = 0; iLight < lightSetup_->size(); ++iLight) {
const auto& lightInfo = (*lightSetup_)[iLight];
lightPositions.emplace_back(Mn::Vector4(getLightPositionRelativeToCamera(
lightInfo, transformationMatrix, cameraMatrix)));
}
shader_->setLightVectors(lightPositions);
return *this;
}
} // namespace gfx
} // namespace esp
| 37.706422
| 79
| 0.688078
|
vauduong
|
60e4f5770fc568b86fcf87e11b9894989b363963
| 5,326
|
cpp
|
C++
|
test/integration/acceptance/create_account_test.cpp
|
coderintherye/iroha
|
68509282851130c9818f21acef1ef28e53622315
|
[
"Apache-2.0"
] | null | null | null |
test/integration/acceptance/create_account_test.cpp
|
coderintherye/iroha
|
68509282851130c9818f21acef1ef28e53622315
|
[
"Apache-2.0"
] | null | null | null |
test/integration/acceptance/create_account_test.cpp
|
coderintherye/iroha
|
68509282851130c9818f21acef1ef28e53622315
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include <gtest/gtest.h>
#include "framework/integration_framework/integration_test_framework.hpp"
#include "integration/acceptance/acceptance_fixture.hpp"
using namespace integration_framework;
using namespace shared_model;
using namespace common_constants;
class CreateAccount : public AcceptanceFixture {
public:
auto makeUserWithPerms(const interface::RolePermissionSet &perms = {
interface::permissions::Role::kCreateAccount}) {
return AcceptanceFixture::makeUserWithPerms(perms);
}
const std::string kNewUser = "userone";
const crypto::Keypair kNewUserKeypair =
crypto::DefaultCryptoAlgorithmType::generateKeypair();
};
/**
* @given some user with can_create_account permission
* @when execute tx with CreateAccount command
* @then there is the tx in proposal
*/
TEST_F(CreateAccount, Basic) {
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms())
.skipProposal()
.skipBlock()
.sendTxAwait(
complete(baseTx().createAccount(
kNewUser, kDomain, kNewUserKeypair.publicKey())),
[](auto &block) { ASSERT_EQ(block->transactions().size(), 1); });
}
/**
* @given some user without can_create_account permission
* @when execute tx with CreateAccount command
* @then verified proposal is empty
*/
TEST_F(CreateAccount, NoPermissions) {
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms({interface::permissions::Role::kGetMyTxs}))
.skipProposal()
.skipVerifiedProposal()
.skipBlock()
.sendTx(complete(baseTx().createAccount(
kNewUser, kDomain, kNewUserKeypair.publicKey())))
.skipProposal()
.checkVerifiedProposal(
[](auto &proposal) { ASSERT_EQ(proposal->transactions().size(), 0); })
.checkBlock(
[](auto block) { ASSERT_EQ(block->transactions().size(), 0); });
}
/**
* @given some user with can_create_account permission
* @when execute tx with CreateAccount command with nonexistent domain
* @then verified proposal is empty
*/
TEST_F(CreateAccount, NoDomain) {
const std::string nonexistent_domain = "asdf";
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms())
.skipProposal()
.skipVerifiedProposal()
.skipBlock()
.sendTx(complete(baseTx().createAccount(
kNewUser, nonexistent_domain, kNewUserKeypair.publicKey())))
.skipProposal()
.checkVerifiedProposal(
[](auto &proposal) { ASSERT_EQ(proposal->transactions().size(), 0); })
.checkBlock(
[](auto block) { ASSERT_EQ(block->transactions().size(), 0); });
}
/**
* @given some user with can_create_account permission
* @when execute tx with CreateAccount command with already existing username
* @then verified proposal is empty
*/
TEST_F(CreateAccount, ExistingName) {
std::string existing_name = kUser;
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms())
.skipProposal()
.skipVerifiedProposal()
.skipBlock()
.sendTx(complete(baseTx().createAccount(
existing_name, kDomain, kNewUserKeypair.publicKey())))
.skipProposal()
.checkVerifiedProposal(
[](auto &proposal) { ASSERT_EQ(proposal->transactions().size(), 0); })
.checkBlock(
[](const auto block) { ASSERT_EQ(block->transactions().size(), 0); });
}
/**
* @given some user with can_create_account permission
* @when execute tx with CreateAccount command with maximum available length
* @then there is the tx in proposal
*/
TEST_F(CreateAccount, MaxLenName) {
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms())
.skipProposal()
.skipBlock()
.sendTxAwait(
complete(baseTx().createAccount(
std::string(32, 'a'), kDomain, kNewUserKeypair.publicKey())),
[](auto &block) { ASSERT_EQ(block->transactions().size(), 1); });
}
/**
* @given some user with can_create_account permission
* @when execute tx with CreateAccount command with too long length
* @then the tx hasn't passed stateless validation
* (aka skipProposal throws)
*/
TEST_F(CreateAccount, TooLongName) {
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms())
.skipProposal()
.skipBlock()
.sendTx(complete(baseTx().createAccount(
std::string(33, 'a'), kDomain, kNewUserKeypair.publicKey())),
CHECK_STATELESS_INVALID);
}
/**
* @given some user with can_create_account permission
* @when execute tx with CreateAccount command with empty user name
* @then the tx hasn't passed stateless validation
* (aka skipProposal throws)
*/
TEST_F(CreateAccount, EmptyName) {
std::string empty_name = "";
IntegrationTestFramework(1)
.setInitialState(kAdminKeypair)
.sendTx(makeUserWithPerms())
.skipProposal()
.skipBlock()
.sendTx(complete(baseTx().createAccount(
empty_name, kDomain, kNewUserKeypair.publicKey())),
CHECK_STATELESS_INVALID);
}
| 33.496855
| 80
| 0.68344
|
coderintherye
|
60ea2a29a841e1e17d40941f86a0c9b44396435d
| 273
|
cpp
|
C++
|
wrapper/Lua/methods/Helper.cpp
|
arrayfire/arrayfire-lua
|
5cd1e7702cd37d3bae60cfbc819c01cda1d0f6ec
|
[
"BSD-3-Clause"
] | 10
|
2015-09-21T07:20:20.000Z
|
2019-07-29T10:36:50.000Z
|
wrapper/Lua/methods/Helper.cpp
|
arrayfire/arrayfire-lua
|
5cd1e7702cd37d3bae60cfbc819c01cda1d0f6ec
|
[
"BSD-3-Clause"
] | 3
|
2015-09-20T06:15:41.000Z
|
2017-02-27T01:38:04.000Z
|
wrapper/Lua/methods/Helper.cpp
|
arrayfire/arrayfire_lua
|
5cd1e7702cd37d3bae60cfbc819c01cda1d0f6ec
|
[
"BSD-3-Clause"
] | 5
|
2015-09-21T10:12:43.000Z
|
2021-03-05T02:07:50.000Z
|
#include "../methods.h"
#include "../template/out_in.h"
//
static const struct luaL_Reg helper_methods[] = {
OUTIN_ARG(cast, af_dtype),
OUTIN(isinf),
OUTIN(iszero),
{ NULL, NULL }
};
int Helper (lua_State * L)
{
luaL_register(L, NULL, helper_methods);
return 0;
}
| 15.166667
| 49
| 0.673993
|
arrayfire
|
60eadec343c01187f38466d14ec8d8a7cd56cdfc
| 18,616
|
cpp
|
C++
|
app/src/main/jni/src/main.cpp
|
zimspy007/Funda-Ndebele-ECD-App
|
d2df5ff54e1cc482870ff7b0b08e89898ed25645
|
[
"BSD-3-Clause"
] | 1
|
2019-10-12T12:07:01.000Z
|
2019-10-12T12:07:01.000Z
|
app/src/main/jni/src/main.cpp
|
zimspy007/Funda-Ndebele-ECD-App
|
d2df5ff54e1cc482870ff7b0b08e89898ed25645
|
[
"BSD-3-Clause"
] | null | null | null |
app/src/main/jni/src/main.cpp
|
zimspy007/Funda-Ndebele-ECD-App
|
d2df5ff54e1cc482870ff7b0b08e89898ed25645
|
[
"BSD-3-Clause"
] | 1
|
2019-12-04T17:45:29.000Z
|
2019-12-04T17:45:29.000Z
|
#include "game_code/puzzle_data.hpp"
#include "game_code/game.hpp"
#include "game_code/grid.hpp"
#include "game_code/card.hpp"
#include "game_code/puzzle.hpp"
#include "game_code/alien.hpp"
#include "game_code/walking_alien.hpp"
#include "game_code/black_bird.hpp"
#include "game_code/butterfly.hpp"
#include "game_code/pink_tree.hpp"
#include "game_code/firework.hpp"
#include "game_code/button.hpp"
#ifdef __ANDROID__
#endif //__ANDROID__
/*amount of fireworks to use for fireworks effect*/
#define AMOUNT 18
/*destroys sdl textures and frees up memory*/
void destroyTextures();
/*loads all media into memory, returns true if successful*/
bool loadmedia();
void processInput(SDL_Point _point);
bool showFireworks = false;
/*pointer to the game object*/
Game *game;
/*the camera object. used to project screen to a specific rect but only useful for scrolling screens*/
Camera cam;
Grid grid;
GTexture bgTex;
GTexture forestbg;
GTexture scrnTex;
GTexture schoolTex;
GTexture creditsTex;
Card clickCard;
Alien alien;
WalkingAlien walkingalien;
Butterfly bfly;
BlackBird blackbird;
PinkTree pinktree;
PinkTree greentree;
int MAX_LEVEL = 45;
int puzzles_index = 0;
Puzzle currPuzzle, oldPuzzle;
int puzzleCounter = 0;
bool updatePuzzle = false;
Button btnquit;
Button btninfo;
Button btnPlay;
Mix_Chunk *eff_help;
Mix_Chunk *eff_hello;
Mix_Chunk *eff_tools;
Mix_Chunk *eff_correct;
Mix_Chunk *eff_retry;
mFirework fire[AMOUNT];
const int GAME_STATE_MENU = 10;
const int GAME_STATE_CREDITS = 20;
const int GAME_STATE_LOADING = 30;
const int GAME_STATE_EXITING = 40;
const int GAME_STATE_3PUZZLE = 50;
int GAME_STATE = GAME_STATE_MENU;
int main(int argc, char *argv[]) {
game = new Game();
grid = Grid(game->getScrnW(), game->getScrnH());
cam = Camera(game->getScrnW(), game->getScrnH());
std::random_shuffle(puzzles, puzzles + sizeof(puzzles) / sizeof(puzzles[0]));
//load game stuff here
if (!loadmedia())
exit(2);
//Center the camera over the screen
cam.camRect.x = 0;
cam.camRect.y = 0;
game->runGame();
destroyTextures();
game->shutdown();
exit(0);
}
void destroyTextures() {
bgTex.destroyTex();
forestbg.destroyTex();
scrnTex.destroyTex();
schoolTex.destroyTex();
creditsTex.destroyTex();
clickCard.getTex()->destroyTex();
currPuzzle.dispose();
alien.dispose();
walkingalien.dispose();
bfly.dispose();
blackbird.dispose();
pinktree.dispose();
greentree.dispose();
for (int i = 0; i < AMOUNT; i++) {
fire[i].destroyFirework();
}
btnPlay.disposeTex();
btnquit.disposeTex();
btninfo.disposeTex();
Mix_FreeChunk(eff_hello);
Mix_FreeChunk(eff_help);
Mix_FreeChunk(eff_tools);
Mix_FreeChunk(eff_correct);
Mix_FreeChunk(eff_retry);
}
/*implementation of global function declared in game.cpp*/
void updateGame(float deltaTime) {
switch (GAME_STATE) {
case GAME_STATE_MENU:
bfly.update(deltaTime, game->getScrnW(), game->getScrnH());
blackbird.update(deltaTime, game->getScrnW(), game->getScrnH());
pinktree.update(150);
greentree.update(265);
break;
case GAME_STATE_CREDITS:
alien.update();
break;
case GAME_STATE_LOADING:
if (walkingalien.getTex()->getTexRect()->x < game->getScrnW()) {
walkingalien.setPos(walkingalien.getTex()->getTexRect()->x + 2,
walkingalien.getTex()->getTexRect()->y);
} else {
GAME_STATE = GAME_STATE_3PUZZLE;
Mix_PlayChannel(-1, eff_help, 0);
}
walkingalien.update();
break;
case GAME_STATE_EXITING:
if (walkingalien.getTex()->getTexRect()->x > 0) {
walkingalien.setPos(walkingalien.getTex()->getTexRect()->x - 2,
walkingalien.getTex()->getTexRect()->y);
} else {
GAME_STATE = GAME_STATE_MENU;
}
walkingalien.update();
break;
case GAME_STATE_3PUZZLE:
if (showFireworks) {
for (int i = 0; i < AMOUNT; i++) {
fire[i].updateFirework();
}
}
alien.update();
if (updatePuzzle) {
puzzleCounter++;
if (puzzleCounter == 275) {
updatePuzzle = false;
puzzleCounter = 0;
showFireworks = false;
clickCard.setPos(grid.getUpperpos2().x, grid.getUpperpos2().y);
puzzles_index++;
if (puzzles_index < MAX_LEVEL + 1) {
oldPuzzle = currPuzzle;
Puzzle puzzle = Puzzle(game->getRenderer(), &grid, puzzles[puzzles_index]);
currPuzzle = puzzle;
oldPuzzle.dispose();
eff_help = Mix_LoadWAV(puzzle.getPuzzleSound().c_str());
} else {
puzzles_index = 0;
oldPuzzle = currPuzzle;
Puzzle puzzle = Puzzle(game->getRenderer(), &grid, puzzles[puzzles_index]);
currPuzzle = puzzle;
oldPuzzle.dispose();
eff_help = Mix_LoadWAV(puzzle.getPuzzleSound().c_str());
}
/*Use puzzleType to play a sound and introduce the puzzle*/
Mix_PlayChannel(-1, eff_help, 0);
}
}
break;
default:
break;
}
}
/*implementation of global function declared in game.cpp*/
void drawGame() {
switch (GAME_STATE) {
case GAME_STATE_MENU:
forestbg.draw(game->getRenderer(), forestbg.getTexRect(), &cam.camRect, 0.0f);
pinktree.draw(game->getRenderer(), &cam.camRect);
greentree.draw(game->getRenderer(), &cam.camRect);
btnPlay.draw(game->getRenderer(), &cam.camRect);
bfly.draw(game->getRenderer(), &cam.camRect);
blackbird.draw(game->getRenderer(), &cam.camRect);
btninfo.draw(game->getRenderer(), &cam.camRect);
btnquit.draw(game->getRenderer(), &cam.camRect);
break;
case GAME_STATE_CREDITS:
creditsTex.draw(game->getRenderer(), creditsTex.getTexRect(), &cam.camRect, 0.0f);
alien.draw(game->getRenderer(), &cam.camRect);
break;
case GAME_STATE_LOADING:
schoolTex.draw(game->getRenderer(), schoolTex.getTexRect(), &cam.camRect, 0.0f);
walkingalien.draw(game->getRenderer(), &cam.camRect);
break;
case GAME_STATE_EXITING:
schoolTex.draw(game->getRenderer(), schoolTex.getTexRect(), &cam.camRect, 0.0f);
walkingalien.draw(game->getRenderer(), &cam.camRect, -1);
break;
case GAME_STATE_3PUZZLE:
bgTex.draw(game->getRenderer(), bgTex.getTexRect(), &cam.camRect, 0.0f);
scrnTex.draw(game->getRenderer(), scrnTex.getTexRect(), &cam.camRect, 0.0f);
alien.draw(game->getRenderer(), &cam.camRect);
currPuzzle.draw(game->getRenderer(), &cam.camRect);
clickCard.draw(game->getRenderer(), &cam.camRect);
if (showFireworks) {
//
for (int i = 0; i < AMOUNT; i++) {
fire[i].sketchFirework(game->getRenderer(), &cam.camRect);
}
}
break;
default:
break;
}
}
bool loadmedia() {
bool success = false;
schoolTex = GTexture(game->getRenderer(), "media/images/school.png", 0.0f);
schoolTex.setupRect(0, 0, game->getScrnW(), game->getScrnH());
bgTex = GTexture(game->getRenderer(), "media/images/winter_bg.png", 0.0f);
bgTex.setupRect(0, 0, game->getScrnW(), game->getScrnH());
forestbg = GTexture(game->getRenderer(), "media/images/forest.jpg", 0.0f);
forestbg.setupRect(0, 0, game->getScrnW(), game->getScrnH());
creditsTex = GTexture(game->getRenderer(), "media/images/credits.png", 0.0f);
creditsTex.setupRect(0, 0, game->getScrnW(), game->getScrnH());
scrnTex = GTexture(game->getRenderer(), "media/images/screen.png", 0.0f);
float scrW = float(game->getScrnW() * 0.975f);
float scrH = float(game->getScrnH() * 0.975f);
int scrX = (game->getScrnW() / 2) - (scrW / 2);
int scrY = (game->getScrnH() / 2) - (scrH / 2);
scrnTex.setupRect(scrX, scrY, scrW, scrH);
clickCard = Card(game->getRenderer(), &grid, "media/images/clickcard.png");
clickCard.setPos(grid.getUpperpos2().x, grid.getUpperpos2().y);
//calculate image rect dimensions
/*int cardW = 400, cardH = 400;
float cardDimens = grid.getCardwidth();*/
float imgScale = float(grid.getCardwidth() / clickCard.getTex()->getTextureW());
alien = Alien(game->getRenderer(), "media/images/alien/alien_idle.png", imgScale * 213,
imgScale * 400);
alien.setPos(0, game->getScrnH() - (imgScale * 400));
walkingalien = WalkingAlien(game->getRenderer(), "media/images/alien/alien_walk.png",
imgScale * 176, imgScale * 430);
walkingalien.setPos(0, game->getScrnH() - (imgScale * 430));
bfly = Butterfly(game->getRenderer(), "media/images/butterfly/butterfly.png", imgScale * 70,
imgScale * 70);
bfly.setPos(0, /*game->getScrnW()*/ 100);
blackbird = BlackBird(game->getRenderer(), "media/images/birds/black_bird.png", imgScale * 180,
imgScale * 120);
blackbird.setPos(0, /*game->getScrnW()*/ 100);
pinktree = PinkTree(game->getRenderer(), "media/images/trees/pink_tree.png",
(imgScale * 271) * 3, (imgScale * 240) * 3);
pinktree.setPos(0, (game->getScrnH() - (imgScale * 240 * 3)));
greentree = PinkTree(game->getRenderer(), "media/images/trees/green_tree.png",
(imgScale * 271) * 2.75f, (imgScale * 240) * 2.75f);
greentree.setPos(game->getScrnW() - (((imgScale * 271) * 3.25f)),
(game->getScrnH() - (imgScale * 240 * 2.75f)));
currPuzzle = Puzzle(game->getRenderer(), &grid, puzzles[puzzles_index]);
btnPlay = Button(game->getRenderer(), "media/ui/play.png", grid.getCardwidth(),
grid.getCardheight());
btnPlay.setPos(grid.getUpperpos2());
btnquit = Button(game->getRenderer(), "media/ui/quit.png", imgScale * 128, imgScale * 128);
SDL_Vector _pos325 = SDL_Vector(game->getScrnW() - (imgScale * 128), 0, 0);
btnquit.setPos(_pos325);
btninfo = Button(game->getRenderer(), "media/ui/info.png", imgScale * 128, imgScale * 128);
SDL_Vector _pos335 = SDL_Vector(btnPlay.getPos().x + (btnPlay.getBtnRect()->w / 2),
btnPlay.getPos().y + (btnPlay.getBtnRect()->h + 28), 0);
btninfo.setPos(_pos335);
if (bgTex.getTex() != NULL) {
success = true;
}
eff_help = Mix_LoadWAV(currPuzzle.getPuzzleSound().c_str());
eff_hello = Mix_LoadWAV("media/sounds/hello.ogg");
eff_tools = Mix_LoadWAV("media/sounds/hello.ogg");
eff_correct = Mix_LoadWAV("media/sounds/bing.ogg");
eff_retry = Mix_LoadWAV("media/sounds/no.ogg");
Mix_PlayChannel(-1, eff_hello, 0);
for (int n = 0; n < AMOUNT; n++) {
fire[n] = mFirework(game->getRenderer(), game->getScrnW(), game->getScrnH(), AMOUNT);
}
SDL_Color txtCol1 = {255, 255, 255, 0};
return success;
}
/*implementation of global function declared in game.cpp*/
void handleTouchUps(float touchX, float touchY) {
}
/*implementation of global function declared in game.cpp*/
void handleTouchDwns(float touchX, float touchY) {
SDL_Point touchLoc = {touchX, touchY,};
switch (GAME_STATE) {
case GAME_STATE_MENU:
if (game->getTouchDwn()) {
if (SDL_PointInRect(&touchLoc, btnPlay.getBtnRect())) {
GAME_STATE = GAME_STATE_LOADING;
}
if (SDL_PointInRect(&touchLoc, btninfo.getBtnRect())) {
GAME_STATE = GAME_STATE_CREDITS;
}
if (SDL_PointInRect(&touchLoc, btnquit.getBtnRect())) {
exit(EXIT_SUCCESS);
}
}
break;
case GAME_STATE_CREDITS:
break;
case GAME_STATE_LOADING:
break;
case GAME_STATE_EXITING:
break;
case GAME_STATE_3PUZZLE:
if (game->getTouchDwn()) {
processInput(touchLoc);
if (SDL_PointInRect(&touchLoc, btnquit.getBtnRect())) {
GAME_STATE = GAME_STATE_EXITING;
}
}
break;
default:
break;
}
}
/*implementation of global function declared in game.cpp*/
void handleMouseInput(SDL_Event *event) {
switch (GAME_STATE) {
case GAME_STATE_MENU:
switch (event->type) {
case SDL_MOUSEBUTTONDOWN:
switch (event->button.button) {
case SDL_BUTTON_LEFT:
int x, y;
SDL_GetMouseState(&x, &y);
SDL_Point clickpoint = {x, y,};
if (SDL_PointInRect(&clickpoint, btnPlay.getBtnRect())) {
GAME_STATE = GAME_STATE_LOADING;
}
if (SDL_PointInRect(&clickpoint, btninfo.getBtnRect())) {
GAME_STATE = GAME_STATE_CREDITS;
}
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event->button.button) {
case SDL_BUTTON_LEFT:
break;
}
break;
}
break;
case GAME_STATE_CREDITS:
switch (event->type) {
case SDL_MOUSEBUTTONDOWN:
switch (event->button.button) {
case SDL_BUTTON_LEFT:
int x, y;
SDL_GetMouseState(&x, &y);
SDL_Point clickpoint = {x, y,};
/*if (SDL_PointInRect(&clickpoint, btnquit.getBtnRect())) {
GAME_STATE = GAME_STATE_MENU;
}*/
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event->button.button) {
case SDL_BUTTON_LEFT:
break;
}
break;
}
break;
case GAME_STATE_LOADING:
break;
case GAME_STATE_EXITING:
break;
case GAME_STATE_3PUZZLE:
switch (event->type) {
case SDL_MOUSEBUTTONDOWN:
switch (event->button.button) {
case SDL_BUTTON_LEFT:
int x, y;
SDL_GetMouseState(&x, &y);
SDL_Point clickpoint = {x, y,};
processInput(clickpoint);
if (SDL_PointInRect(&clickpoint, btnquit.getBtnRect())) {
GAME_STATE = GAME_STATE_EXITING;
}
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event->button.button) {
case SDL_BUTTON_LEFT:
break;
}
break;
}
break;
default:
break;
}
}
/*implementation of global function declared in game.cpp*/
void handleInput(SDL_Event *event) {
if (event->type == SDL_KEYDOWN) {
switch (event->key.keysym.sym) {
case SDLK_AC_BACK:
if (GAME_STATE == GAME_STATE_CREDITS) {
GAME_STATE = GAME_STATE_MENU;
} else if (GAME_STATE == GAME_STATE_3PUZZLE) {
GAME_STATE = GAME_STATE_EXITING;
} else if (GAME_STATE == GAME_STATE_MENU) {
//exit(0);
}
break;
}
}
}
void processInput(SDL_Point _point) {
switch (GAME_STATE) {
case GAME_STATE_MENU:
break;
case GAME_STATE_CREDITS:
break;
case GAME_STATE_LOADING:
break;
case GAME_STATE_3PUZZLE:
if (SDL_PointInRect(&_point, currPuzzle.getLowerCard1().getTex()->getTexRect())) {
clickCard.setPos(currPuzzle.getLowerCard1().getPos());
if (currPuzzle.getSolution() == currPuzzle.getLowerCard1().getName()) {
updatePuzzle = true;
showFireworks = true;
Mix_PlayChannel(-1, eff_correct, 0);
} else { Mix_PlayChannel(-1, eff_retry, 0); }
} else if (SDL_PointInRect(&_point,
currPuzzle.getLowerCard2().getTex()->getTexRect())) {
clickCard.setPos(currPuzzle.getLowerCard2().getPos());
if (currPuzzle.getSolution() == currPuzzle.getLowerCard2().getName()) {
updatePuzzle = true;
showFireworks = true;
Mix_PlayChannel(-1, eff_correct, 0);
} else { Mix_PlayChannel(-1, eff_retry, 0); }
} else if (SDL_PointInRect(&_point,
currPuzzle.getLowerCard3().getTex()->getTexRect())) {
clickCard.setPos(currPuzzle.getLowerCard3().getPos());
if (currPuzzle.getSolution() == currPuzzle.getLowerCard3().getName()) {
updatePuzzle = true;
showFireworks = true;
Mix_PlayChannel(-1, eff_correct, 0);
} else { Mix_PlayChannel(-1, eff_retry, 0); }
}
break;
default:
break;
}
}
| 29.409163
| 102
| 0.538408
|
zimspy007
|
60ebdecbb33d45a182fe10debff0c30be64326d6
| 4,950
|
cpp
|
C++
|
libraries/disp3D/engine/model/materials/networkmaterial.cpp
|
MagCPP/mne-cpp
|
05f634a8401b20226bd719254a5da227e67a379b
|
[
"BSD-3-Clause"
] | 1
|
2019-05-14T07:38:25.000Z
|
2019-05-14T07:38:25.000Z
|
libraries/disp3D/engine/model/materials/networkmaterial.cpp
|
MagCPP/mne-cpp
|
05f634a8401b20226bd719254a5da227e67a379b
|
[
"BSD-3-Clause"
] | 1
|
2018-08-23T12:40:56.000Z
|
2018-08-23T12:40:56.000Z
|
libraries/disp3D/engine/model/materials/networkmaterial.cpp
|
MagCPP/mne-cpp
|
05f634a8401b20226bd719254a5da227e67a379b
|
[
"BSD-3-Clause"
] | null | null | null |
//=============================================================================================================
/**
* @file networkmaterial.cpp
* @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief NetworkMaterial class definition
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "networkmaterial.h"
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <Qt3DRender/qshaderprogram.h>
#include <QFilterKey>
#include <QUrl>
#include <QVector3D>
#include <QVector4D>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISP3DLIB;
using namespace Qt3DRender;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
NetworkMaterial::NetworkMaterial(bool bUseSortPolicy, QNode *parent)
: AbstractPhongAlphaMaterial(bUseSortPolicy, parent)
, m_pVertexGL3Shader(new QShaderProgram())
, m_pVertexES2Shader(new QShaderProgram())
{
init();
setShaderCode();
}
//*************************************************************************************************************
void NetworkMaterial::setShaderCode()
{
m_pVertexGL3Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/gl3/network.vert"))));
m_pVertexGL3Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/gl3/network.frag"))));
m_pVertexES2Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/es2/network.vert"))));
m_pVertexES2Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/es2/network.frag"))));
addShaderToRenderPass(QStringLiteral("pVertexGL3RenderPass"), m_pVertexGL3Shader);
addShaderToRenderPass(QStringLiteral("pVertexGL2RenderPass"), m_pVertexES2Shader);
addShaderToRenderPass(QStringLiteral("pVertexES2RenderPass"), m_pVertexES2Shader);
}
//*************************************************************************************************************
| 50.510204
| 152
| 0.512727
|
MagCPP
|
60ec177ca5e627bef410fbbde50345d25401a309
| 6,304
|
cpp
|
C++
|
android/jni/com/mapswithme/maps/taxi/TaxiManager.cpp
|
ruilin/RLMap
|
e16b52f77d165e719b3af20b097f227959e8e374
|
[
"Apache-2.0"
] | 2
|
2019-01-24T15:36:20.000Z
|
2019-12-26T10:03:48.000Z
|
android/jni/com/mapswithme/maps/taxi/TaxiManager.cpp
|
ruilin/RLMap
|
e16b52f77d165e719b3af20b097f227959e8e374
|
[
"Apache-2.0"
] | 1
|
2018-03-07T15:05:23.000Z
|
2018-03-07T15:05:23.000Z
|
android/jni/com/mapswithme/maps/taxi/TaxiManager.cpp
|
ruilin/RLMap
|
e16b52f77d165e719b3af20b097f227959e8e374
|
[
"Apache-2.0"
] | 1
|
2019-08-09T21:31:29.000Z
|
2019-08-09T21:31:29.000Z
|
#include "com/mapswithme/maps/Framework.hpp"
#include "com/mapswithme/core/jni_helper.hpp"
#include "partners_api/taxi_provider.hpp"
namespace
{
jclass g_productClass;
jclass g_taxiManagerClass;
jclass g_taxiInfoClass;
jclass g_taxiInfoErrorClass;
jmethodID g_taxiInfoConstructor;
jmethodID g_taxiInfoErrorConstructor;
jobject g_taxiManagerInstance;
jmethodID g_productConstructor;
jfieldID g_taxiManagerInstanceField;
jmethodID g_taxiInfoCallbackMethod;
jmethodID g_taxiErrorCallbackMethod;
jclass g_taxiLinksClass;
jmethodID g_taxiLinksConstructor;
uint64_t g_lastRequestId;
void PrepareClassRefs(JNIEnv * env)
{
if (g_taxiManagerClass)
return;
g_taxiManagerClass =
jni::GetGlobalClassRef(env, "com/mapswithme/maps/taxi/TaxiManager");
g_productClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/taxi/TaxiInfo$Product");
g_productConstructor = jni::GetConstructorID(
env, g_productClass,
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
g_taxiInfoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/taxi/TaxiInfo");
g_taxiInfoErrorClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/taxi/TaxiInfoError");
g_taxiManagerInstanceField = jni::GetStaticFieldID(
env, g_taxiManagerClass, "INSTANCE", "Lcom/mapswithme/maps/taxi/TaxiManager;");
g_taxiManagerInstance =
env->GetStaticObjectField(g_taxiManagerClass, g_taxiManagerInstanceField);
g_taxiInfoCallbackMethod =
jni::GetMethodID(env, g_taxiManagerInstance, "onTaxiProvidersReceived",
"([Lcom/mapswithme/maps/taxi/TaxiInfo;)V");
g_taxiErrorCallbackMethod = jni::GetMethodID(env, g_taxiManagerInstance,
"onTaxiErrorsReceived", "([Lcom/mapswithme/maps/taxi/TaxiInfoError;)V");
g_taxiInfoConstructor = jni::GetConstructorID(env, g_taxiInfoClass,
"(I[Lcom/mapswithme/maps/taxi/TaxiInfo$Product;)V");
g_taxiInfoErrorConstructor = jni::GetConstructorID(env, g_taxiInfoErrorClass,
"(ILjava/lang/String;)V");
g_taxiLinksClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/taxi/TaxiLinks");
g_taxiLinksConstructor =
jni::GetConstructorID(env, g_taxiLinksClass, "(Ljava/lang/String;Ljava/lang/String;)V");
}
void OnTaxiInfoReceived(taxi::ProvidersContainer const & providers, uint64_t const requestId)
{
GetPlatform().RunOnGuiThread([=]() {
if (g_lastRequestId != requestId)
return;
JNIEnv * env = jni::GetEnv();
auto const productBuilder = [](JNIEnv * env, taxi::Product const & item)
{
jni::TScopedLocalRef jProductId(env, jni::ToJavaString(env, item.m_productId));
jni::TScopedLocalRef jName(env, jni::ToJavaString(env, item.m_name));
jni::TScopedLocalRef jTime(env, jni::ToJavaString(env, item.m_time));
jni::TScopedLocalRef jPrice(env, jni::ToJavaString(env, item.m_price));
jni::TScopedLocalRef jCurrency(env, jni::ToJavaString(env, item.m_currency));
return env->NewObject(g_productClass, g_productConstructor, jProductId.get(), jName.get(),
jTime.get(), jPrice.get(), jCurrency.get());
};
auto const providerBuilder = [productBuilder](JNIEnv * env, taxi::Provider const & item)
{
return env->NewObject(g_taxiInfoClass, g_taxiInfoConstructor, item.GetType(),
jni::ToJavaArray(env, g_productClass, item.GetProducts(), productBuilder));
};
jni::TScopedLocalObjectArrayRef jProviders(env, jni::ToJavaArray(env, g_taxiInfoClass, providers,
providerBuilder));
jobject const taxiManagerInstance = env->GetStaticObjectField(g_taxiManagerClass,
g_taxiManagerInstanceField);
env->CallVoidMethod(taxiManagerInstance, g_taxiInfoCallbackMethod, jProviders.get());
jni::HandleJavaException(env);
});
}
void OnTaxiError(taxi::ErrorsContainer const & errors, uint64_t const requestId)
{
GetPlatform().RunOnGuiThread([=]() {
if (g_lastRequestId != requestId)
return;
JNIEnv * env = jni::GetEnv();
jobject const taxiManagerInstance = env->GetStaticObjectField(g_taxiManagerClass,
g_taxiManagerInstanceField);
auto const errorBuilder = [](JNIEnv * env, taxi::ProviderError const & error)
{
jni::TScopedLocalRef jErrorCode(env, jni::ToJavaString(env, taxi::DebugPrint(error.m_code)));
return env->NewObject(g_taxiInfoErrorClass, g_taxiInfoErrorConstructor, error.m_type,
jErrorCode.get());
};
jni::TScopedLocalObjectArrayRef jErrors(env, jni::ToJavaArray(env, g_taxiInfoErrorClass, errors, errorBuilder));
env->CallVoidMethod(taxiManagerInstance, g_taxiErrorCallbackMethod, jErrors.get());
jni::HandleJavaException(env);
});
}
} // namespace
extern "C" {
JNIEXPORT void JNICALL Java_com_mapswithme_maps_taxi_TaxiManager_nativeRequestTaxiProducts(
JNIEnv * env, jclass clazz, jobject policy, jdouble srcLat, jdouble srcLon, jdouble dstLat,
jdouble dstLon)
{
PrepareClassRefs(env);
ms::LatLon const from(srcLat, srcLon);
ms::LatLon const to(dstLat, dstLon);
g_lastRequestId =
g_framework->RequestTaxiProducts(env, policy, from, to, &OnTaxiInfoReceived, &OnTaxiError);
}
JNIEXPORT jobject JNICALL Java_com_mapswithme_maps_taxi_TaxiManager_nativeGetTaxiLinks(
JNIEnv * env, jclass clazz, jobject policy, jint providerType, jstring productId, jdouble srcLat,
jdouble srcLon, jdouble dstLat, jdouble dstLon)
{
PrepareClassRefs(env);
ms::LatLon const from(srcLat, srcLon);
ms::LatLon const to(dstLat, dstLon);
taxi::Provider::Type type = static_cast<taxi::Provider::Type>(providerType);
taxi::RideRequestLinks const links =
g_framework->GetTaxiLinks(env, policy, type, jni::ToNativeString(env, productId), from, to);
return env->NewObject(g_taxiLinksClass, g_taxiLinksConstructor,
jni::ToJavaString(env, links.m_deepLink),
jni::ToJavaString(env, links.m_universalLink));
}
} // extern "C"
| 41.748344
| 119
| 0.699873
|
ruilin
|
60ed2726f07b48d025023c8a7013c9efef8bba93
| 921
|
hpp
|
C++
|
15_GameLoopsUserInput/lve_model.hpp
|
vladiant/VulkanTutorial
|
9b1be76c2130e1a771c1b92557541dba55fa0ff7
|
[
"MIT"
] | null | null | null |
15_GameLoopsUserInput/lve_model.hpp
|
vladiant/VulkanTutorial
|
9b1be76c2130e1a771c1b92557541dba55fa0ff7
|
[
"MIT"
] | null | null | null |
15_GameLoopsUserInput/lve_model.hpp
|
vladiant/VulkanTutorial
|
9b1be76c2130e1a771c1b92557541dba55fa0ff7
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include "lve_device.hpp"
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
namespace lve {
class LveDevice;
class LveModel {
public:
struct Vertex {
glm::vec3 position;
glm::vec3 color;
static std::vector<VkVertexInputBindingDescription> getBindingDescription();
static std::vector<VkVertexInputAttributeDescription>
getAttributeDescription();
};
LveModel(LveDevice& lveDevice, const std::vector<Vertex>& vertices);
~LveModel();
LveModel(const LveModel&) = delete;
LveModel& operator=(const LveModel&) = delete;
void bind(VkCommandBuffer commandBuffer);
void draw(VkCommandBuffer commandBuffer);
private:
void createVertexBuffers(const std::vector<Vertex>& vertices);
LveDevice& lveDevice;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
uint32_t vertexCount;
};
} // namespace lve
| 20.466667
| 80
| 0.751357
|
vladiant
|
60eec60018467016f3b41e2931e782248998080f
| 21,511
|
cpp
|
C++
|
lgc/elfLinker/GlueShader.cpp
|
asuonpaa/llpc
|
89eac816465c27bb788186a1cb3bb54d8a7183d4
|
[
"MIT"
] | 1
|
2019-11-25T04:54:55.000Z
|
2019-11-25T04:54:55.000Z
|
lgc/elfLinker/GlueShader.cpp
|
asuonpaa/llpc
|
89eac816465c27bb788186a1cb3bb54d8a7183d4
|
[
"MIT"
] | null | null | null |
lgc/elfLinker/GlueShader.cpp
|
asuonpaa/llpc
|
89eac816465c27bb788186a1cb3bb54d8a7183d4
|
[
"MIT"
] | null | null | null |
/*
***********************************************************************************************************************
*
* Copyright (c) 2020-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* 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.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file GlueShader.cpp
* @brief LGC source file: Glue shader (fetch shader, parameter/color export shader) generated in linking
***********************************************************************************************************************
*/
#include "GlueShader.h"
#include "lgc/BuilderBase.h"
#include "lgc/patch/FragColorExport.h"
#include "lgc/patch/ShaderInputs.h"
#include "lgc/patch/VertexFetch.h"
#include "lgc/state/AbiMetadata.h"
#include "lgc/state/PassManagerCache.h"
#include "lgc/state/ShaderStage.h"
#include "lgc/state/TargetInfo.h"
#include "lgc/util/AddressExtender.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#include "llvm/IR/Module.h"
#include "llvm/Target/TargetMachine.h"
using namespace lgc;
using namespace llvm;
// =====================================================================================================================
// Compile the glue shader
//
// @param [in/out] outStream : Stream to write ELF to
void GlueShader::compile(raw_pwrite_stream &outStream) {
// Generate the glue shader IR module.
std::unique_ptr<Module> module(generate());
// Add empty PAL metadata, to ensure that the back-end writes its PAL metadata in MsgPack format.
PalMetadata *palMetadata = new PalMetadata(nullptr);
palMetadata->record(&*module);
delete palMetadata;
// Get the pass manager and run it on the module, generating ELF.
PassManager &passManager = m_lgcContext->getPassManagerCache()->getGlueShaderPassManager(outStream);
passManager.run(*module);
m_lgcContext->getPassManagerCache()->resetStream();
}
namespace {
// =====================================================================================================================
// A fetch shader
class FetchShader : public GlueShader {
public:
FetchShader(PipelineState *pipelineState, ArrayRef<VertexFetchInfo> fetches, const VsEntryRegInfo &vsEntryRegInfo);
~FetchShader() override {}
// Get the string for this glue shader. This is some encoding or hash of the inputs to the create*Shader function
// that the front-end client can use as a cache key to avoid compiling the same glue shader more than once.
StringRef getString() override;
// Get the symbol name of the main shader that this glue shader is prolog or epilog for.
StringRef getMainShaderName() override;
// Get the symbol name of the glue shader.
StringRef getGlueShaderName() override {
return getEntryPointName(m_vsEntryRegInfo.callingConv, /*isFetchlessVs=*/false);
}
// Get whether this glue shader is a prolog (rather than epilog) for its main shader.
bool isProlog() override { return true; }
// Get the name of this glue shader.
StringRef getName() const override { return "fetch shader"; }
protected:
// Generate the glue shader to IR module
Module *generate() override;
private:
Function *createFetchFunc();
// The information stored here is all that is needed to generate the fetch shader. We deliberately do not
// have access to PipelineState, so we can hash the information here and let the front-end use it as the
// key for a cache of glue shaders.
SmallVector<VertexFetchInfo, 8> m_fetches;
VsEntryRegInfo m_vsEntryRegInfo;
SmallVector<const VertexInputDescription *, 8> m_fetchDescriptions;
// The encoded or hashed (in some way) single string version of the above.
std::string m_shaderString;
};
// =====================================================================================================================
// A color export shader
class ColorExportShader : public GlueShader {
public:
ColorExportShader(PipelineState *pipelineState, ArrayRef<ColorExportInfo> exports);
~ColorExportShader() override {}
// Get the string for this glue shader. This is some encoding or hash of the inputs to the create*Shader function
// that the front-end client can use as a cache key to avoid compiling the same glue shader more than once.
StringRef getString() override;
// Get the symbol name of the main shader that this glue shader is prolog or epilog for.
StringRef getMainShaderName() override;
// Get the symbol name of the glue shader.
StringRef getGlueShaderName() override { return "color_export_shader"; }
// Get whether this glue shader is a prolog (rather than epilog) for its main shader.
bool isProlog() override { return false; }
// Get the name of this glue shader.
StringRef getName() const override { return "color export shader"; }
protected:
// Generate the glue shader to IR module
Module *generate() override;
private:
Function *createColorExportFunc();
// The information stored here is all that is needed to generate the color export shader. We deliberately do not
// have access to PipelineState, so we can hash the information here and let the front-end use it as the
// key for a cache of glue shaders.
SmallVector<ColorExportInfo, 8> m_exports;
ExportFormat m_exportFormat[MaxColorTargets]; // The export format for each hw color target.
// The encoded or hashed (in some way) single string version of the above.
std::string m_shaderString;
PipelineState *m_pipelineState; // The pipeline state. Used to set meta data information.
bool m_killEnabled; // True if this fragement shader has kill enabled.
};
} // anonymous namespace
// =====================================================================================================================
// Create a fetch shader object
GlueShader *GlueShader::createFetchShader(PipelineState *pipelineState, ArrayRef<VertexFetchInfo> fetches,
const VsEntryRegInfo &vsEntryRegInfo) {
return new FetchShader(pipelineState, fetches, vsEntryRegInfo);
}
// =====================================================================================================================
// Create a color export shader object
std::unique_ptr<GlueShader> GlueShader::createColorExportShader(PipelineState *pipelineState,
ArrayRef<ColorExportInfo> exports) {
return std::make_unique<ColorExportShader>(pipelineState, exports);
}
// =====================================================================================================================
// Constructor. This is where we store all the information needed to generate the fetch shader; other methods
// do not need to look at PipelineState.
FetchShader::FetchShader(PipelineState *pipelineState, ArrayRef<VertexFetchInfo> fetches,
const VsEntryRegInfo &vsEntryRegInfo)
: GlueShader(pipelineState->getLgcContext()), m_vsEntryRegInfo(vsEntryRegInfo) {
m_fetches.append(fetches.begin(), fetches.end());
for (const auto &fetch : m_fetches)
m_fetchDescriptions.push_back(pipelineState->findVertexInputDescription(fetch.location));
}
// =====================================================================================================================
// Get the string for this fetch shader. This is some encoding or hash of the inputs to the createFetchShader function
// that the front-end client can use as a cache key to avoid compiling the same glue shader more than once.
StringRef FetchShader::getString() {
if (m_shaderString.empty()) {
m_shaderString =
StringRef(reinterpret_cast<const char *>(m_fetches.data()), m_fetches.size() * sizeof(VertexFetchInfo)).str();
m_shaderString += StringRef(reinterpret_cast<const char *>(&m_vsEntryRegInfo), sizeof(m_vsEntryRegInfo)).str();
for (const VertexInputDescription *description : m_fetchDescriptions) {
if (!description)
m_shaderString += StringRef("\0", 1);
else
m_shaderString += StringRef(reinterpret_cast<const char *>(description), sizeof(*description));
}
}
return m_shaderString;
}
// =====================================================================================================================
// Get the symbol name of the main shader that this glue shader is prolog or epilog for
StringRef FetchShader::getMainShaderName() {
return getEntryPointName(m_vsEntryRegInfo.callingConv, /*isFetchlessVs=*/true);
}
// =====================================================================================================================
// Generate the IR module for the fetch shader
Module *FetchShader::generate() {
// Create the function.
Function *fetchFunc = createFetchFunc();
// Process each vertex input.
std::unique_ptr<VertexFetch> vertexFetch(VertexFetch::create(m_lgcContext));
auto ret = cast<ReturnInst>(fetchFunc->back().getTerminator());
Value *result = ret->getOperand(0);
BuilderBase builder(ret);
for (unsigned idx = 0; idx != m_fetches.size(); ++idx) {
const auto &fetch = m_fetches[idx];
const VertexInputDescription *description = m_fetchDescriptions[idx];
unsigned structIdx = idx + m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vgprCount;
Type *ty = cast<StructType>(result->getType())->getElementType(structIdx);
if (description) {
// Fetch the vertex.
Value *vertex = vertexFetch->fetchVertex(ty, description, fetch.location, fetch.component, builder);
result = builder.CreateInsertValue(result, vertex, structIdx);
}
}
ret->setOperand(0, result);
// Hook up the inputs (vertex buffer, base vertex, base instance, vertex ID, instance ID). The fetchVertex calls
// left its uses of them as lgc.special.user.data and lgc.shader.input calls.
for (Function &func : *fetchFunc->getParent()) {
if (!func.isDeclaration())
continue;
if (func.getName().startswith(lgcName::SpecialUserData) || func.getName().startswith(lgcName::ShaderInput)) {
while (!func.use_empty()) {
auto call = cast<CallInst>(func.use_begin()->getUser());
Value *replacement = nullptr;
switch (cast<ConstantInt>(call->getArgOperand(0))->getZExtValue()) {
case static_cast<unsigned>(UserDataMapping::VertexBufferTable): {
// Need to extend 32-bit vertex buffer table address to 64 bits.
AddressExtender extender(fetchFunc);
Value *highAddr = call->getArgOperand(1);
builder.SetInsertPoint(&*fetchFunc->front().getFirstInsertionPt());
replacement = extender.extend(fetchFunc->getArg(m_vsEntryRegInfo.vertexBufferTable), highAddr,
call->getType(), builder);
break;
}
case static_cast<unsigned>(UserDataMapping::BaseVertex):
replacement = fetchFunc->getArg(m_vsEntryRegInfo.baseVertex);
break;
case static_cast<unsigned>(UserDataMapping::BaseInstance):
replacement = fetchFunc->getArg(m_vsEntryRegInfo.baseInstance);
break;
case static_cast<unsigned>(ShaderInput::VertexId):
builder.SetInsertPoint(&*fetchFunc->front().getFirstInsertionPt());
replacement = builder.CreateBitCast(fetchFunc->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vertexId),
builder.getInt32Ty());
break;
case static_cast<unsigned>(ShaderInput::InstanceId):
builder.SetInsertPoint(&*fetchFunc->front().getFirstInsertionPt());
replacement = builder.CreateBitCast(
fetchFunc->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.instanceId), builder.getInt32Ty());
break;
default:
llvm_unreachable("Unexpected special user data or shader input");
}
call->replaceAllUsesWith(replacement);
call->eraseFromParent();
}
}
}
return fetchFunc->getParent();
}
// =====================================================================================================================
// Create module with function for the fetch shader. On return, the function contains only the code to copy the
// wave dispatch SGPRs and VGPRs to the return value.
Function *FetchShader::createFetchFunc() {
// Create the module
Module *module = new Module("fetchShader", getContext());
TargetMachine *targetMachine = m_lgcContext->getTargetMachine();
module->setTargetTriple(targetMachine->getTargetTriple().getTriple());
module->setDataLayout(targetMachine->createDataLayout());
// Get the function type. Its inputs are the wave dispatch SGPRs and VGPRs. Its return type is a struct
// containing the wave dispatch SGPRs and VGPRs, plus the fetched values in VGPRs. In the return type struct,
// VGPR values must be FP so the back-end puts them into VGPRs; we do the same for the inputs for symmetry.
SmallVector<Type *, 16> types;
types.append(m_vsEntryRegInfo.sgprCount, Type::getInt32Ty(getContext()));
types.append(m_vsEntryRegInfo.vgprCount, Type::getFloatTy(getContext()));
for (const auto &fetch : m_fetches)
types.push_back(getVgprTy(fetch.ty));
Type *retTy = StructType::get(getContext(), types);
auto entryTys = ArrayRef<Type *>(types).slice(0, m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vgprCount);
auto funcTy = FunctionType::get(retTy, entryTys, false);
// Create the function. Mark SGPR inputs as "inreg".
Function *func = Function::Create(funcTy, GlobalValue::ExternalLinkage, getGlueShaderName(), module);
func->setCallingConv(m_vsEntryRegInfo.callingConv);
for (unsigned i = 0; i != m_vsEntryRegInfo.sgprCount; ++i)
func->getArg(i)->addAttr(Attribute::InReg);
// Add mnemonic names to input args.
func->getArg(m_vsEntryRegInfo.vertexBufferTable)->setName("VertexBufferTable");
func->getArg(m_vsEntryRegInfo.baseVertex)->setName("BaseVertex");
func->getArg(m_vsEntryRegInfo.baseInstance)->setName("BaseInstance");
func->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vertexId)->setName("VertexId");
func->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.instanceId)->setName("InstanceId");
if (m_lgcContext->getTargetInfo().getGfxIpVersion().major >= 10) {
// Set up wave32 or wave64 to match the vertex shader.
func->addFnAttr("target-features", m_vsEntryRegInfo.wave32 ? "+wavefrontsize32" : "+wavefrontsize64");
}
BasicBlock *block = BasicBlock::Create(func->getContext(), "", func);
BuilderBase builder(block);
if (m_vsEntryRegInfo.callingConv == CallingConv::AMDGPU_HS ||
m_vsEntryRegInfo.callingConv == CallingConv::AMDGPU_GS) {
// The VS is the first half of a merged shader, LS-HS or ES-GS. This fetch shader needs to include code
// to enable the correct lanes for the vertices. It happens that LS vertex count in LS-HS and ES vertex
// count in ES-GS are in the same place: the low 8 bits of s3.
constexpr unsigned MergedWaveInfoSgpr = 3;
builder.CreateIntrinsic(Intrinsic::amdgcn_init_exec_from_input, {},
{func->getArg(MergedWaveInfoSgpr), builder.getInt32(0)});
}
// Copy the wave dispatch SGPRs and VGPRs from inputs to outputs.
builder.SetInsertPoint(&func->back());
Value *retVal = UndefValue::get(retTy);
for (unsigned i = 0; i != m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vgprCount; ++i)
retVal = builder.CreateInsertValue(retVal, func->getArg(i), i);
builder.CreateRet(retVal);
return func;
}
// =====================================================================================================================
// Constructor. This is where we store all the information needed to generate the export shader; other methods
// do not need to look at PipelineState.
ColorExportShader::ColorExportShader(PipelineState *pipelineState, ArrayRef<ColorExportInfo> exports)
: GlueShader(pipelineState->getLgcContext()) {
m_exports.append(exports.begin(), exports.end());
memset(m_exportFormat, 0, sizeof(m_exportFormat));
for (auto &exp : m_exports) {
if (exp.hwColorTarget == MaxColorTargets)
continue;
m_exportFormat[exp.hwColorTarget] =
static_cast<ExportFormat>(pipelineState->computeExportFormat(exp.ty, exp.location));
}
m_pipelineState = pipelineState;
PalMetadata *metadata = pipelineState->getPalMetadata();
DB_SHADER_CONTROL shaderControl = {};
shaderControl.u32All = metadata->getRegister(mmDB_SHADER_CONTROL);
m_killEnabled = shaderControl.bits.KILL_ENABLE;
}
// =====================================================================================================================
// Get the string for this color export shader. This is some encoding or hash of the inputs to the
// createColorExportShader function that the front-end client can use as a cache key to avoid compiling the same glue
// shader more than once.
StringRef ColorExportShader::getString() {
if (m_shaderString.empty()) {
m_shaderString =
StringRef(reinterpret_cast<const char *>(m_exports.data()), m_exports.size() * sizeof(ColorExportInfo)).str();
m_shaderString += StringRef(reinterpret_cast<const char *>(m_exportFormat), sizeof(m_exportFormat)).str();
m_shaderString += StringRef(reinterpret_cast<const char *>(&m_killEnabled), sizeof(m_killEnabled));
}
return m_shaderString;
}
// =====================================================================================================================
// Get the symbol name of the main shader that this glue shader is prolog or epilog for
StringRef ColorExportShader::getMainShaderName() {
return getEntryPointName(CallingConv::AMDGPU_PS, /*isFetchlessVs=*/false);
}
// =====================================================================================================================
// Generate the IR module for the color export shader
Module *ColorExportShader::generate() {
// Create the function.
Function *colorExportFunc = createColorExportFunc();
// Process each vertex input.
std::unique_ptr<FragColorExport> fragColorExport(new FragColorExport(&getContext(), m_pipelineState));
auto ret = cast<ReturnInst>(colorExportFunc->back().getTerminator());
BuilderBase builder(ret);
SmallVector<Value *, 8> values(MaxColorTargets + 1, nullptr);
for (unsigned idx = 0; idx != m_exports.size(); ++idx) {
values[m_exports[idx].hwColorTarget] = colorExportFunc->getArg(idx);
}
bool dummyExport = m_lgcContext->getTargetInfo().getGfxIpVersion().major < 10 || m_killEnabled;
fragColorExport->generateExportInstructions(m_exports, values, m_exportFormat, dummyExport, builder);
bool hasDepthExpFmtZero = true;
for (auto &info : m_exports) {
if (info.hwColorTarget == MaxColorTargets) {
hasDepthExpFmtZero = false;
break;
}
}
m_pipelineState->getPalMetadata()->updateSpiShaderColFormat(m_exports, hasDepthExpFmtZero, m_killEnabled);
return colorExportFunc->getParent();
}
// =====================================================================================================================
// Create module with function for the fetch shader. On return, the function contains only the code to copy the
// wave dispatch SGPRs and VGPRs to the return value.
Function *ColorExportShader::createColorExportFunc() {
// Create the module
Module *module = new Module("colorExportShader", getContext());
TargetMachine *targetMachine = m_lgcContext->getTargetMachine();
module->setTargetTriple(targetMachine->getTargetTriple().getTriple());
module->setDataLayout(targetMachine->createDataLayout());
// Get the function type. Its inputs are the outputs from the unlinked pixel shader or similar.
SmallVector<Type *, 16> entryTys;
for (const auto &exp : m_exports)
entryTys.push_back(exp.ty);
auto funcTy = FunctionType::get(Type::getVoidTy(getContext()), entryTys, false);
// Create the function. Mark SGPR inputs as "inreg".
Function *func = Function::Create(funcTy, GlobalValue::ExternalLinkage, getGlueShaderName(), module);
func->setCallingConv(CallingConv::AMDGPU_PS);
BasicBlock *block = BasicBlock::Create(func->getContext(), "", func);
BuilderBase builder(block);
builder.CreateRetVoid();
return func;
}
| 49.111872
| 120
| 0.653247
|
asuonpaa
|
60efdfc55aaa66a4e13017dad0f7d11df599b474
| 11,689
|
cc
|
C++
|
zircon/system/ulib/ftl/ftln/ndm-driver.cc
|
liexusong/fuchsia
|
81897680af92a1848a063e3c20ff3a4892ccff07
|
[
"BSD-2-Clause"
] | 3
|
2021-09-02T07:21:06.000Z
|
2022-03-12T03:20:10.000Z
|
zircon/system/ulib/ftl/ftln/ndm-driver.cc
|
liexusong/fuchsia
|
81897680af92a1848a063e3c20ff3a4892ccff07
|
[
"BSD-2-Clause"
] | null | null | null |
zircon/system/ulib/ftl/ftln/ndm-driver.cc
|
liexusong/fuchsia
|
81897680af92a1848a063e3c20ff3a4892ccff07
|
[
"BSD-2-Clause"
] | 2
|
2022-02-25T12:22:49.000Z
|
2022-03-12T03:20:10.000Z
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/ftl/ndm-driver.h>
#include <stdarg.h>
#include <zircon/assert.h>
#include <memory>
#include <optional>
#include "ftl.h"
#include "ftl_private.h"
#include "ndm/ndmp.h"
namespace ftl {
namespace {
bool g_init_performed = false;
// Extra configuration data saved to the partition info.
struct UserData {
uint16_t major_version = 1;
uint16_t minor_version = 0;
uint32_t ftl_flags; // Flags used to create the FtlNdmVol structure.
uint32_t extra_free; // Overallocation for the FTL.
uint32_t reserved_1[5];
VolumeOptions options;
uint32_t reserved_2[10];
};
static_assert(sizeof(UserData) == 96);
// This structure exposes the two views into the partition data.
// See ftl.h for the definition of NDMPartitionInfo.
union PartitionInfo {
NDMPartitionInfo ndm;
struct {
// This is the equivalent structure, with an explicit |data| field of the
// "correct" type, instead of just a placeholder. In this case, |data_size|
// tracks |data|.
NDMPartition basic_data;
uint32_t data_size = sizeof(UserData);
UserData data;
} exploded;
};
static_assert(sizeof(NDMPartition) + sizeof(uint32_t) == sizeof(NDMPartitionInfo));
static_assert(sizeof(NDMPartitionInfo) + sizeof(UserData) == sizeof(PartitionInfo));
// Fills |data| with the desired configuration info.
void CopyConfigData(const VolumeOptions& options, const FtlNdmVol& ftl, UserData* data) {
data->ftl_flags = ftl.flags;
data->extra_free = ftl.extra_free;
data->options = options;
}
// Implementation of the driver interface:
// Returns kNdmOk, kNdmUncorrectableEcc, kNdmFatalError or kNdmUnsafeEcc.
int ReadPagesImpl(uint32_t page, uint32_t count, uint8_t* data, uint8_t* spare, void* dev) {
NdmDriver* device = reinterpret_cast<NdmDriver*>(dev);
return device->NandRead(page, count, data, spare);
}
// Returns kNdmOk, kNdmUncorrectableEcc, kNdmFatalError or kNdmUnsafeEcc.
int ReadPages(uint32_t page, uint32_t count, uint8_t* data, uint8_t* spare, void* dev) {
return ReadPagesImpl(page, count, data, nullptr, dev);
}
// Returns kNdmOk, kNdmUncorrectableEcc, kNdmFatalError or kNdmUnsafeEcc.
int ReadPage(uint32_t page, uint8_t* data, uint8_t* spare, void* dev) {
return ReadPagesImpl(page, 1, data, nullptr, dev);
}
// Returns kNdmOk or kNdmError on ECC decode failure.
int ReadSpare(uint32_t page, uint8_t* spare, void* dev) {
int result = ReadPagesImpl(page, 1, nullptr, spare, dev);
if (result == kNdmFatalError || result == kNdmUncorrectableEcc) {
return kNdmError;
}
// kNdmUnsafeEcc is also OK as the data is still correct.
return kNdmOk;
}
// Returns kNdmOk or kNdmError.
int ReadSpareNoEcc(uint32_t page, uint8_t* spare, void* dev) {
int result = ReadPagesImpl(page, 1, nullptr, spare, dev);
return result == kNdmFatalError ? kNdmError : kNdmOk;
}
// Returns kNdmOk, kNdmError or kNdmFatalError. kNdmError triggers marking the block as bad.
int WritePages(uint32_t page, uint32_t count, const uint8_t* data, uint8_t* spare, int action,
void* dev) {
NdmDriver* device = reinterpret_cast<NdmDriver*>(dev);
return device->NandWrite(page, count, data, spare);
}
// Returns kNdmOk, kNdmError or kNdmFatalError. kNdmError triggers marking the block as bad.
int WritePage(uint32_t page, const uint8_t* data, uint8_t* spare, int action, void* dev) {
return WritePages(page, 1, data, spare, action, dev);
}
// Returns kNdmOk or kNdmError. kNdmError triggers marking the block as bad.
int EraseBlock(uint32_t page, void* dev) {
NdmDriver* device = reinterpret_cast<NdmDriver*>(dev);
return device->NandErase(page);
}
// Returns kTrue, kFalse or kNdmError.
int IsBadBlockImpl(uint32_t page, void* dev) {
NdmDriver* device = reinterpret_cast<NdmDriver*>(dev);
return device->IsBadBlock(page);
}
// Returns kTrue or kFalse (kFalse on error).
int IsEmpty(uint32_t page, uint8_t* data, uint8_t* spare, void* dev) {
int result = ReadPagesImpl(page, 1, data, spare, dev);
// kNdmUncorrectableEcc and kNdmUnsafeEcc are ok.
if (result == kNdmFatalError) {
return kFalse;
}
NdmDriver* device = reinterpret_cast<NdmDriver*>(dev);
return device->IsEmptyPage(page, data, spare) ? kTrue : kFalse;
}
// Returns kNdmOk or kNdmError, but kNdmError implies aborting initialization.
int CheckPage(uint32_t page, uint8_t* data, uint8_t* spare, int* status, void* dev) {
int result = ReadPagesImpl(page, 1, data, spare, dev);
if (result == kNdmUncorrectableEcc || result == kNdmFatalError) {
*status = NDM_PAGE_INVALID;
return kNdmOk;
}
NdmDriver* device = reinterpret_cast<NdmDriver*>(dev);
bool empty = device->IsEmptyPage(page, data, spare) ? kTrue : kFalse;
*status = empty ? NDM_PAGE_ERASED : NDM_PAGE_VALID;
return kNdmOk;
}
__PRINTFLIKE(3, 4) void LogTrace(const char* file, int line, const char* format, ...) {
fprintf(stderr, "[FTL] TRACE: ");
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
__PRINTFLIKE(3, 4) void LogDebug(const char* file, int line, const char* format, ...) {
fprintf(stderr, "[FTL] DEBUG: ");
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
__PRINTFLIKE(3, 4) void LogInfo(const char* file, int line, const char* format, ...) {
fprintf(stderr, "[FTL] INFO: ");
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
__PRINTFLIKE(3, 4) void LogWarning(const char* file, int line, const char* format, ...) {
fprintf(stderr, "[FTL] WARNING: ");
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
__PRINTFLIKE(3, 4) void LogError(const char* file, int line, const char* format, ...) {
fprintf(stderr, "[FTL] ERROR: ");
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
} // namespace
FtlLogger DefaultLogger() {
return FtlLogger{
.trace = &LogTrace,
.debug = &LogDebug,
.info = &LogInfo,
.warn = &LogWarning,
.error = &LogError,
};
}
NdmBaseDriver::~NdmBaseDriver() { RemoveNdmVolume(); }
bool NdmBaseDriver::IsNdmDataPresent(const VolumeOptions& options, bool use_format_v2) {
NDMDrvr driver;
FillNdmDriver(options, use_format_v2, &driver);
SetFsErrCode(NDM_OK);
ndm_ = ndmAddDev(&driver);
return ndm_ || GetFsErrCode() != NDM_NO_META_BLK;
}
bool NdmBaseDriver::BadBbtReservation() const {
if (ndm_) {
return false;
}
FsErrorCode error = static_cast<FsErrorCode>(GetFsErrCode());
switch (error) {
case NDM_TOO_MANY_IBAD:
case NDM_TOO_MANY_RBAD:
case NDM_RBAD_LOCATION:
return true;
default:
return false;
}
}
const char* NdmBaseDriver::CreateNdmVolume(const Volume* ftl_volume, const VolumeOptions& options,
bool save_volume_data) {
if (!ndm_) {
IsNdmDataPresent(options, save_volume_data);
}
if (!ndm_) {
return "ndmAddDev failed";
}
PartitionInfo partition = {};
partition.exploded = {}; // Initialize the "real" structure.
FtlNdmVol ftl = {};
XfsVol xfs = {};
ftl.flags = FSF_EXTRA_FREE;
ftl.cached_map_pages = options.num_blocks * (options.block_size / options.page_size);
ftl.extra_free = 6; // Over-provision 6% of the device.
xfs.ftl_volume = const_cast<Volume*>(ftl_volume);
ftl.logger = logger_;
partition.exploded.basic_data.num_blocks = ndmGetNumVBlocks(ndm_);
strncpy(partition.exploded.basic_data.name, "ftl", sizeof(partition.exploded.basic_data.name));
CopyConfigData(options, ftl, &partition.exploded.data);
if (save_volume_data) {
const NDMPartitionInfo* info = ndmGetPartitionInfo(ndm_);
if (info) {
volume_data_saved_ = true;
}
if (ndmWritePartitionInfo(ndm_, &partition.ndm) != 0) {
return "ndmWritePartitionInfo failed";
}
if (!info && !(options.flags & kReadOnlyInit)) {
// There was no volume information saved, save it now.
if (ndmSavePartitionTable(ndm_) != 0) {
return "ndmSavePartitionTable failed";
}
volume_data_saved_ = true;
}
} else {
// This call also allocates the partition data, but old style.
if (ndmSetNumPartitions(ndm_, 1) != 0) {
return "ndmSetNumPartitions failed";
}
if (ndmWritePartition(ndm_, &partition.ndm.basic_data, 0, "ftl") != 0) {
return "ndmWritePartition failed";
}
}
if (ndmAddVolFTL(ndm_, 0, &ftl, &xfs) == NULL) {
return "ndmAddVolFTL failed";
}
return nullptr;
}
bool NdmBaseDriver::RemoveNdmVolume() {
if (ndm_ && ndmDelDev(ndm_) == 0) {
ndm_ = nullptr;
return true;
}
return false;
}
bool NdmBaseDriver::SaveBadBlockData() { return ndmExtractBBL(ndm_) >= 0 ? true : false; }
bool NdmBaseDriver::RestoreBadBlockData() { return ndmInsertBBL(ndm_) == 0 ? true : false; }
bool NdmBaseDriver::IsEmptyPageImpl(const uint8_t* data, uint32_t data_len, const uint8_t* spare,
uint32_t spare_len) const {
const int64_t* pointer = reinterpret_cast<const int64_t*>(data);
ZX_DEBUG_ASSERT(data_len % sizeof(*pointer) == 0);
for (size_t i = 0; i < data_len / sizeof(*pointer); i++) {
if (pointer[i] != -1) {
return false;
}
}
ZX_DEBUG_ASSERT(spare_len % sizeof(*pointer) == 0);
pointer = reinterpret_cast<const int64_t*>(spare);
for (size_t i = 0; i < spare_len / sizeof(*pointer); i++) {
if (pointer[i] != -1) {
return false;
}
}
return true;
}
const VolumeOptions* NdmBaseDriver::GetSavedOptions() const {
const NDMPartitionInfo* partition = ndmGetPartitionInfo(ndm_);
if (!partition) {
return nullptr;
}
auto info = reinterpret_cast<const PartitionInfo*>(partition);
if (info->exploded.data_size != sizeof(UserData)) {
return nullptr;
}
if (info->exploded.data.major_version != 1) {
return nullptr;
}
return &info->exploded.data.options;
}
bool NdmBaseDriver::WriteVolumeData() {
if (ndmSavePartitionTable(ndm_) != 0) {
return false;
}
volume_data_saved_ = true;
return true;
}
void NdmBaseDriver::FillNdmDriver(const VolumeOptions& options, bool use_format_v2,
NDMDrvr* driver) const {
*driver = {};
driver->num_blocks = options.num_blocks;
driver->max_bad_blocks = options.max_bad_blocks;
driver->block_size = options.block_size;
driver->page_size = options.page_size;
driver->eb_size = options.eb_size;
driver->flags = FSF_MULTI_ACCESS | FSF_FREE_SPARE_ECC | options.flags;
driver->format_version_2 = use_format_v2;
driver->dev = const_cast<NdmBaseDriver*>(this);
driver->type = NDM_SLC;
driver->read_pages = ReadPages;
driver->write_pages = WritePages;
driver->write_data_and_spare = WritePage;
driver->read_decode_data = ReadPage;
driver->read_decode_spare = ReadSpare;
driver->read_spare = ReadSpareNoEcc;
driver->data_and_spare_erased = IsEmpty;
driver->data_and_spare_check = CheckPage;
driver->erase_block = EraseBlock;
driver->is_block_bad = IsBadBlockImpl;
driver->logger = logger_;
}
__EXPORT
bool InitModules() {
if (!g_init_performed) {
// Unfortunately, module initialization is a global affair, and there is
// no cleanup. At least, make sure no re-initialization takes place.
if (NdmInit() != 0 || FtlInit() != 0) {
return false;
}
g_init_performed = true;
}
return true;
}
} // namespace ftl
| 30.361039
| 98
| 0.695611
|
liexusong
|
60f0c82f8c9af612e75f5ef9960dbc8b1ca8c3d3
| 12,684
|
hpp
|
C++
|
boost/atomic/detail/base.hpp
|
juslee/boost-svn
|
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
|
[
"BSL-1.0"
] | null | null | null |
boost/atomic/detail/base.hpp
|
juslee/boost-svn
|
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
|
[
"BSL-1.0"
] | null | null | null |
boost/atomic/detail/base.hpp
|
juslee/boost-svn
|
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
|
[
"BSL-1.0"
] | null | null | null |
#ifndef BOOST_ATOMIC_DETAIL_BASE_HPP
#define BOOST_ATOMIC_DETAIL_BASE_HPP
// Copyright (c) 2009 Helge Bahmann
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Base class definition and fallback implementation.
// To be overridden (through partial specialization) by
// platform implementations.
#include <string.h>
#include <boost/atomic/detail/lockpool.hpp>
#define BOOST_ATOMIC_DECLARE_BASE_OPERATORS \
operator value_type(void) volatile const \
{ \
return load(memory_order_seq_cst); \
} \
\
this_type & \
operator=(value_type v) volatile \
{ \
store(v, memory_order_seq_cst); \
return *const_cast<this_type *>(this); \
} \
\
bool \
compare_exchange_strong( \
value_type & expected, \
value_type desired, \
memory_order order = memory_order_seq_cst) volatile \
{ \
return compare_exchange_strong(expected, desired, order, calculate_failure_order(order)); \
} \
\
bool \
compare_exchange_weak( \
value_type & expected, \
value_type desired, \
memory_order order = memory_order_seq_cst) volatile \
{ \
return compare_exchange_weak(expected, desired, order, calculate_failure_order(order)); \
} \
\
#define BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \
value_type \
operator++(int) volatile \
{ \
return fetch_add(1); \
} \
\
value_type \
operator++(void) volatile \
{ \
return fetch_add(1) + 1; \
} \
\
value_type \
operator--(int) volatile \
{ \
return fetch_sub(1); \
} \
\
value_type \
operator--(void) volatile \
{ \
return fetch_sub(1) - 1; \
} \
\
value_type \
operator+=(difference_type v) volatile \
{ \
return fetch_add(v) + v; \
} \
\
value_type \
operator-=(difference_type v) volatile \
{ \
return fetch_sub(v) - v; \
} \
#define BOOST_ATOMIC_DECLARE_BIT_OPERATORS \
value_type \
operator&=(difference_type v) volatile \
{ \
return fetch_and(v) & v; \
} \
\
value_type \
operator|=(difference_type v) volatile \
{ \
return fetch_or(v) | v; \
} \
\
value_type \
operator^=(difference_type v) volatile \
{ \
return fetch_xor(v) ^ v; \
} \
#define BOOST_ATOMIC_DECLARE_POINTER_OPERATORS \
BOOST_ATOMIC_DECLARE_BASE_OPERATORS \
BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \
#define BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS \
BOOST_ATOMIC_DECLARE_BASE_OPERATORS \
BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \
BOOST_ATOMIC_DECLARE_BIT_OPERATORS \
namespace boost {
namespace atomics {
namespace detail {
static inline memory_order
calculate_failure_order(memory_order order)
{
switch(order) {
case memory_order_acq_rel:
return memory_order_acquire;
case memory_order_release:
return memory_order_relaxed;
default:
return order;
}
}
template<typename T, typename C , unsigned int Size, bool Sign>
class base_atomic {
private:
typedef base_atomic this_type;
typedef T value_type;
typedef lockpool::scoped_lock guard_type;
public:
base_atomic(void) {}
explicit base_atomic(const value_type & v)
{
memcpy(&v_, &v, Size);
}
void
store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<char *>(v_));
memcpy(const_cast<char *>(v_), &v, Size);
}
value_type
load(memory_order /*order*/ = memory_order_seq_cst) volatile const
{
guard_type guard(const_cast<const char *>(v_));
value_type v;
memcpy(&v, const_cast<const char *>(v_), Size);
return v;
}
bool
compare_exchange_strong(
value_type & expected,
value_type desired,
memory_order /*success_order*/,
memory_order /*failure_order*/) volatile
{
guard_type guard(const_cast<char *>(v_));
if (memcmp(const_cast<char *>(v_), &expected, Size) == 0) {
memcpy(const_cast<char *>(v_), &desired, Size);
return true;
} else {
memcpy(&expected, const_cast<char *>(v_), Size);
return false;
}
}
bool
compare_exchange_weak(
value_type & expected,
value_type desired,
memory_order success_order,
memory_order failure_order) volatile
{
return compare_exchange_strong(expected, desired, success_order, failure_order);
}
value_type
exchange(value_type v, memory_order /*order*/=memory_order_seq_cst) volatile
{
guard_type guard(const_cast<char *>(v_));
value_type tmp;
memcpy(&tmp, const_cast<char *>(v_), Size);
memcpy(const_cast<char *>(v_), &v, Size);
return tmp;
}
bool
is_lock_free(void) const volatile
{
return false;
}
BOOST_ATOMIC_DECLARE_BASE_OPERATORS
private:
base_atomic(const base_atomic &) /* = delete */ ;
void operator=(const base_atomic &) /* = delete */ ;
char v_[Size];
};
template<typename T, unsigned int Size, bool Sign>
class base_atomic<T, int, Size, Sign> {
private:
typedef base_atomic this_type;
typedef T value_type;
typedef T difference_type;
typedef lockpool::scoped_lock guard_type;
public:
explicit base_atomic(value_type v) : v_(v) {}
base_atomic(void) {}
void
store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
v_ = v;
}
value_type
load(memory_order /*order*/ = memory_order_seq_cst) const volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type v = const_cast<const volatile value_type &>(v_);
return v;
}
value_type
exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ = v;
return old;
}
bool
compare_exchange_strong(value_type & expected, value_type desired,
memory_order /*success_order*/,
memory_order /*failure_order*/) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
if (v_ == expected) {
v_ = desired;
return true;
} else {
expected = v_;
return false;
}
}
bool
compare_exchange_weak(value_type & expected, value_type desired,
memory_order success_order,
memory_order failure_order) volatile
{
return compare_exchange_strong(expected, desired, success_order, failure_order);
}
value_type
fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ += v;
return old;
}
value_type
fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ -= v;
return old;
}
value_type
fetch_and(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ &= v;
return old;
}
value_type
fetch_or(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ |= v;
return old;
}
value_type
fetch_xor(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ ^= v;
return old;
}
bool
is_lock_free(void) const volatile
{
return false;
}
BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS
private:
base_atomic(const base_atomic &) /* = delete */ ;
void operator=(const base_atomic &) /* = delete */ ;
value_type v_;
};
template<typename T, unsigned int Size, bool Sign>
class base_atomic<T *, void *, Size, Sign> {
private:
typedef base_atomic this_type;
typedef T * value_type;
typedef ptrdiff_t difference_type;
typedef lockpool::scoped_lock guard_type;
public:
explicit base_atomic(value_type v) : v_(v) {}
base_atomic(void) {}
void
store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
v_ = v;
}
value_type
load(memory_order /*order*/ = memory_order_seq_cst) const volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type v = const_cast<const volatile value_type &>(v_);
return v;
}
value_type
exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ = v;
return old;
}
bool
compare_exchange_strong(value_type & expected, value_type desired,
memory_order /*success_order*/,
memory_order /*failure_order*/) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
if (v_ == expected) {
v_ = desired;
return true;
} else {
expected = v_;
return false;
}
}
bool
compare_exchange_weak(value_type & expected, value_type desired,
memory_order success_order,
memory_order failure_order) volatile
{
return compare_exchange_strong(expected, desired, success_order, failure_order);
}
value_type fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ += v;
return old;
}
value_type fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ -= v;
return old;
}
bool
is_lock_free(void) const volatile
{
return false;
}
BOOST_ATOMIC_DECLARE_POINTER_OPERATORS
private:
base_atomic(const base_atomic &) /* = delete */ ;
void operator=(const base_atomic &) /* = delete */ ;
value_type v_;
};
template<unsigned int Size, bool Sign>
class base_atomic<void *, void *, Size, Sign> {
private:
typedef base_atomic this_type;
typedef void * value_type;
typedef lockpool::scoped_lock guard_type;
public:
explicit base_atomic(value_type v) : v_(v) {}
base_atomic(void) {}
void
store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
v_ = v;
}
value_type
load(memory_order /*order*/ = memory_order_seq_cst) const volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type v = const_cast<const volatile value_type &>(v_);
return v;
}
value_type
exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
value_type old = v_;
v_ = v;
return old;
}
bool
compare_exchange_strong(value_type & expected, value_type desired,
memory_order /*success_order*/,
memory_order /*failure_order*/) volatile
{
guard_type guard(const_cast<value_type *>(&v_));
if (v_ == expected) {
v_ = desired;
return true;
} else {
expected = v_;
return false;
}
}
bool
compare_exchange_weak(value_type & expected, value_type desired,
memory_order success_order,
memory_order failure_order) volatile
{
return compare_exchange_strong(expected, desired, success_order, failure_order);
}
bool
is_lock_free(void) const volatile
{
return false;
}
BOOST_ATOMIC_DECLARE_BASE_OPERATORS
private:
base_atomic(const base_atomic &) /* = delete */ ;
void operator=(const base_atomic &) /* = delete */ ;
value_type v_;
};
}
}
}
#endif
| 24.725146
| 99
| 0.622044
|
juslee
|
60f468280dabfd003c3f29bd05c07f724b45b4ac
| 911
|
hpp
|
C++
|
Main course/Homework4/Problem2/Header files/KeyValueDatabase.hpp
|
nia-flo/FMI-OOP
|
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
|
[
"MIT"
] | null | null | null |
Main course/Homework4/Problem2/Header files/KeyValueDatabase.hpp
|
nia-flo/FMI-OOP
|
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
|
[
"MIT"
] | null | null | null |
Main course/Homework4/Problem2/Header files/KeyValueDatabase.hpp
|
nia-flo/FMI-OOP
|
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Object.hpp"
#include <vector>
class KeyValueDatabase : public Object
{
public:
KeyValueDatabase(const std::string& name, const std::string& location, const std::string& extension);
void add_entry(const std::pair<std::string, int>& entry);
int get_value(const std::string& key) const;
bool operator==(const Comparable* toCompare) const override;
bool operator!=(const Comparable* toCompare) const override;
bool operator==(const KeyValueDatabase& toCompare) const;
bool operator!=(const KeyValueDatabase& toCompare) const;
std::string to_string() const override;
void from_string(const std::string& stringData) override;
std::string debug_print() const override;
Object* clone() const override;
private:
std::vector< std::pair<std::string, int> > data;
const std::pair<std::string, int>* find(const std::string& key) const;
};
| 28.46875
| 105
| 0.712404
|
nia-flo
|
60f544e61753fe9be01c6bfe6caff72dc3cfbed1
| 320
|
cpp
|
C++
|
C++/zigZagPattern.cpp
|
Chanchal2125/Hacktoberfest2021_PatternMaking
|
c962f1e93f45a97351fbffc49ed1fc526741d772
|
[
"MIT"
] | 1
|
2021-10-09T11:48:21.000Z
|
2021-10-09T11:48:21.000Z
|
C++/zigZagPattern.cpp
|
Chanchal2125/Hacktoberfest2021_PatternMaking
|
c962f1e93f45a97351fbffc49ed1fc526741d772
|
[
"MIT"
] | null | null | null |
C++/zigZagPattern.cpp
|
Chanchal2125/Hacktoberfest2021_PatternMaking
|
c962f1e93f45a97351fbffc49ed1fc526741d772
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
int c;
cin>>c;
int r = 3;
for(int i=1; i<=r; i++){
for(int j=1; j<=c; j++){
if((j+i)%4==0){
cout<<"*";
}
else if((j%4==0 && i==2)){
cout<<"*";
}
else{
cout<<" ";
}
}
cout<<endl;
}
return 0;
}
| 11.034483
| 32
| 0.428125
|
Chanchal2125
|
60f784ab8f262a7bbaab47844a0b93133bd1444b
| 189
|
hpp
|
C++
|
include/riw/concepts/signed_integral.hpp
|
SachiSakurane/riw
|
9d3f61359d82ba93d4a1efae06a86f2f5337564d
|
[
"BSL-1.0"
] | 2
|
2021-04-13T15:38:42.000Z
|
2021-06-13T16:12:11.000Z
|
include/riw/concepts/signed_integral.hpp
|
SachiSakurane/riw
|
9d3f61359d82ba93d4a1efae06a86f2f5337564d
|
[
"BSL-1.0"
] | 1
|
2021-06-07T08:14:24.000Z
|
2021-06-07T08:14:44.000Z
|
include/riw/concepts/signed_integral.hpp
|
SachiSakurane/riw
|
9d3f61359d82ba93d4a1efae06a86f2f5337564d
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <type_traits>
#include <riw/concepts/integral.hpp>
namespace riw {
template <class Type>
concept signed_integral = riw::integral<Type> && std::is_signed_v<Type>;
}
| 17.181818
| 72
| 0.746032
|
SachiSakurane
|
60f9c89cdcc144305597557c7d60663853036b26
| 979
|
cpp
|
C++
|
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlMessageFormatter Example/CPP/source3.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 421
|
2018-04-01T01:57:50.000Z
|
2022-03-28T15:24:42.000Z
|
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlMessageFormatter Example/CPP/source3.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 5,797
|
2018-04-02T21:12:23.000Z
|
2022-03-31T23:54:38.000Z
|
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlMessageFormatter Example/CPP/source3.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 1,482
|
2018-03-31T11:26:20.000Z
|
2022-03-30T22:36:45.000Z
|
// <Snippet3>
#using <System.dll>
#using <System.Messaging.dll>
using namespace System;
using namespace System::Messaging;
// placeholder; see complete definition elsewhere in this section
public ref class Order
{
public:
int itemId;
int quantity;
String^ address;
void ShipItems(){}
};
// Creates the queue if it does not already exist.
void EnsureQueueExists( String^ path )
{
if ( !MessageQueue::Exists( path ) )
{
MessageQueue::Create( path );
}
}
int main()
{
String^ queuePath = ".\\orders";
EnsureQueueExists( queuePath );
MessageQueue^ queue = gcnew MessageQueue( queuePath );
Order^ orderRequest = gcnew Order;
orderRequest->itemId = 1025;
orderRequest->quantity = 5;
orderRequest->address = "One Microsoft Way";
queue->Send( orderRequest );
// This line uses a new method you define on the Order class:
// orderRequest.PrintReceipt();
}
// </Snippet3>
| 20.829787
| 66
| 0.6476
|
hamarb123
|
60fb49517674a641dcb6cfb9ed7be53c047bee15
| 6,978
|
cc
|
C++
|
chrome/browser/apps/app_service/built_in_chromeos_apps.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/apps/app_service/built_in_chromeos_apps.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/apps/app_service/built_in_chromeos_apps.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/apps/app_service/built_in_chromeos_apps.h"
#include <utility>
#include <vector>
#include "ash/public/cpp/app_list/app_list_metrics.h"
#include "ash/public/cpp/app_list/internal_app_id_constants.h"
#include "ash/public/cpp/app_menu_constants.h"
#include "ash/public/cpp/keyboard_shortcut_viewer.h"
#include "base/metrics/user_metrics.h"
#include "base/time/time.h"
#include "chrome/browser/apps/app_service/app_icon_factory.h"
#include "chrome/browser/apps/app_service/app_service_metrics.h"
#include "chrome/browser/apps/app_service/menu_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/internal_app/internal_app_metadata.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/settings_window_manager_chromeos.h"
#include "chrome/browser/ui/webui/chromeos/login/discover/discover_window_manager.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/services/app_service/public/mojom/types.mojom.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
apps::mojom::AppPtr Convert(const app_list::InternalApp& internal_app) {
if ((internal_app.app_id == nullptr) ||
(internal_app.name_string_resource_id == 0) ||
(internal_app.icon_resource_id <= 0)) {
return apps::mojom::AppPtr();
}
apps::mojom::AppPtr app = apps::PublisherBase::MakeApp(
apps::mojom::AppType::kBuiltIn, internal_app.app_id,
apps::mojom::Readiness::kReady,
l10n_util::GetStringUTF8(internal_app.name_string_resource_id),
apps::mojom::InstallSource::kSystem);
if (internal_app.searchable_string_resource_id != 0) {
app->additional_search_terms.push_back(
l10n_util::GetStringUTF8(internal_app.searchable_string_resource_id));
}
app->icon_key = apps::mojom::IconKey::New(
apps::mojom::IconKey::kDoesNotChangeOverTime,
internal_app.icon_resource_id, apps::IconEffects::kNone);
app->recommendable = internal_app.recommendable
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->searchable = internal_app.searchable ? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->show_in_launcher = internal_app.show_in_launcher
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->show_in_search = internal_app.searchable
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->show_in_management = apps::mojom::OptionalBool::kFalse;
return app;
}
} // namespace
namespace apps {
BuiltInChromeOsApps::BuiltInChromeOsApps(
const mojo::Remote<apps::mojom::AppService>& app_service,
Profile* profile)
: profile_(profile) {
PublisherBase::Initialize(app_service, apps::mojom::AppType::kBuiltIn);
}
BuiltInChromeOsApps::~BuiltInChromeOsApps() = default;
bool BuiltInChromeOsApps::hide_settings_app_for_testing_ = false;
// static
bool BuiltInChromeOsApps::SetHideSettingsAppForTesting(bool hide) {
bool old_value = hide_settings_app_for_testing_;
hide_settings_app_for_testing_ = hide;
return old_value;
}
void BuiltInChromeOsApps::Connect(
mojo::PendingRemote<apps::mojom::Subscriber> subscriber_remote,
apps::mojom::ConnectOptionsPtr opts) {
std::vector<apps::mojom::AppPtr> apps;
if (profile_) {
// TODO(crbug.com/826982): move source of truth for built-in apps from
// ui/app_list to here when the AppService feature is enabled by default.
for (const auto& internal_app : app_list::GetInternalAppList(profile_)) {
apps::mojom::AppPtr app = Convert(internal_app);
if (!app.is_null()) {
if (hide_settings_app_for_testing_ &&
(internal_app.internal_app_name == BuiltInAppName::kSettings)) {
app->show_in_search = apps::mojom::OptionalBool::kFalse;
}
apps.push_back(std::move(app));
}
}
}
mojo::Remote<apps::mojom::Subscriber> subscriber(
std::move(subscriber_remote));
subscriber->OnApps(std::move(apps));
// Unlike other apps::mojom::Publisher implementations, we don't need to
// retain the subscriber (e.g. add it to a
// mojo::RemoteSet<apps::mojom::Subscriber> subscribers_) after this
// function returns. The list of built-in Chrome OS apps is fixed for the
// lifetime of the Chrome OS session. There won't be any further updates.
}
void BuiltInChromeOsApps::LoadIcon(
const std::string& app_id,
apps::mojom::IconKeyPtr icon_key,
apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
LoadIconCallback callback) {
constexpr bool is_placeholder_icon = false;
if (icon_key &&
(icon_key->resource_id != apps::mojom::IconKey::kInvalidResourceId)) {
LoadIconFromResource(icon_compression, size_hint_in_dip,
icon_key->resource_id, is_placeholder_icon,
static_cast<IconEffects>(icon_key->icon_effects),
std::move(callback));
return;
}
// On failure, we still run the callback, with the zero IconValue.
std::move(callback).Run(apps::mojom::IconValue::New());
}
void BuiltInChromeOsApps::Launch(const std::string& app_id,
int32_t event_flags,
apps::mojom::LaunchSource launch_source,
int64_t display_id) {
if (app_id == ash::kInternalAppIdKeyboardShortcutViewer) {
ash::ToggleKeyboardShortcutViewer();
} else if (app_id == ash::kInternalAppIdDiscover) {
base::RecordAction(base::UserMetricsAction("ShowDiscover"));
chromeos::DiscoverWindowManager::GetInstance()
->ShowChromeDiscoverPageForProfile(profile_);
} else if (app_id == ash::kReleaseNotesAppId) {
base::RecordAction(
base::UserMetricsAction("ReleaseNotes.SuggestionChipLaunched"));
chrome::LaunchReleaseNotes(profile_);
}
}
void BuiltInChromeOsApps::GetMenuModel(const std::string& app_id,
apps::mojom::MenuType menu_type,
int64_t display_id,
GetMenuModelCallback callback) {
apps::mojom::MenuItemsPtr menu_items = apps::mojom::MenuItems::New();
if (ShouldAddOpenItem(app_id, menu_type, profile_)) {
AddCommandItem(ash::MENU_OPEN_NEW, IDS_APP_CONTEXT_MENU_ACTIVATE_ARC,
&menu_items);
}
if (ShouldAddCloseItem(app_id, menu_type, profile_)) {
AddCommandItem(ash::MENU_CLOSE, IDS_SHELF_CONTEXT_MENU_CLOSE, &menu_items);
}
std::move(callback).Run(std::move(menu_items));
}
} // namespace apps
| 39.874286
| 84
| 0.691745
|
sarang-apps
|
60fb7467cd56855f2f511e3fd6c6023de48b5585
| 11,302
|
hpp
|
C++
|
include/GlobalNamespace/ColorHueSlider.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/ColorHueSlider.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/ColorHueSlider.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: HMUI.CircleSlider
#include "HMUI/CircleSlider.hpp"
// Including type: ColorChangeUIEventType
#include "GlobalNamespace/ColorChangeUIEventType.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`3<T1, T2, T3>
template<typename T1, typename T2, typename T3>
class Action_3;
}
// Forward declaring namespace: UnityEngine::EventSystems
namespace UnityEngine::EventSystems {
// Forward declaring type: PointerEventData
class PointerEventData;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// WARNING Size may be invalid!
// Autogenerated type: ColorHueSlider
// [TokenAttribute] Offset: FFFFFFFF
class ColorHueSlider : public HMUI::CircleSlider {
public:
// private UnityEngine.Color _darkColor
// Size: 0x10
// Offset: 0x124
UnityEngine::Color darkColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// private UnityEngine.Color _lightColor
// Size: 0x10
// Offset: 0x134
UnityEngine::Color lightColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// private System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> colorHueDidChangeEvent
// Size: 0x8
// Offset: 0x148
System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* colorHueDidChangeEvent;
// Field size check
static_assert(sizeof(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*) == 0x8);
// Creating value type constructor for type: ColorHueSlider
ColorHueSlider(UnityEngine::Color darkColor_ = {}, UnityEngine::Color lightColor_ = {}, System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* colorHueDidChangeEvent_ = {}) noexcept : darkColor{darkColor_}, lightColor{lightColor_}, colorHueDidChangeEvent{colorHueDidChangeEvent_} {}
// Get instance field reference: private UnityEngine.Color _darkColor
UnityEngine::Color& dyn__darkColor();
// Get instance field reference: private UnityEngine.Color _lightColor
UnityEngine::Color& dyn__lightColor();
// Get instance field reference: private System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> colorHueDidChangeEvent
System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*& dyn_colorHueDidChangeEvent();
// public System.Void add_colorHueDidChangeEvent(System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> value)
// Offset: 0x10E1214
void add_colorHueDidChangeEvent(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* value);
// public System.Void remove_colorHueDidChangeEvent(System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> value)
// Offset: 0x10E12BC
void remove_colorHueDidChangeEvent(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* value);
// private System.Void HandleNormalizedValueDidChange(HMUI.CircleSlider slider, System.Single normalizedValue)
// Offset: 0x10E1510
void HandleNormalizedValueDidChange(HMUI::CircleSlider* slider, float normalizedValue);
// public System.Void .ctor()
// Offset: 0x10E1618
// Implemented from: HMUI.CircleSlider
// Base method: System.Void CircleSlider::.ctor()
// Base method: System.Void Selectable::.ctor()
// Base method: System.Void UIBehaviour::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ColorHueSlider* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::ColorHueSlider::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ColorHueSlider*, creationType>()));
}
// protected override System.Void Awake()
// Offset: 0x10E1364
// Implemented from: UnityEngine.UI.Selectable
// Base method: System.Void Selectable::Awake()
void Awake();
// protected override System.Void OnDestroy()
// Offset: 0x10E13F0
// Implemented from: UnityEngine.EventSystems.UIBehaviour
// Base method: System.Void UIBehaviour::OnDestroy()
void OnDestroy();
// protected override System.Void UpdateVisuals()
// Offset: 0x10E147C
// Implemented from: HMUI.CircleSlider
// Base method: System.Void CircleSlider::UpdateVisuals()
void UpdateVisuals();
// public override System.Void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData)
// Offset: 0x10E158C
// Implemented from: UnityEngine.UI.Selectable
// Base method: System.Void Selectable::OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData)
void OnPointerUp(UnityEngine::EventSystems::PointerEventData* eventData);
}; // ColorHueSlider
// WARNING Not writing size check since size may be invalid!
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ColorHueSlider*, "", "ColorHueSlider");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::add_colorHueDidChangeEvent
// Il2CppName: add_colorHueDidChangeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*)>(&GlobalNamespace::ColorHueSlider::add_colorHueDidChangeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ColorHueSlider"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "ColorChangeUIEventType")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "add_colorHueDidChangeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::remove_colorHueDidChangeEvent
// Il2CppName: remove_colorHueDidChangeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*)>(&GlobalNamespace::ColorHueSlider::remove_colorHueDidChangeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ColorHueSlider"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "ColorChangeUIEventType")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "remove_colorHueDidChangeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::HandleNormalizedValueDidChange
// Il2CppName: HandleNormalizedValueDidChange
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(HMUI::CircleSlider*, float)>(&GlobalNamespace::ColorHueSlider::HandleNormalizedValueDidChange)> {
static const MethodInfo* get() {
static auto* slider = &::il2cpp_utils::GetClassFromName("HMUI", "CircleSlider")->byval_arg;
static auto* normalizedValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "HandleNormalizedValueDidChange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{slider, normalizedValue});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)()>(&GlobalNamespace::ColorHueSlider::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)()>(&GlobalNamespace::ColorHueSlider::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::UpdateVisuals
// Il2CppName: UpdateVisuals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)()>(&GlobalNamespace::ColorHueSlider::UpdateVisuals)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "UpdateVisuals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::OnPointerUp
// Il2CppName: OnPointerUp
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(UnityEngine::EventSystems::PointerEventData*)>(&GlobalNamespace::ColorHueSlider::OnPointerUp)> {
static const MethodInfo* get() {
static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "OnPointerUp", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData});
}
};
| 63.494382
| 332
| 0.750133
|
Fernthedev
|
60fbe922ed8a64b7ceae9b263b0cb60e2a62e301
| 119
|
cpp
|
C++
|
libwx/src/Maps/MapSpin.cpp
|
EnjoMitch/EnjoLib
|
321167146657cba1497a9d3b4ffd71430f9b24b3
|
[
"BSD-3-Clause"
] | 3
|
2021-06-14T15:36:46.000Z
|
2022-02-28T15:16:08.000Z
|
libwx/src/Maps/MapSpin.cpp
|
EnjoMitch/EnjoLib
|
321167146657cba1497a9d3b4ffd71430f9b24b3
|
[
"BSD-3-Clause"
] | 1
|
2021-07-17T07:52:15.000Z
|
2021-07-17T07:52:15.000Z
|
libwx/src/Maps/MapSpin.cpp
|
EnjoMitch/EnjoLib
|
321167146657cba1497a9d3b4ffd71430f9b24b3
|
[
"BSD-3-Clause"
] | 3
|
2021-07-12T14:52:38.000Z
|
2021-11-28T17:10:33.000Z
|
#include "MapSpin.hpp"
#include <wx/spinctrl.h>
MapSpin::MapSpin()
{
//ctor
}
MapSpin::~MapSpin()
{
//dtor
}
| 9.153846
| 24
| 0.596639
|
EnjoMitch
|
60fc05cd42d75e31402cc1252b989149b56c63fa
| 5,365
|
hpp
|
C++
|
modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellipke.hpp
|
timblechmann/nt2
|
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
|
[
"BSL-1.0"
] | 2
|
2016-09-14T00:23:53.000Z
|
2018-01-14T12:51:18.000Z
|
modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellipke.hpp
|
timblechmann/nt2
|
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
|
[
"BSL-1.0"
] | null | null | null |
modules/core/elliptic/include/nt2/toolbox/elliptic/functions/scalar/ellipke.hpp
|
timblechmann/nt2
|
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
|
[
"BSL-1.0"
] | null | null | null |
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SCALAR_ELLIPKE_HPP_INCLUDED
#define NT2_TOOLBOX_ELLIPTIC_FUNCTIONS_SCALAR_ELLIPKE_HPP_INCLUDED
#include <nt2/toolbox/elliptic/functions/ellipke.hpp>
#include <boost/fusion/tuple.hpp>
#include <nt2/include/functions/scalar/sqr.hpp>
#include <nt2/include/functions/scalar/ldexp.hpp>
#include <nt2/include/functions/scalar/sqrt.hpp>
#include <nt2/include/functions/scalar/sqr.hpp>
#include <nt2/include/functions/scalar/average.hpp>
#include <nt2/include/functions/scalar/oneminus.hpp>
#include <nt2/include/functions/scalar/is_greater.hpp>
#include <nt2/include/functions/scalar/is_equal.hpp>
#include <nt2/include/functions/scalar/is_ltz.hpp>
#include <nt2/toolbox/trigonometric/constants.hpp>
#include <nt2/include/constants/real.hpp>
#include <nt2/include/constants/digits.hpp>
#include <nt2/include/constants/eps.hpp>
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is arithmetic_
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::ellipke_, tag::cpu_,
(A0),
(scalar_<arithmetic_<A0> > )
)
{
typedef typename boost::dispatch::meta::as_floating<A0>::type etype;
typedef boost::fusion::tuple<etype, etype> result_type;
NT2_FUNCTOR_CALL(1)
{
return ellipke(etype(a0), Eps<etype>());
}
};
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is arithmetic_
/////////////////////////////////////////////////////////////////////////////
NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::ellipke_, tag::cpu_,
(A0),
(scalar_<arithmetic_<A0> >)
(scalar_<arithmetic_<A0> >)
)
{
typedef boost::fusion::tuple<A0, A0> result_type;
NT2_FUNCTOR_CALL_REPEAT(2)
{
typedef typename boost::dispatch::meta::as_floating<A0>::type type;
return ellipke(type(a0), type(a1));
}
};
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is floating_
/////////////////////////////////////////////////////////////////////////////
NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::ellipke_, tag::cpu_,
(A0),
(scalar_<floating_<A0> >)
(scalar_<floating_<A0> >)
)
{
typedef boost::fusion::tuple<A0, A0> result_type;
NT2_FUNCTOR_CALL_REPEAT(2)
{
result_type res;
nt2::ellipke(a0, a1, boost::fusion::at_c<0>(res), boost::fusion::at_c<1>(res));
return res;
}
};
/////////////////////////////////////////////////////////////////////////////
// reference based Implementations 1 input
/////////////////////////////////////////////////////////////////////////////
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellipke_, tag::cpu_,
(A0),
(scalar_<floating_<A0> >)
(scalar_<floating_<A0> >)
(scalar_<floating_<A0> >)
)
{
typedef int result_type;
inline result_type operator()(A0 const& a0,A0 & a1,A0 & a2) const
{
nt2::ellipke(a0,Eps<A0>(),a1,a2);
return 0;
}
};
/////////////////////////////////////////////////////////////////////////////
// reference based Implementations 2 inputs
/////////////////////////////////////////////////////////////////////////////
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::ellipke_, tag::cpu_,(A0),
(scalar_<floating_<A0> >)
(scalar_<floating_<A0> >)
(scalar_<floating_<A0> >)
(scalar_<floating_<A0> >)
)
{
typedef int result_type;
inline result_type operator()(A0 const& a0,A0 const& a1, A0 & a2,A0 & a3) const
{
if (is_ltz(a0) || gt(a0, One<A0>()))
{
a2 = Nan<A0>();
a3 = Nan<A0>();
return 0;
}
A0 m = a0;
A0 aa0 = One<A0>();;
A0 bb0 = nt2::sqrt(oneminus(m));
A0 s0 = m;
size_t i1 = 0;
A0 mm = 1;
A0 aa1 = Zero<A0>();
while (mm > a1) {
aa1 = average(aa0, bb0);
A0 bb1 = nt2::sqrt(aa0*bb0);
A0 cc1 = nt2::average(aa0, -bb0);
++i1;
mm = nt2::ldexp(sqr(cc1), i1);
s0 += mm;
aa0 = aa1;
bb0 = bb1;
};
if (is_equal(m, One<A0>()))
{
a2 = Inf<A0>();
a3 = One<A0>();
}
else
{
a2 = nt2::Pio_2<A0>()/aa1;
a3 = a2*(One<A0>()-s0*Half<A0>());
}
return 0;
}
};
} }
#endif
| 35.529801
| 85
| 0.459273
|
timblechmann
|
60fdd3353c1bec13e9aba440f1f8d2410a5768c7
| 345
|
cpp
|
C++
|
src_db/base_io_stream/OutputStream.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_db/base_io_stream/OutputStream.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_db/base_io_stream/OutputStream.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* OutputStream.cpp
*
* Created on: 2018/04/19
* Author: iizuka
*/
#include "debug/debugMacros.h"
#include "OutputStream.h"
namespace alinous {
OutputStream::OutputStream() {
}
OutputStream::~OutputStream() {
}
void OutputStream::write(const char* buffer, int size) {
write(buffer, 0, size);
}
} /* namespace alinous */
| 13.269231
| 56
| 0.657971
|
alinous-core
|
8801d684bd26fb6bcbb6b3c1be97d0e1658c1342
| 901
|
cpp
|
C++
|
01.basic_algorithms/01.Sort/quickSelection/quick_selection_template.cpp
|
digSelf/algorithms
|
c0778fb9b2ad441861ed0b681f60baf2d6472109
|
[
"MIT"
] | 4
|
2022-02-25T05:53:12.000Z
|
2022-03-21T02:42:39.000Z
|
01.basic_algorithms/01.Sort/quickSelection/quick_selection_template.cpp
|
digSelf/algorithms
|
c0778fb9b2ad441861ed0b681f60baf2d6472109
|
[
"MIT"
] | null | null | null |
01.basic_algorithms/01.Sort/quickSelection/quick_selection_template.cpp
|
digSelf/algorithms
|
c0778fb9b2ad441861ed0b681f60baf2d6472109
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
const int N = 1e5 + 5;
int arr[N];
// arr, [start, end], k
int quickSelection(int *arr, int start, int end, int k) {
// exit condition
if (start >= end)
return arr[start];
int left = start - 1, right = end + 1;
int pivot = arr[(left + right) >> 1];
while (left < right) {
while (arr[++left] < pivot); // >=
while (arr[--right] > pivot); // <=
if (left < right) {
std::swap(arr[left], arr[right]);
}
}
if (k <= right - start + 1) {
return quickSelection(arr, start, right, k);
} else {
return quickSelection(arr, right + 1, end, k - right + start - 1);
}
}
int main() {
int n = 0, k = 0;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
printf("%d\n", quickSelection(arr, 0, n - 1, k));
return 0;
}
| 21.452381
| 74
| 0.473918
|
digSelf
|
88028aa144f2dcf090153252157a1b9b46e13279
| 8,707
|
cc
|
C++
|
tensorflow/lite/toco/tflite/import.cc
|
aeverall/tensorflow
|
7992bf97711919f56f80bff9e5510cead4ab2095
|
[
"Apache-2.0"
] | 52
|
2018-11-12T06:39:35.000Z
|
2022-03-08T05:31:27.000Z
|
tensorflow/lite/toco/tflite/import.cc
|
aeverall/tensorflow
|
7992bf97711919f56f80bff9e5510cead4ab2095
|
[
"Apache-2.0"
] | 2
|
2018-12-04T08:35:40.000Z
|
2020-10-22T16:17:39.000Z
|
tensorflow/lite/toco/tflite/import.cc
|
aeverall/tensorflow
|
7992bf97711919f56f80bff9e5510cead4ab2095
|
[
"Apache-2.0"
] | 17
|
2019-03-11T01:17:16.000Z
|
2022-02-21T00:44:47.000Z
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/toco/tflite/import.h"
#include "flatbuffers/flexbuffers.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/toco/tflite/operator.h"
#include "tensorflow/lite/toco/tflite/types.h"
#include "tensorflow/lite/toco/tooling_util.h"
#include "tensorflow/lite/tools/verifier.h"
namespace toco {
namespace tflite {
namespace details {
void LoadTensorsTable(const ::tflite::Model& input_model,
TensorsTable* tensors_table) {
// TODO(aselle): add support to toco for multiple subgraphs.
auto tensors = (*input_model.subgraphs())[0]->tensors();
if (!tensors) return;
for (const auto* tensor : *tensors) {
tensors_table->push_back(tensor->name()->c_str());
}
}
void LoadOperatorsTable(const ::tflite::Model& input_model,
OperatorsTable* operators_table) {
auto opcodes = input_model.operator_codes();
if (!opcodes) return;
for (const auto* opcode : *opcodes) {
if (opcode->builtin_code() != ::tflite::BuiltinOperator_CUSTOM) {
operators_table->push_back(
EnumNameBuiltinOperator(opcode->builtin_code()));
} else {
operators_table->push_back(opcode->custom_code()->c_str());
}
}
}
} // namespace details
void ImportTensors(const ::tflite::Model& input_model, Model* model) {
auto tensors = (*input_model.subgraphs())[0]->tensors();
auto* buffers = input_model.buffers();
// auto tensors = input_model.tensors();
if (!tensors) return;
for (const auto* input_tensor : *tensors) {
Array& array = model->GetOrCreateArray(input_tensor->name()->c_str());
array.data_type = DataType::Deserialize(input_tensor->type());
int buffer_index = input_tensor->buffer();
auto* buffer = buffers->Get(buffer_index);
DataBuffer::Deserialize(*input_tensor, *buffer, &array);
auto shape = input_tensor->shape();
if (shape) {
// If the shape is 0-dimensional, make sure to record it as such,
// as oppose to leaving the array without a shape.
array.mutable_shape()->mutable_dims()->clear();
for (int i = 0; i < shape->Length(); ++i) {
auto d = shape->Get(i);
array.mutable_shape()->mutable_dims()->push_back(d);
}
}
auto quantization = input_tensor->quantization();
if (quantization) {
// Note that tf.mini only supports a single quantization parameters for
// the whole array.
if (quantization->min() && quantization->max()) {
CHECK_EQ(1, quantization->min()->Length());
CHECK_EQ(1, quantization->max()->Length());
MinMax& minmax = array.GetOrCreateMinMax();
minmax.min = quantization->min()->Get(0);
minmax.max = quantization->max()->Get(0);
}
if (quantization->scale() && quantization->zero_point()) {
CHECK_EQ(1, quantization->scale()->Length());
CHECK_EQ(1, quantization->zero_point()->Length());
QuantizationParams& q = array.GetOrCreateQuantizationParams();
q.scale = quantization->scale()->Get(0);
q.zero_point = quantization->zero_point()->Get(0);
}
}
}
}
void ImportOperators(
const ::tflite::Model& input_model,
const std::map<string, std::unique_ptr<BaseOperator>>& ops_by_name,
const details::TensorsTable& tensors_table,
const details::OperatorsTable& operators_table, Model* model) {
// TODO(aselle): add support for multiple subgraphs.
auto ops = (*input_model.subgraphs())[0]->operators();
if (!ops) return;
for (const auto* input_op : *ops) {
int index = input_op->opcode_index();
if (index < 0 || index > operators_table.size()) {
LOG(FATAL) << "Index " << index << " must be between zero and "
<< operators_table.size();
}
string opname = operators_table.at(index);
// Find and use the appropriate operator deserialization factory.
std::unique_ptr<Operator> new_op = nullptr;
if (ops_by_name.count(opname) == 0) {
string effective_opname = "TENSORFLOW_UNSUPPORTED";
if (ops_by_name.count(effective_opname) == 0) {
LOG(FATAL) << "Internal logic error: TENSORFLOW_UNSUPPORTED not found.";
}
new_op = ops_by_name.at(effective_opname)
->Deserialize(input_op->builtin_options(),
input_op->custom_options());
if (new_op->type == OperatorType::kUnsupported) {
auto* unsupported_op =
static_cast<TensorFlowUnsupportedOperator*>(new_op.get());
unsupported_op->tensorflow_op = opname;
// TODO(b/109932940): Remove this when quantized is removed.
// For now, we assume all ops are quantized.
unsupported_op->quantized = true;
} else {
LOG(FATAL) << "Expected a TensorFlowUnsupportedOperator";
}
} else {
new_op = ops_by_name.at(opname)->Deserialize(input_op->builtin_options(),
input_op->custom_options());
}
model->operators.emplace_back(new_op.release());
auto* op = model->operators.back().get();
// Make sure all the inputs and outputs are hooked up.
auto inputs = input_op->inputs();
for (int i = 0; i < inputs->Length(); i++) {
auto input_index = inputs->Get(i);
// input_index == -1 indicates optional tensor.
if (input_index != -1) {
const string& input_name = tensors_table.at(input_index);
op->inputs.push_back(input_name);
} else {
const string& tensor_name =
toco::AvailableArrayName(*model, "OptionalTensor");
model->CreateOptionalArray(tensor_name);
op->inputs.push_back(tensor_name);
}
}
auto outputs = input_op->outputs();
for (int i = 0; i < outputs->Length(); i++) {
auto output_index = outputs->Get(i);
const string& output_name = tensors_table.at(output_index);
op->outputs.push_back(output_name);
}
}
}
void ImportIOTensors(const ::tflite::Model& input_model,
const details::TensorsTable& tensors_table, Model* model) {
auto inputs = (*input_model.subgraphs())[0]->inputs();
if (inputs) {
for (int input : *inputs) {
const string& input_name = tensors_table.at(input);
model->flags.add_input_arrays()->set_name(input_name);
}
}
auto outputs = (*input_model.subgraphs())[0]->outputs();
if (outputs) {
for (int output : *outputs) {
const string& output_name = tensors_table.at(output);
model->flags.add_output_arrays(output_name);
}
}
}
namespace {
bool Verify(const void* buf, size_t len) {
::flatbuffers::Verifier verifier(static_cast<const uint8_t*>(buf), len);
return ::tflite::VerifyModelBuffer(verifier);
}
} // namespace
std::unique_ptr<Model> Import(const ModelFlags& model_flags,
const string& input_file_contents) {
::tflite::AlwaysTrueResolver r;
if (!::tflite::Verify(input_file_contents.data(), input_file_contents.size(),
r, ::tflite::DefaultErrorReporter())) {
LOG(FATAL) << "Invalid flatbuffer.";
}
const ::tflite::Model* input_model =
::tflite::GetModel(input_file_contents.data());
// Full list of all known operators.
const auto ops_by_name = BuildOperatorByNameMap();
if (!input_model->subgraphs() || input_model->subgraphs()->size() != 1) {
LOG(FATAL) << "Number of subgraphs in tflite should be exactly 1.";
}
std::unique_ptr<Model> model;
model.reset(new Model);
details::TensorsTable tensors_table;
details::LoadTensorsTable(*input_model, &tensors_table);
details::OperatorsTable operators_table;
details::LoadOperatorsTable(*input_model, &operators_table);
ImportTensors(*input_model, model.get());
ImportOperators(*input_model, ops_by_name, tensors_table, operators_table,
model.get());
ImportIOTensors(*input_model, tensors_table, model.get());
UndoWeightsShuffling(model.get());
return model;
}
} // namespace tflite
} // namespace toco
| 37.530172
| 80
| 0.653153
|
aeverall
|
8802ea92bd86d33480b6eac24195b90b8613c4a0
| 10,662
|
cpp
|
C++
|
LearnVideoToolBox/Tutorial05-LiveSample/LearnLIVE/Pods/LFLiveKit/LFLiveKit/coder/H264/LFNALUnit.cpp
|
xuyushiguang/video_audio
|
06290205568d5bd6981be06d6fa4b97bbebca63d
|
[
"MIT"
] | 50
|
2017-01-22T20:10:31.000Z
|
2020-11-18T08:24:48.000Z
|
LearnVideoToolBox/Tutorial05-LiveSample/LearnLIVE/Pods/LFLiveKit/LFLiveKit/coder/H264/LFNALUnit.cpp
|
xuyushiguang/video_audio
|
06290205568d5bd6981be06d6fa4b97bbebca63d
|
[
"MIT"
] | 4
|
2017-03-10T15:23:25.000Z
|
2019-01-07T17:51:06.000Z
|
LearnVideoToolBox/Tutorial05-LiveSample/LearnLIVE/Pods/LFLiveKit/LFLiveKit/coder/H264/LFNALUnit.cpp
|
xuyushiguang/video_audio
|
06290205568d5bd6981be06d6fa4b97bbebca63d
|
[
"MIT"
] | 21
|
2017-03-14T10:03:16.000Z
|
2018-08-31T16:15:24.000Z
|
//
// NALUnit.cpp
//
// Implementation of Basic parsing of H.264 NAL Units
//
// Geraint Davies, March 2004
//
// Copyright (c) GDCL 2004-2008 http://www.gdcl.co.uk/license.htm
#include "LFNALUnit.h"
// --- core NAL Unit implementation ------------------------------
LFNALUnit::LFNALUnit()
: m_pStart(NULL),
m_cBytes(0){
}
bool
LFNALUnit::GetStartCode(const BYTE *& pBegin, const BYTE *& pStart, int& cRemain){
// start code is any number of 00 followed by 00 00 01
// We need to record the first 00 in pBegin and the first byte
// following the startcode in pStart.
// if no start code is found, pStart and cRemain should be unchanged.
const BYTE *pThis = pStart;
int cBytes = cRemain;
pBegin = NULL;
while (cBytes >= 4) {
if (pThis[0] == 0) {
// remember first 00
if (pBegin == NULL) {
pBegin = pThis;
}
if ((pThis[1] == 0) &&
(pThis[2] == 1)) {
// point to type byte of NAL unit
pStart = pThis + 3;
cRemain = cBytes - 3;
return true;
}
} else {
pBegin = NULL;
}
cBytes--;
pThis++;
}
return false;
}
bool
LFNALUnit::Parse(const BYTE *pBuffer, int cSpace, int LengthSize, bool bEnd){
// if we get the start code but not the whole
// NALU, we can return false but still have the length property valid
m_cBytes = 0;
ResetBitstream();
if (LengthSize > 0) {
m_pStartCodeStart = pBuffer;
if (LengthSize > cSpace) {
return false;
}
m_cBytes = 0;
for (int i = 0; i < LengthSize; i++) {
m_cBytes <<= 8;
m_cBytes += *pBuffer++;
}
if ((m_cBytes+LengthSize) <= cSpace) {
m_pStart = pBuffer;
return true;
}
} else {
// this is not length-delimited: we must look for start codes
const BYTE *pBegin;
if (GetStartCode(pBegin, pBuffer, cSpace)) {
m_pStart = pBuffer;
m_pStartCodeStart = pBegin;
// either we find another startcode, or we continue to the
// buffer end (if this is the last block of data)
if (GetStartCode(pBegin, pBuffer, cSpace)) {
m_cBytes = int(pBegin - m_pStart);
return true;
} else if (bEnd) {
// current element extends to end of buffer
m_cBytes = cSpace;
return true;
}
}
}
return false;
}
// bitwise access to data
void
LFNALUnit::ResetBitstream(){
m_idx = 0;
m_nBits = 0;
m_cZeros = 0;
}
void
LFNALUnit::Skip(int nBits){
if (nBits < m_nBits) {
m_nBits -= nBits;
} else {
nBits -= m_nBits;
while (nBits >= 8) {
GetBYTE();
nBits -= 8;
}
if (nBits) {
m_byte = GetBYTE();
m_nBits = 8;
m_nBits -= nBits;
}
}
}
// get the next byte, removing emulation prevention bytes
BYTE
LFNALUnit::GetBYTE(){
if (m_idx >= m_cBytes) {
return 0;
}
BYTE b = m_pStart[m_idx++];
// to avoid start-code emulation, a byte 0x03 is inserted
// after any 00 00 pair. Discard that here.
if (b == 0) {
m_cZeros++;
if ((m_idx < m_cBytes) && (m_cZeros == 2) && (m_pStart[m_idx] == 0x03)) {
m_idx++;
m_cZeros = 0;
}
} else {
m_cZeros = 0;
}
return b;
}
unsigned long
LFNALUnit::GetBit(){
if (m_nBits == 0) {
m_byte = GetBYTE();
m_nBits = 8;
}
m_nBits--;
return (m_byte >> m_nBits) & 0x1;
}
unsigned long
LFNALUnit::GetWord(int nBits){
unsigned long u = 0;
while (nBits > 0) {
u <<= 1;
u |= GetBit();
nBits--;
}
return u;
}
unsigned long
LFNALUnit::GetUE(){
// Exp-Golomb entropy coding: leading zeros, then a one, then
// the data bits. The number of leading zeros is the number of
// data bits, counting up from that number of 1s as the base.
// That is, if you see
// 0001010
// You have three leading zeros, so there are three data bits (010)
// counting up from a base of 111: thus 111 + 010 = 1001 = 9
int cZeros = 0;
while (GetBit() == 0) {
cZeros++;
}
return GetWord(cZeros) + ((1 << cZeros)-1);
}
long
LFNALUnit::GetSE(){
// same as UE but signed.
// basically the unsigned numbers are used as codes to indicate signed numbers in pairs
// in increasing value. Thus the encoded values
// 0, 1, 2, 3, 4
// mean
// 0, 1, -1, 2, -2 etc
unsigned long UE = GetUE();
bool bPositive = UE & 1;
long SE = (UE + 1) >> 1;
if (!bPositive) {
SE = -SE;
}
return SE;
}
// --- sequence params parsing ---------------
LFSeqParamSet::LFSeqParamSet()
: m_cx(0),
m_cy(0),
m_FrameBits(0){
// SetRect(&m_rcFrame, 0, 0, 0, 0);
}
void
ScalingList(int size, LFNALUnit *pnalu){
long lastScale = 8;
long nextScale = 8;
for (int j = 0; j < size; j++) {
if (nextScale != 0) {
long delta = pnalu->GetSE();
nextScale = (lastScale + delta + 256) %256;
}
int scaling_list_j = (nextScale == 0) ? lastScale : nextScale;
lastScale = scaling_list_j;
}
}
bool
LFSeqParamSet::Parse(LFNALUnit *pnalu){
if (pnalu->Type() != LFNALUnit::NAL_Sequence_Params) {
return false;
}
// with the UE/SE type encoding, we must decode all the values
// to get through to the ones we want
pnalu->ResetBitstream();
pnalu->Skip(8); // type
m_Profile = pnalu->GetWord(8);
m_Compatibility = (BYTE)pnalu->GetWord(8);
m_Level = pnalu->GetWord(8);
/*int seq_param_id =*/ pnalu->GetUE();
if ((m_Profile == 100) || (m_Profile == 110) || (m_Profile == 122) || (m_Profile == 144)) {
int chroma_fmt = pnalu->GetUE();
if (chroma_fmt == 3) {
pnalu->Skip(1);
}
/* int bit_depth_luma_minus8 = */ pnalu->GetUE();
/* int bit_depth_chroma_minus8 = */ pnalu->GetUE();
pnalu->Skip(1);
int seq_scaling_matrix_present = pnalu->GetBit();
if (seq_scaling_matrix_present) {
for (int i = 0; i < 8; i++) {
if (pnalu->GetBit()) {
if (i < 6) {
ScalingList(16, pnalu);
} else {
ScalingList(64, pnalu);
}
}
}
}
}
int log2_frame_minus4 = pnalu->GetUE();
m_FrameBits = log2_frame_minus4 + 4;
int POCtype = pnalu->GetUE();
if (POCtype == 0) {
/*int log2_poc_minus4 =*/ pnalu->GetUE();
} else if (POCtype == 1) {
pnalu->Skip(1); // delta always zero
/*int nsp_offset =*/ pnalu->GetSE();
/*int nsp_top_to_bottom = */ pnalu->GetSE();
int num_ref_in_cycle = pnalu->GetUE();
for (int i = 0; i < num_ref_in_cycle; i++) {
/*int sf_offset =*/ pnalu->GetSE();
}
} else if (POCtype != 2) {
return false;
}
// else for POCtype == 2, no additional data in stream
/*int num_ref_frames =*/ pnalu->GetUE();
/*int gaps_allowed =*/ pnalu->GetBit();
int mbs_width = pnalu->GetUE();
int mbs_height = pnalu->GetUE();
m_cx = (mbs_width+1) * 16;
m_cy = (mbs_height+1) * 16;
// smoke test validation of sps
if ((m_cx > 2000) || (m_cy > 2000)) {
return false;
}
// if this is false, then sizes are field sizes and need adjusting
m_bFrameOnly = pnalu->GetBit() ? true : false;
if (!m_bFrameOnly) {
pnalu->Skip(1); // adaptive frame/field
}
pnalu->Skip(1); // direct 8x8
#if 0
SetRect(&m_rcFrame, 0, 0, 0, 0);
bool bCrop = pnalu->GetBit() ? true : false;
if (bCrop) {
// get cropping rect
// store as exclusive, pixel parameters relative to frame
m_rcFrame.left = pnalu->GetUE() * 2;
m_rcFrame.right = pnalu->GetUE() * 2;
m_rcFrame.top = pnalu->GetUE() * 2;
m_rcFrame.bottom = pnalu->GetUE() * 2;
}
if (!IsRectEmpty(&m_rcFrame)) {
m_rcFrame.right = m_cx - m_rcFrame.right;
m_rcFrame.bottom = m_cy - m_rcFrame.bottom;
}
#endif
// adjust rect from 2x2 units to pixels
if (!m_bFrameOnly) {
// adjust heights from field to frame
m_cy *= 2;
#if 0
m_rcFrame.top *= 2;
m_rcFrame.bottom *= 2;
#endif
}
// .. rest are not interesting yet
m_nalu = *pnalu;
return true;
}
// --- slice header --------------------
bool
LFSliceHeader::Parse(LFNALUnit *pnalu){
switch (pnalu->Type()) {
case LFNALUnit::NAL_IDR_Slice:
case LFNALUnit::NAL_Slice:
case LFNALUnit::NAL_PartitionA:
// all these begin with a slice header
break;
default:
return false;
}
// slice header has the 1-byte type, then one UE value,
// then the frame number.
pnalu->ResetBitstream();
pnalu->Skip(8); // NALU type
pnalu->GetUE(); // first mb in slice
pnalu->GetUE(); // slice type
pnalu->GetUE(); // pic param set id
m_framenum = pnalu->GetWord(m_nBitsFrame);
return true;
}
// --- SEI ----------------------
LFSEIMessage::LFSEIMessage(LFNALUnit *pnalu){
m_pnalu = pnalu;
const BYTE *p = pnalu->Start();
p++; // nalu type byte
m_type = 0;
while (*p == 0xff) {
m_type += 255;
p++;
}
m_type += *p;
p++;
m_length = 0;
while (*p == 0xff) {
m_type += 255;
p++;
}
m_length += *p;
p++;
m_idxPayload = int(p - m_pnalu->Start());
}
LFavcCHeader::LFavcCHeader(const BYTE *header, int cBytes){
if (cBytes < 8) {
return;
}
const BYTE *pEnd = header + cBytes;
int cSeq = header[5] & 0x1f;
header += 6;
for (int i = 0; i < cSeq; i++) {
if ((header+2) > pEnd) {
return;
}
int cThis = (header[0] << 8) + header[1];
header += 2;
if ((header+cThis) > pEnd) {
return;
}
if (i == 0) {
LFNALUnit n(header, cThis);
m_sps = n;
}
header += cThis;
}
if ((header + 3) >= pEnd) {
return;
}
int cPPS = header[0];
if (cPPS > 0) {
int cThis = (header[1] << 8) + header[2];
header += 3;
LFNALUnit n(header, cThis);
m_pps = n;
}
}
| 25.087059
| 95
| 0.518008
|
xuyushiguang
|
8802ec4a570f0f3dc44f28ca128c2d8668595f6e
| 7,243
|
cpp
|
C++
|
src/kre/ParticleSystemParameters.cpp
|
sweetkristas/hex_test
|
c29f8ad781e580bc80f43addcfce654e08ca0bc4
|
[
"MIT"
] | 6
|
2017-11-16T06:07:37.000Z
|
2020-06-26T20:24:01.000Z
|
src/kre/ParticleSystemParameters.cpp
|
sweetkristas/hex_test
|
c29f8ad781e580bc80f43addcfce654e08ca0bc4
|
[
"MIT"
] | null | null | null |
src/kre/ParticleSystemParameters.cpp
|
sweetkristas/hex_test
|
c29f8ad781e580bc80f43addcfce654e08ca0bc4
|
[
"MIT"
] | 3
|
2017-04-11T15:42:54.000Z
|
2018-07-07T09:48:56.000Z
|
/*
Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "asserts.hpp"
#include "spline.hpp"
#include "ParticleSystemParameters.hpp"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace KRE
{
namespace Particles
{
namespace
{
template<class T>
T sign(T x)
{
if(x < 0) {
return T(-1);
} else if(x > 0) {
return T(1);
}
return 0;
}
}
class RandomParameter : public Parameter
{
public:
RandomParameter(const variant& node);
virtual ~RandomParameter();
virtual float getValue(float t);
private:
float min_value_;
float max_value_;
RandomParameter(const RandomParameter&);
};
class OscillateParameter : public Parameter
{
public:
OscillateParameter(const variant& node);
virtual ~OscillateParameter();
virtual float getValue(float t);
private:
enum class WaveType {
SINE,
SQUARE,
};
WaveType osc_type_;
float frequency_;
float phase_;
float base_;
float amplitude_;
OscillateParameter(const OscillateParameter&);
};
class CurvedParameter : public Parameter
{
public:
enum class InterpolationType {
LINEAR,
SPLINE,
};
CurvedParameter(InterpolationType type, const variant& node);
virtual ~CurvedParameter();
virtual float getValue(float t);
private:
InterpolationType curve_type_;
geometry::control_point_vector control_points_;
geometry::control_point_vector::iterator findClosestPoint(float t);
CurvedParameter(const CurvedParameter&);
};
ParameterPtr Parameter::factory(const variant& node)
{
if(node.is_float() || node.is_int()) {
// single fixed attribute
return ParameterPtr(new FixedParameter(float(node.as_float())));
}
ASSERT_LOG(node.has_key("type"), "parameter must have 'type' attribute");
const std::string& ntype = node["type"].as_string();
if(ntype == "fixed") {
return ParameterPtr(new FixedParameter(node));
} else if(ntype == "dyn_random") {
return ParameterPtr(new RandomParameter(node));
} else if(ntype == "dyn_curved_linear") {
return ParameterPtr(new CurvedParameter(CurvedParameter::InterpolationType::LINEAR, node));
} else if(ntype == "dyn_curved_spline") {
return ParameterPtr(new CurvedParameter(CurvedParameter::InterpolationType::SPLINE, node));
} else if(ntype == "dyn_oscillate") {
return ParameterPtr(new OscillateParameter(node));
} else {
ASSERT_LOG(false, "Unrecognised affector type: " << ntype);
}
return ParameterPtr();
}
Parameter::Parameter()
{
}
Parameter::~Parameter()
{
}
FixedParameter::FixedParameter(float value)
: Parameter(ParameterType::FIXED),
value_(value)
{
}
FixedParameter::FixedParameter(const variant& node)
{
value_ = node["value"].as_float();
}
FixedParameter::~FixedParameter()
{
}
RandomParameter::RandomParameter(const variant& node)
: Parameter(ParameterType::RANDOM),
min_value_(node["min"].as_float(0.1f)),
max_value_(node["max"].as_float(1.0f))
{
}
RandomParameter::~RandomParameter()
{
}
float RandomParameter::getValue(float t)
{
return get_random_float(min_value_, max_value_);
}
OscillateParameter::OscillateParameter(const variant& node)
: Parameter(ParameterType::OSCILLATE),
frequency_(1.0f),
phase_(0.0f),
base_(0.0f),
amplitude_(1.0f),
osc_type_(WaveType::SINE)
{
if(node.has_key("oscillate_frequency")) {
frequency_ = node["oscillate_frequency"].as_float();
}
if(node.has_key("oscillate_phase")) {
phase_ = node["oscillate_phase"].as_float();
}
if(node.has_key("oscillate_base")) {
base_ = node["oscillate_base"].as_float();
}
if(node.has_key("oscillate_amplitude")) {
amplitude_ = node["oscillate_amplitude"].as_float();
}
if(node.has_key("oscillate_type")) {
const std::string& type = node["oscillate_type"].as_string();
if(type == "sine" || type == "sin") {
osc_type_ = WaveType::SINE;
} else if(type == "square" || type == "sq") {
osc_type_ = WaveType::SQUARE;
} else {
ASSERT_LOG(false, "unrecognised oscillate type: " << type);
}
}
}
OscillateParameter::~OscillateParameter()
{
}
float OscillateParameter::getValue(float t)
{
if(osc_type_ == WaveType::SINE) {
return float(base_ + amplitude_ * sin(2*M_PI*frequency_*t + phase_));
} else if(osc_type_ == WaveType::SQUARE) {
return float(base_ + amplitude_ * sign(sin(2*M_PI*frequency_*t + phase_)));
}
return 0;
}
CurvedParameter::CurvedParameter(InterpolationType type, const variant& node)
: Parameter(ParameterType::CURVED),
curve_type_(type)
{
ASSERT_LOG(node.has_key("control_point")
&& node["control_point"].is_list()
&& node["control_point"].num_elements() >= 2,
"curved parameters must have at least 2 control points.");
for(size_t n = 0; n != node["control_point"].num_elements(); ++n) {
ASSERT_LOG(node["control_point"][n].is_list()
&& node["control_point"][n].num_elements() == 2,
"Control points should be list of two elements.");
auto p = std::make_pair(node["control_point"][n][0].as_float(),
node["control_point"][n][1].as_float());
control_points_.push_back(p);
}
}
CurvedParameter::~CurvedParameter()
{
}
geometry::control_point_vector::iterator CurvedParameter::findClosestPoint(float t)
{
// find nearest control point to t
auto it = control_points_.begin();
for(; it != control_points_.end(); ++it) {
if(t < it->first) {
if(it == control_points_.begin()) {
return it;
} else {
return --it;
}
}
}
return --it;
}
float CurvedParameter::getValue(float t)
{
if(curve_type_ == InterpolationType::LINEAR) {
auto it = findClosestPoint(t);
auto it2 = it + 1;
if(it2 == control_points_.end()) {
return float(it2->second);
} else {
// linear interpolate, see http://en.wikipedia.org/wiki/Linear_interpolation
return float(it->second + (it2->second - it->second) * (t - it->first) / (it2->first - it->first));
}
} else if(curve_type_ == InterpolationType::SPLINE) {
// http://en.wikipedia.org/wiki/Spline_interpolation
geometry::spline spl(control_points_);
return float(spl.interpolate(t));
}
return 0;
}
}
}
| 27.229323
| 104
| 0.670717
|
sweetkristas
|
880645a72ed6c6aba599567a2a8e11188d975479
| 3,378
|
cxx
|
C++
|
tomviz/operators/OperatorResult.cxx
|
sukhsung/tomviz
|
b5ab44440be94476093206672e527c54098b58c7
|
[
"BSD-3-Clause"
] | null | null | null |
tomviz/operators/OperatorResult.cxx
|
sukhsung/tomviz
|
b5ab44440be94476093206672e527c54098b58c7
|
[
"BSD-3-Clause"
] | null | null | null |
tomviz/operators/OperatorResult.cxx
|
sukhsung/tomviz
|
b5ab44440be94476093206672e527c54098b58c7
|
[
"BSD-3-Clause"
] | null | null | null |
/* This source file is part of the Tomviz project, https://tomviz.org/.
It is released under the 3-Clause BSD License, see "LICENSE". */
#include "OperatorResult.h"
#include "ActiveObjects.h"
#include "ModuleFactory.h"
#include "ModuleManager.h"
#include "ModuleMolecule.h"
#include <vtkDataObject.h>
#include <vtkMolecule.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineController.h>
#include <vtkSMProxyManager.h>
#include <vtkSMSessionProxyManager.h>
#include <vtkSMSourceProxy.h>
#include <vtkTrivialProducer.h>
namespace tomviz {
OperatorResult::OperatorResult(QObject* parent)
: Superclass(parent), m_name(tr("Unnamed"))
{}
OperatorResult::~OperatorResult()
{
finalize();
}
void OperatorResult::setName(QString name)
{
m_name = name;
}
QString OperatorResult::name() const
{
return m_name;
}
void OperatorResult::setLabel(QString label)
{
m_label = label;
}
QString OperatorResult::label() const
{
return m_label;
}
void OperatorResult::setDescription(QString desc)
{
m_description = desc;
}
QString OperatorResult::description() const
{
return m_description;
}
bool OperatorResult::finalize()
{
deleteProxy();
return true;
}
vtkDataObject* OperatorResult::dataObject()
{
vtkDataObject* object = nullptr;
if (m_producerProxy.Get()) {
vtkObjectBase* clientSideObject = m_producerProxy->GetClientSideObject();
vtkTrivialProducer* producer =
vtkTrivialProducer::SafeDownCast(clientSideObject);
object = producer->GetOutputDataObject(0);
}
return object;
}
void OperatorResult::setDataObject(vtkDataObject* object)
{
vtkDataObject* previousObject = dataObject();
if (object == previousObject) {
// Nothing to do
return;
}
if (object == nullptr) {
deleteProxy();
return;
}
createProxyIfNeeded();
// Set the output in the producer
vtkObjectBase* clientSideObject = m_producerProxy->GetClientSideObject();
vtkTrivialProducer* producer =
vtkTrivialProducer::SafeDownCast(clientSideObject);
producer->SetOutput(object);
// If the result is a vtkMolecule, create a ModuleMolecule to display it
if (vtkMolecule::SafeDownCast(object)) {
auto view = ActiveObjects::instance().activeView();
ModuleManager::instance().createAndAddModule("Molecule", this, view);
}
}
vtkSMSourceProxy* OperatorResult::producerProxy()
{
createProxyIfNeeded();
return m_producerProxy;
}
void OperatorResult::createProxyIfNeeded()
{
if (!m_producerProxy.Get()) {
vtkSMProxyManager* proxyManager = vtkSMProxyManager::GetProxyManager();
vtkSMSessionProxyManager* sessionProxyManager =
proxyManager->GetActiveSessionProxyManager();
vtkSmartPointer<vtkSMProxy> producerProxy;
producerProxy.TakeReference(
sessionProxyManager->NewProxy("sources", "TrivialProducer"));
m_producerProxy = vtkSMSourceProxy::SafeDownCast(producerProxy);
m_producerProxy->UpdateVTKObjects();
vtkNew<vtkSMParaViewPipelineController> controller;
controller->PreInitializeProxy(m_producerProxy);
controller->PostInitializeProxy(m_producerProxy);
controller->RegisterPipelineProxy(m_producerProxy);
}
}
void OperatorResult::deleteProxy()
{
if (m_producerProxy.Get()) {
vtkNew<vtkSMParaViewPipelineController> controller;
controller->UnRegisterPipelineProxy(m_producerProxy);
m_producerProxy = nullptr;
}
}
} // namespace tomviz
| 23.458333
| 77
| 0.747484
|
sukhsung
|
88092dcacdb9dacb0171f27c1fdba05360e57e51
| 207
|
hpp
|
C++
|
callback.hpp
|
gregvw/cython-callback-numpy-arrays
|
6f3bc342745ca35651d79b74616e6c37fc523fdd
|
[
"MIT"
] | null | null | null |
callback.hpp
|
gregvw/cython-callback-numpy-arrays
|
6f3bc342745ca35651d79b74616e6c37fc523fdd
|
[
"MIT"
] | null | null | null |
callback.hpp
|
gregvw/cython-callback-numpy-arrays
|
6f3bc342745ca35651d79b74616e6c37fc523fdd
|
[
"MIT"
] | null | null | null |
typedef double (*Callback)( void *apply, const double &x );
void function( Callback callback,
void *apply,
const double *x,
double *y,
int n );
| 23
| 59
| 0.492754
|
gregvw
|
8809853778cab2d11a104a5a4c384d51aae913f2
| 5,570
|
cc
|
C++
|
chrome/browser/protector/session_startup_change_unittest.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | 1
|
2016-03-10T09:13:57.000Z
|
2016-03-10T09:13:57.000Z
|
chrome/browser/protector/session_startup_change_unittest.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | 1
|
2022-03-13T08:39:05.000Z
|
2022-03-13T08:39:05.000Z
|
chrome/browser/protector/session_startup_change_unittest.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/protector/base_setting_change.h"
#include "chrome/test/base/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace protector {
namespace {
const char kStartupUrl1[] = "http://google.com";
const char kStartupUrl2[] = "http://example.com";
} // namespace
class SessionStartupChangeTest : public testing::Test {
public:
SessionStartupChangeTest()
: initial_startup_pref_(SessionStartupPref::DEFAULT) {
}
virtual void SetUp() OVERRIDE {
// Ensure initial session startup pref.
SessionStartupPref::SetStartupPref(&profile_, initial_startup_pref_);
}
protected:
TestingProfile profile_;
SessionStartupPref initial_startup_pref_;
PinnedTabCodec::Tabs empty_pinned_tabs_;
};
TEST_F(SessionStartupChangeTest, InitAndApply) {
// Create a change and apply it.
SessionStartupPref backup_startup_pref(SessionStartupPref::LAST);
scoped_ptr<BaseSettingChange> change(
CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
// Setting is initially reverted to backup.
EXPECT_EQ(SessionStartupPref::LAST,
SessionStartupPref::GetStartupPref(&profile_).type);
change->Apply(NULL); // |browser| is unused.
// New setting active now.
EXPECT_EQ(SessionStartupPref::DEFAULT,
SessionStartupPref::GetStartupPref(&profile_).type);
}
TEST_F(SessionStartupChangeTest, InitAndDiscard) {
// Create a change and discard it.
SessionStartupPref backup_startup_pref(SessionStartupPref::LAST);
scoped_ptr<BaseSettingChange> change(
CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
// Setting is initially reverted to backup.
EXPECT_EQ(SessionStartupPref::LAST,
SessionStartupPref::GetStartupPref(&profile_).type);
change->Discard(NULL); // |browser| is unused.
// Nothing changed by Discard.
EXPECT_EQ(SessionStartupPref::LAST,
SessionStartupPref::GetStartupPref(&profile_).type);
}
TEST_F(SessionStartupChangeTest, ApplyButtonCaptions) {
// Apply button captions for "Open NTP" and "Open specific URLs" cases.
string16 open_ntp_caption =
l10n_util::GetStringUTF16(IDS_CHANGE_STARTUP_SETTINGS_NTP);
string16 open_url1_etc_caption =
l10n_util::GetStringFUTF16(IDS_CHANGE_STARTUP_SETTINGS_URLS,
UTF8ToUTF16(GURL(kStartupUrl1).host()));
string16 open_url2_etc_caption =
l10n_util::GetStringFUTF16(IDS_CHANGE_STARTUP_SETTINGS_URLS,
UTF8ToUTF16(GURL(kStartupUrl2).host()));
// Open NTP.
initial_startup_pref_.type = SessionStartupPref::DEFAULT;
SessionStartupPref backup_startup_pref(SessionStartupPref::DEFAULT);
scoped_ptr<BaseSettingChange> change(
CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
EXPECT_EQ(open_ntp_caption, change->GetApplyButtonText());
// Pinned tabs count as startup URLs as well.
PinnedTabCodec::Tabs new_pinned_tabs;
BrowserInit::LaunchWithProfile::Tab pinned_tab;
pinned_tab.url = GURL(kStartupUrl2);
new_pinned_tabs.push_back(pinned_tab);
change.reset(
CreateSessionStartupChange(initial_startup_pref_, new_pinned_tabs,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
EXPECT_EQ(open_url2_etc_caption, change->GetApplyButtonText());
// "Open URLs" with no URLs is the same as "Open NTP".
initial_startup_pref_.type = SessionStartupPref::URLS;
change.reset(
CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
EXPECT_EQ(open_ntp_caption, change->GetApplyButtonText());
// Single URL.
initial_startup_pref_.urls.push_back(GURL(kStartupUrl1));
change.reset(
CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
// Multiple URLs: name of the first one used.
initial_startup_pref_.urls.push_back(GURL(kStartupUrl2));
change.reset(
CreateSessionStartupChange(initial_startup_pref_, empty_pinned_tabs_,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
// Pinned tabs go after the startup URLs.
change.reset(
CreateSessionStartupChange(initial_startup_pref_, new_pinned_tabs,
backup_startup_pref, empty_pinned_tabs_));
ASSERT_TRUE(change->Init(&profile_));
EXPECT_EQ(open_url1_etc_caption, change->GetApplyButtonText());
}
} // namespace protector
| 40.656934
| 75
| 0.735189
|
gavinp
|
880bd00f22dbf5087fd53e5e1aff990899148672
| 14,303
|
cpp
|
C++
|
unit_tests/sharings/gl/gl_create_from_texture_tests.cpp
|
cwang64/compute-runtime
|
440520ffdc5807574f0abfbf64b3790d1c0547e4
|
[
"MIT"
] | null | null | null |
unit_tests/sharings/gl/gl_create_from_texture_tests.cpp
|
cwang64/compute-runtime
|
440520ffdc5807574f0abfbf64b3790d1c0547e4
|
[
"MIT"
] | null | null | null |
unit_tests/sharings/gl/gl_create_from_texture_tests.cpp
|
cwang64/compute-runtime
|
440520ffdc5807574f0abfbf64b3790d1c0547e4
|
[
"MIT"
] | 3
|
2019-05-16T07:22:51.000Z
|
2019-11-11T03:05:32.000Z
|
/*
* Copyright (C) 2018-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "runtime/helpers/get_info.h"
#include "runtime/mem_obj/image.h"
#include "runtime/sharings/gl/gl_texture.h"
#include "test.h"
#include "unit_tests/libult/create_command_stream.h"
#include "unit_tests/libult/ult_command_stream_receiver.h"
#include "unit_tests/mocks/gl/mock_gl_sharing.h"
#include "unit_tests/mocks/mock_context.h"
#include "unit_tests/mocks/mock_execution_environment.h"
#include "unit_tests/mocks/mock_gmm.h"
#include "gtest/gtest.h"
namespace NEO {
class CreateFromGlTexture : public ::testing::Test {
public:
// temp solution - we need to query size from GMM:
class TempMM : public OsAgnosticMemoryManager {
public:
TempMM() : OsAgnosticMemoryManager(*(new MockExecutionEnvironment(*platformDevices))) {
mockExecutionEnvironment.reset(&executionEnvironment);
}
GraphicsAllocation *createGraphicsAllocationFromSharedHandle(osHandle handle, const AllocationProperties &properties, bool requireSpecificBitness) override {
auto alloc = OsAgnosticMemoryManager::createGraphicsAllocationFromSharedHandle(handle, properties, requireSpecificBitness);
if (handle == CreateFromGlTexture::mcsHandle) {
alloc->setDefaultGmm(forceMcsGmm);
} else {
alloc->setDefaultGmm(forceGmm);
}
return alloc;
}
size_t forceAllocationSize;
Gmm *forceGmm = nullptr;
Gmm *forceMcsGmm = nullptr;
std::unique_ptr<ExecutionEnvironment> mockExecutionEnvironment;
};
void SetUp() override {
imgDesc = {};
imgInfo = {};
clContext.setSharingFunctions(glSharing->sharingFunctions.release());
ASSERT_FALSE(overrideCommandStreamReceiverCreation);
clContext.memoryManager = &tempMM;
}
void TearDown() override {
gmm.release();
mcsGmm.release();
}
void updateImgInfoAndForceGmm() {
imgInfo = MockGmm::initImgInfo(imgDesc, 0, nullptr);
gmm = MockGmm::queryImgParams(imgInfo);
tempMM.forceAllocationSize = imgInfo.size;
tempMM.forceGmm = gmm.get();
if (glSharing->m_textureInfoOutput.globalShareHandleMCS != 0) {
cl_image_desc mcsImgDesc = {};
mcsImgDesc.image_height = 128;
mcsImgDesc.image_row_pitch = 256;
mcsImgDesc.image_width = 128;
mcsImgDesc.image_type = CL_MEM_OBJECT_IMAGE2D;
auto mcsImgInfo = MockGmm::initImgInfo(mcsImgDesc, 0, nullptr);
mcsGmm = MockGmm::queryImgParams(mcsImgInfo);
tempMM.forceMcsGmm = mcsGmm.get();
}
}
cl_image_desc imgDesc;
ImageInfo imgInfo = {0};
std::unique_ptr<Gmm> gmm;
std::unique_ptr<Gmm> mcsGmm;
TempMM tempMM;
MockContext clContext;
std::unique_ptr<MockGlSharing> glSharing = std::make_unique<MockGlSharing>();
cl_int retVal;
static const unsigned int mcsHandle = 0xFF;
};
class CreateFromGlTextureTestsWithParams : public CreateFromGlTexture,
public ::testing::WithParamInterface<unsigned int /*cl_GLenum*/> {
};
class CreateFromGlTextureTests : public CreateFromGlTexture {
};
INSTANTIATE_TEST_CASE_P(
CreateFromGlTextureTestsWithParams,
CreateFromGlTextureTestsWithParams,
testing::ValuesIn(glTextureTargets::supportedTargets));
TEST_P(CreateFromGlTextureTestsWithParams, givenAllTextureSpecificParamsWhenCreateIsCalledThenFillImageDescription) {
unsigned int target = GetParam();
unsigned int baseTarget = GlTexture::getBaseTargetType(target);
imgDesc.image_type = GlTexture::getClMemObjectType(target);
imgDesc.image_width = 5;
if (target == GL_TEXTURE_1D_ARRAY || target == GL_TEXTURE_2D_ARRAY || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
imgDesc.image_array_size = 5;
}
if (target == GL_TEXTURE_2D || target == GL_TEXTURE_RECTANGLE ||
target == GL_TEXTURE_2D_ARRAY || target == GL_TEXTURE_3D ||
target == GL_RENDERBUFFER_EXT || baseTarget == GL_TEXTURE_CUBE_MAP_ARB ||
target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
imgDesc.image_height = 5;
}
if (target == GL_TEXTURE_3D) {
imgDesc.image_depth = 5;
}
if (target == GL_TEXTURE_BUFFER) {
// size and width for texture buffer are queried from textureInfo - not from gmm
glSharing->m_textureInfoOutput.textureBufferWidth = 64;
glSharing->m_textureInfoOutput.textureBufferSize = 1024;
glSharing->uploadDataToTextureInfo();
}
if (target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
imgDesc.num_samples = 16;
glSharing->m_textureInfoOutput.numberOfSamples = 16;
glSharing->m_textureInfoOutput.globalShareHandleMCS = CreateFromGlTexture::mcsHandle;
glSharing->uploadDataToTextureInfo();
}
updateImgInfoAndForceGmm();
auto glImage = GlTexture::createSharedGlTexture(&clContext, (cl_mem_flags)0, target, 0, 0, &retVal);
ASSERT_EQ(CL_SUCCESS, retVal);
if (target == GL_RENDERBUFFER_EXT) {
EXPECT_EQ(1, glSharing->dllParam->getParam("GLAcquireSharedRenderBufferCalled"));
} else {
EXPECT_EQ(1, glSharing->dllParam->getParam("GLAcquireSharedTextureCalled"));
}
EXPECT_EQ(GmmHelper::getCubeFaceIndex(target), glImage->getCubeFaceIndex());
auto glTexture = reinterpret_cast<GlTexture *>(glImage->peekSharingHandler());
EXPECT_EQ(glTexture->getTarget(), target);
EXPECT_EQ(glImage->getImageDesc().image_type, imgDesc.image_type);
if (target == GL_TEXTURE_BUFFER) {
EXPECT_EQ(glImage->getImageDesc().image_width,
static_cast<size_t>(glTexture->getTextureInfo()->textureBufferWidth));
EXPECT_EQ(glImage->getImageDesc().image_row_pitch,
static_cast<size_t>(glTexture->getTextureInfo()->textureBufferSize));
} else {
EXPECT_EQ(glImage->getImageDesc().image_width, gmm->gmmResourceInfo->getBaseWidth());
size_t slicePitch = glImage->getHostPtrSlicePitch();
size_t rowPitch = glImage->getHostPtrRowPitch();
EXPECT_EQ(glImage->getImageDesc().image_row_pitch, rowPitch);
EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, slicePitch);
size_t gmmRowPitch = gmm->gmmResourceInfo->getRenderPitch();
if (gmmRowPitch == 0) {
size_t alignedWidth = alignUp(glImage->getImageDesc().image_width, gmm->gmmResourceInfo->getHAlign());
size_t bpp = gmm->gmmResourceInfo->getBitsPerPixel() >> 3;
EXPECT_EQ(glImage->getImageDesc().image_row_pitch, alignedWidth * bpp);
} else {
EXPECT_EQ(glImage->getImageDesc().image_row_pitch, gmmRowPitch);
}
size_t ImageInfoRowPitch = 0;
retVal = clGetImageInfo(glImage, CL_IMAGE_ROW_PITCH, sizeof(size_t), &ImageInfoRowPitch, NULL);
ASSERT_EQ(CL_SUCCESS, retVal);
ASSERT_EQ(rowPitch, ImageInfoRowPitch);
size_t ImageInfoSlicePitch = 0;
slicePitch *= !(glImage->getImageDesc().image_type == CL_MEM_OBJECT_IMAGE2D || glImage->getImageDesc().image_type == CL_MEM_OBJECT_IMAGE1D || glImage->getImageDesc().image_type == CL_MEM_OBJECT_IMAGE1D_BUFFER);
retVal = clGetImageInfo(glImage, CL_IMAGE_SLICE_PITCH, sizeof(size_t), &ImageInfoSlicePitch, NULL);
ASSERT_EQ(CL_SUCCESS, retVal);
ASSERT_EQ(slicePitch, ImageInfoSlicePitch);
}
EXPECT_EQ(glImage->getImageDesc().image_height, gmm->gmmResourceInfo->getBaseHeight());
EXPECT_EQ(glImage->getImageDesc().image_array_size, gmm->gmmResourceInfo->getArraySize());
if (target == GL_TEXTURE_3D) {
EXPECT_EQ(glImage->getImageDesc().image_depth, gmm->gmmResourceInfo->getBaseDepth());
} else {
EXPECT_EQ(glImage->getImageDesc().image_depth, 0u);
}
if (imgDesc.image_array_size > 1 || imgDesc.image_depth > 1) {
GMM_REQ_OFFSET_INFO GMMReqInfo = {};
GMMReqInfo.ArrayIndex = imgDesc.image_array_size > 1 ? 1 : 0;
GMMReqInfo.Slice = imgDesc.image_depth > 1 ? 1 : 0;
GMMReqInfo.ReqLock = 1;
gmm->gmmResourceInfo->getOffset(GMMReqInfo);
size_t expectedSlicePitch = GMMReqInfo.Lock.Offset;
EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, expectedSlicePitch);
} else {
EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, imgInfo.size);
}
EXPECT_EQ(glImage->getQPitch(), gmm->queryQPitch(gmm->gmmResourceInfo->getResourceType()));
// gmm returns 1 by default - OCL requires 0
uint32_t numSamples = static_cast<uint32_t>(gmm->gmmResourceInfo->getNumSamples());
auto expectedNumSamples = getValidParam(numSamples, 0u, 1u);
EXPECT_EQ(expectedNumSamples, glImage->getImageDesc().num_samples);
if (target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
EXPECT_NE(nullptr, glImage->getMcsAllocation());
EXPECT_EQ(getValidParam(static_cast<uint32_t>(mcsGmm->gmmResourceInfo->getRenderPitch() / 128)),
glImage->getMcsSurfaceInfo().pitch);
EXPECT_EQ(static_cast<uint32_t>(mcsGmm->gmmResourceInfo->getQPitch()),
glImage->getMcsSurfaceInfo().qPitch);
EXPECT_EQ(GmmHelper::getRenderMultisamplesCount(static_cast<uint32_t>(gmm->gmmResourceInfo->getNumSamples())),
glImage->getMcsSurfaceInfo().multisampleCount);
}
delete glImage;
}
TEST_P(CreateFromGlTextureTestsWithParams, givenArrayTextureTargetAndArraySizeEqualOneWhenCreateIsCalledThenSlicePitchAndSizeAreEqual) {
unsigned int target = GetParam();
// only array targets
if (target == GL_TEXTURE_1D_ARRAY ||
target == GL_TEXTURE_2D_ARRAY) {
imgDesc.image_type = GlTexture::getClMemObjectType(target);
imgDesc.image_width = 5;
if (target == GL_TEXTURE_2D_ARRAY) {
imgDesc.image_height = 5;
}
imgDesc.image_array_size = 1;
updateImgInfoAndForceGmm();
auto glImage = GlTexture::createSharedGlTexture(&clContext, (cl_mem_flags)0, target, 0, 0, &retVal);
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, imgInfo.size);
delete glImage;
}
}
TEST_P(CreateFromGlTextureTestsWithParams, givenZeroRowPitchFromGmmWhenCreatingTextureThenComputeIt) {
unsigned int target = GL_TEXTURE_2D;
imgDesc.image_type = GlTexture::getClMemObjectType(target);
imgDesc.image_width = 5;
imgDesc.image_height = 5;
imgDesc.image_array_size = 1;
updateImgInfoAndForceGmm();
auto mockResInfo = reinterpret_cast<::testing::NiceMock<MockGmmResourceInfo> *>(gmm->gmmResourceInfo.get());
mockResInfo->overrideReturnedRenderPitch(0u);
auto alignedWidth = alignUp(imgDesc.image_width, gmm->gmmResourceInfo->getHAlign());
auto expectedRowPitch = alignedWidth * (gmm->gmmResourceInfo->getBitsPerPixel() >> 3);
auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, (cl_mem_flags)0, target, 0, 0, &retVal));
EXPECT_EQ(CL_SUCCESS, retVal);
EXPECT_EQ(imgInfo.size, glImage->getImageDesc().image_slice_pitch);
EXPECT_EQ(expectedRowPitch, glImage->getImageDesc().image_row_pitch);
}
TEST_F(CreateFromGlTextureTests, GivenGlTextureTargetAndMipLevelNegativeWhenCreateIsCalledThenMipMappedImageIsCreated) {
unsigned int target = GL_TEXTURE_3D;
cl_GLint miplevel = -1;
imgDesc.image_type = GlTexture::getClMemObjectType(target);
imgDesc.image_height = 13;
imgDesc.image_width = 15;
imgDesc.image_depth = 7;
updateImgInfoAndForceGmm();
auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, 0u, target, miplevel, 0, &retVal));
EXPECT_EQ(CL_SUCCESS, retVal);
size_t actualHeight = 0;
size_t actualWidth = 0;
size_t actualDepth = 0;
glImage->getImageInfo(CL_IMAGE_HEIGHT, sizeof(size_t), &actualHeight, nullptr);
glImage->getImageInfo(CL_IMAGE_WIDTH, sizeof(size_t), &actualWidth, nullptr);
glImage->getImageInfo(CL_IMAGE_DEPTH, sizeof(size_t), &actualDepth, nullptr);
EXPECT_EQ(13u, actualHeight);
EXPECT_EQ(15u, actualWidth);
EXPECT_EQ(7u, actualDepth);
EXPECT_EQ(gmm->gmmResourceInfo->getMaxLod() + 1, glImage->getImageDesc().num_mip_levels);
EXPECT_EQ(glImage->peekBaseMipLevel(), 0);
}
TEST_F(CreateFromGlTextureTests, GivenGlTextureTargetAndMipLevelNonNegativeWhenCreateIsCalledThenImageFromChosenMipLevelIsCreated) {
unsigned int target = GL_TEXTURE_3D;
cl_GLint miplevel = 2;
imgDesc.image_type = GlTexture::getClMemObjectType(target);
imgDesc.image_height = 13;
imgDesc.image_width = 15;
imgDesc.image_depth = 7;
updateImgInfoAndForceGmm();
auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, 0u, target, miplevel, 0, &retVal));
EXPECT_EQ(CL_SUCCESS, retVal);
size_t actualHeight = 0;
size_t actualWidth = 0;
size_t actualDepth = 0;
glImage->getImageInfo(CL_IMAGE_HEIGHT, sizeof(size_t), &actualHeight, nullptr);
glImage->getImageInfo(CL_IMAGE_WIDTH, sizeof(size_t), &actualWidth, nullptr);
glImage->getImageInfo(CL_IMAGE_DEPTH, sizeof(size_t), &actualDepth, nullptr);
EXPECT_EQ(3u, actualHeight);
EXPECT_EQ(3u, actualWidth);
EXPECT_EQ(1u, actualDepth);
EXPECT_GE(1u, glImage->getImageDesc().num_mip_levels);
EXPECT_EQ(glImage->peekBaseMipLevel(), 2);
}
TEST_F(CreateFromGlTextureTests, GivenGlTextureWhenCreateIsCalledThenAllocationTypeIsSharedImage) {
unsigned int target = GL_TEXTURE_3D;
cl_GLint miplevel = 2;
imgDesc.image_type = GlTexture::getClMemObjectType(target);
imgDesc.image_height = 13;
imgDesc.image_width = 15;
imgDesc.image_depth = 7;
updateImgInfoAndForceGmm();
auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, 0u, target, miplevel, 0, &retVal));
EXPECT_EQ(CL_SUCCESS, retVal);
ASSERT_NE(nullptr, glImage->getGraphicsAllocation());
EXPECT_EQ(GraphicsAllocation::AllocationType::SHARED_IMAGE, glImage->getGraphicsAllocation()->getAllocationType());
}
} // namespace NEO
| 41.33815
| 218
| 0.709851
|
cwang64
|
880c3ccccb127bf5b1b32c7c54718037fce865e1
| 261
|
cpp
|
C++
|
src/MySphere.cpp
|
nicholaschiasson/N3DIL
|
5b598b340c4850cb06f92194f48aa10c76a578aa
|
[
"MIT"
] | null | null | null |
src/MySphere.cpp
|
nicholaschiasson/N3DIL
|
5b598b340c4850cb06f92194f48aa10c76a578aa
|
[
"MIT"
] | 5
|
2015-10-19T03:35:56.000Z
|
2015-11-03T22:19:26.000Z
|
src/MySphere.cpp
|
nicholaschiasson/N3DIL
|
5b598b340c4850cb06f92194f48aa10c76a578aa
|
[
"MIT"
] | null | null | null |
#include "MySphere.h"
#include "MyIncludes.h"
MySphere::MySphere(MyIndexedVertexArray *vertexArray, MyVector3D & position, MyVector3D & scale, MyVector3D & rotation) :
MyGraphicsObject3D(vertexArray, position, scale, rotation)
{
}
MySphere::~MySphere()
{
}
| 20.076923
| 121
| 0.758621
|
nicholaschiasson
|
880f5d2038863ba860602fb540447258bd39b302
| 5,781
|
cpp
|
C++
|
src/InputSample.cpp
|
MSeys/PSV_2DCore_samples
|
3942c75391aeda9172dfed75165e80b5628a7a60
|
[
"MIT"
] | null | null | null |
src/InputSample.cpp
|
MSeys/PSV_2DCore_samples
|
3942c75391aeda9172dfed75165e80b5628a7a60
|
[
"MIT"
] | null | null | null |
src/InputSample.cpp
|
MSeys/PSV_2DCore_samples
|
3942c75391aeda9172dfed75165e80b5628a7a60
|
[
"MIT"
] | null | null | null |
#include "InputSample.h"
InputSample::InputSample()
{
}
InputSample::~InputSample()
{
}
void InputSample::Draw() const
{
// Note: This code was based on VitaTester (hence the code inside the Draw function instead of the respective event functions).
// https://github.com/SMOKE5/VitaTester
//
// You can however check ONE button state (accessible through ButtonEvent / bEvent inside the function)
// These are used in the menu, you can check out that class for an example how it works.
// Draw background
FillRect(Rectf{ 0, 0, float(SCREEN_WIDTH), float(SCREEN_HEIGHT) }, Color4{ 0, 0, 0, 255 });
Bank::FindUI("input_background")->Draw(Point2f{ 0, 54 });
// Draw analog sticks
Bank::FindUI("analog")->Draw(Point2f{ 85.f + float(PSV_Joysticks.at(LSTICK).x - 128) / 8, 285.f + float(PSV_Joysticks.at(LSTICK).y - 128) / 8.f });
Bank::FindUI("analog")->Draw(Point2f{ 802.f + float(PSV_Joysticks.at(RSTICK).x - 128) / 8, 285.f + float(PSV_Joysticks.at(RSTICK).y - 128) / 8.f });
// This is a way to check directly in other functions besides the Event functions
// These are also handy if you want to check multiple buttons states at the same time.
if(PSV_Buttons.at(DPAD_UP).isPressed || PSV_Buttons.at(DPAD_UP).isHeld)
{
Bank::FindUI("dpad")->Draw(Point2f{ 59, 134 });
}
if (PSV_Buttons.at(DPAD_DOWN).isPressed || PSV_Buttons.at(DPAD_DOWN).isHeld)
{
Bank::FindUI("dpad")->Draw(Point2f{ 130, 272 }, 3.14f);
}
if (PSV_Buttons.at(DPAD_LEFT).isPressed || PSV_Buttons.at(DPAD_LEFT).isHeld)
{
Bank::FindUI("dpad")->Draw(Point2f{ 24.3f, 238.6f }, -1.57f);
}
if (PSV_Buttons.at(DPAD_RIGHT).isPressed || PSV_Buttons.at(DPAD_RIGHT).isHeld)
{
Bank::FindUI("dpad")->Draw(Point2f{ 164, 166 }, 1.57f);
}
if (PSV_Buttons.at(CROSS).isPressed || PSV_Buttons.at(CROSS).isHeld)
{
Bank::FindUI("cross")->Draw(Point2f{ 830, 202 });
}
if (PSV_Buttons.at(CIRCLE).isPressed || PSV_Buttons.at(CIRCLE).isHeld)
{
Bank::FindUI("circle")->Draw(Point2f{ 869, 165 });
}
if (PSV_Buttons.at(SQUARE).isPressed || PSV_Buttons.at(SQUARE).isHeld)
{
Bank::FindUI("square")->Draw(Point2f{ 790, 165 });
}
if (PSV_Buttons.at(TRIANGLE).isPressed || PSV_Buttons.at(TRIANGLE).isHeld)
{
Bank::FindUI("triangle")->Draw(Point2f{ 830, 127 });
}
if (PSV_Buttons.at(START).isPressed || PSV_Buttons.at(START).isHeld)
{
Bank::FindUI("start")->Draw(Point2f{ 841, 373 });
}
if (PSV_Buttons.at(SELECT).isPressed || PSV_Buttons.at(SELECT).isHeld)
{
Bank::FindUI("select")->Draw(Point2f{ 781, 375 });
}
if (PSV_Buttons.at(LTRIGGER).isPressed || PSV_Buttons.at(LTRIGGER).isHeld)
{
Bank::FindUI("ltrigger")->Draw(Point2f{ 38, 40 });
}
if (PSV_Buttons.at(RTRIGGER).isPressed || PSV_Buttons.at(RTRIGGER).isHeld)
{
Bank::FindUI("rtrigger")->Draw(Point2f{ 720, 40 });
}
}
void InputSample::ProcessKeyUpEvent(const PSV_ButtonEvent& bEvent)
{
// Example of key event - triggered on release
if(bEvent.buttonType == SQUARE)
{
// if Square is released
}
// you can also use a switch
switch (bEvent.buttonType)
{
case CROSS: break;
case CIRCLE: break;
case SQUARE: break;
case TRIANGLE: break;
case LTRIGGER: break;
case RTRIGGER: break;
case DPAD_UP: break;
case DPAD_DOWN: break;
case DPAD_LEFT: break;
case DPAD_RIGHT: break;
case START: break;
case SELECT: break;
default: break;
}
// Note: There is not much data to send with button actions except held, pressed or released, but these are handled separately.
}
void InputSample::ProcessKeyDownEvent(const PSV_ButtonEvent& bEvent)
{
// Example of key event - triggered on press
// pressed state changes to false if button gets released or goes into held after 0.4 seconds
if(bEvent.buttonType == CIRCLE)
{
// if Circle is pressed
}
// you can also use a switch
switch (bEvent.buttonType)
{
case CROSS: break;
case CIRCLE: break;
case SQUARE: break;
case TRIANGLE: break;
case LTRIGGER: break;
case RTRIGGER: break;
case DPAD_UP: break;
case DPAD_DOWN: break;
case DPAD_LEFT: break;
case DPAD_RIGHT: break;
case START: break;
case SELECT: break;
default: break;
}
// Note: There is not much data to send with button actions except held, pressed or released, but these are handled separately.
}
void InputSample::ProcessKeyHeldEvent(const PSV_ButtonEvent& bEvent)
{
// Example of key event - triggered on held (which is after 0.4 seconds)
// held state changes to false if button gets released
if(bEvent.buttonType == CROSS)
{
// if Cross is held
}
// you can also use a switch
switch (bEvent.buttonType)
{
case CROSS: break;
case CIRCLE: break;
case SQUARE: break;
case TRIANGLE: break;
case LTRIGGER: break;
case RTRIGGER: break;
case DPAD_UP: break;
case DPAD_DOWN: break;
case DPAD_LEFT: break;
case DPAD_RIGHT: break;
case START: break;
case SELECT: break;
default: break;
}
// Note: There is not much data to send with button actions except held, pressed or released, but these are handled separately.
}
void InputSample::ProcessJoystickMotionEvent(const PSV_JoystickEvent& jEvent)
{
//Example of joystick motion
if(jEvent.joyType == LSTICK)
{
// Direction of joystick, including 4 main directions, the diagonals and the middle/idle position.
if(jEvent.joyDirection == MIDDLE)
{
// Middle position
}
else if(jEvent.joyDirection == NE)
{
// North east direction
}
// You can also use a switch case
switch(jEvent.joyDirection)
{
case NW: break;
case N: break;
case NE: break;
case W: break;
case E: break;
case SW: break;
case S: break;
case SE: break;
case MIDDLE: break;
default: break;
}
}
// There is also more values you can get using the JoystickEvent such as the x and y value, aswell as the angle the stick is positioned in, in radians or degrees.
}
| 26.640553
| 163
| 0.702647
|
MSeys
|
8811e63ba85df59615c1468a1fb1ee9b480581d3
| 811
|
hpp
|
C++
|
Source/SFMLIntegration/CSprite.hpp
|
sizlo/TimGameLib
|
b70605c4b043a928645f063a2bb3b267fa91f2c6
|
[
"MIT"
] | null | null | null |
Source/SFMLIntegration/CSprite.hpp
|
sizlo/TimGameLib
|
b70605c4b043a928645f063a2bb3b267fa91f2c6
|
[
"MIT"
] | null | null | null |
Source/SFMLIntegration/CSprite.hpp
|
sizlo/TimGameLib
|
b70605c4b043a928645f063a2bb3b267fa91f2c6
|
[
"MIT"
] | null | null | null |
//
// CSprite.hpp
// TimGameLib
//
// Created by Tim Brier on 18/10/2014.
// Copyright (c) 2014 tbrier. All rights reserved.
//
#ifndef __TimeGameLib__CSprite__
#define __TimeGameLib__CSprite__
// =============================================================================
// Include files
// -----------------------------------------------------------------------------
#include <SFML/Graphics.hpp>
// =============================================================================
// Class definition
// -----------------------------------------------------------------------------
class CSprite : public sf::Sprite
{
public:
CSprite();
CSprite(std::string filename);
CSprite(std::string filename, bool flipX, bool flipY);
~CSprite();
};
#endif /* defined(__TimeGameLib__CSprite__) */
| 27.033333
| 80
| 0.420469
|
sizlo
|
8814c5fa438660fa67acf61756d1f707129f6e9a
| 3,674
|
hpp
|
C++
|
inc/Measure.hpp
|
RuneKokNielsen/TopAwaRe
|
de5099111fca790a3ddf46aeb7f7aeae70229715
|
[
"MIT"
] | 2
|
2019-11-28T11:45:50.000Z
|
2020-03-25T13:38:29.000Z
|
inc/Measure.hpp
|
RuneKokNielsen/TopAwaRe
|
de5099111fca790a3ddf46aeb7f7aeae70229715
|
[
"MIT"
] | null | null | null |
inc/Measure.hpp
|
RuneKokNielsen/TopAwaRe
|
de5099111fca790a3ddf46aeb7f7aeae70229715
|
[
"MIT"
] | null | null | null |
#ifndef MEASURE_HPP
#define MEASURE_HPP
#include "Node.hpp"
#include <Image.hpp>
#include "Interpolator.hpp"
namespace measure{
/**
* A Context holds time-local variables necessary for locally
* computing a measure and its gradients.
**/
struct Context{
/**
* \param timesteps The number of timesteps within this context.
**/
Context(uint timesteps): _timesteps(timesteps){
};
/**
* Get the context at given timestep.
* \param timestep The timestep of the target context.
**/
virtual Context* getContext(uint timestep) = 0;
// Number of timesteps of the context.
uint _timesteps;
// Interpolator object which might be required for computations.
Interpolator* _interpolator;
virtual ~Context(){
}
/**
* Initialize the context with required objects.
* \param S The target image.
* \param I The source image.
* \param interpolator Interpolator object to be used within this context.
**/
virtual void init(Image S, Image I, Interpolator* interpolator){
_I = I;
_S = S;
_interpolator = interpolator;
}
/**
* Update the context based on the current transformation at the
* timestep of this context.
**/
virtual void update(vector<Image> phi, vector<Image> phiInv){
// Surpress unused-warning of optional virtual function
(void) phi; (void) phiInv;
};
// Reference to the source image.
Image _I;
// Reference to the target image.
Image _S;
/**
* Holds the individual contexts for all timesteps, this object
* corresponding to the first element.
**/
vector<Context*> _subs;
};
/**
* A Measure describes how to compute a given similarity measure
* as well as its gradients within a given Measure::Context.
**/
class Measure : Conf::Node
{
public:
/**
* Given a context, computes the similarity measure value.
* \param context The context to compute the measure in.
**/
virtual double measure(const Context* context) const = 0;
/**
* Given a context, computes the gradient of the similarity measure.
* \param context The context to compute the gradient in.
**/
virtual vector<Image> gradient(const Context* context) const = 0;
/**
* Returns the default context for a dsicretization with
* given number of timesteps.
* \param timesteps The number of timesteps.
**/
virtual Context *baseContext(uint timesteps) const = 0;
};
/**
* An AlphaContext is any Measure::Context that somehow handles
* an alpha channel. This is required for applying the
* topology-aware parts of the implementation.
**/
struct AlphaContext : virtual Context{
AlphaContext(): Context(1){
}
virtual ~AlphaContext(){
}
/**
* Returns a copy of itself that can be modified without changing
* anything within this context.
**/
virtual AlphaContext* copy() = 0;
virtual AlphaContext *getContext(uint t){ return t==0?this:dynamic_cast<AlphaContext*>(_subs.at(t)); }
/**
* One-sided update.
* This function is used for finite difference approximation
* of the gradient w.r.t. changes in the singularity model.
* Updates the context using a full transformation.
* Note that the alpha field within this context has already
* accounted for this transformation and as such should not
* be transformed again!
* \param phi Transformation to apply.
**/
virtual void updateAlpha(vector<Image> phi) = 0;
/**
* Current alpha field.
**/
Image alpha;
};
}
#endif
| 26.056738
| 106
| 0.650517
|
RuneKokNielsen
|
8816bf9e86f575c772285e37008732f0191fcafc
| 42,515
|
cc
|
C++
|
processors/IA32/bochs/iodev/cdrom.cc
|
bavison/opensmalltalk-vm
|
d494240736f7c0309e3e819784feb1d53ed0985a
|
[
"MIT"
] | 445
|
2016-06-30T08:19:11.000Z
|
2022-03-28T06:09:49.000Z
|
processors/IA32/bochs/iodev/cdrom.cc
|
bavison/opensmalltalk-vm
|
d494240736f7c0309e3e819784feb1d53ed0985a
|
[
"MIT"
] | 439
|
2016-06-29T20:14:36.000Z
|
2022-03-17T19:59:58.000Z
|
processors/IA32/bochs/iodev/cdrom.cc
|
bavison/opensmalltalk-vm
|
d494240736f7c0309e3e819784feb1d53ed0985a
|
[
"MIT"
] | 137
|
2016-07-02T17:32:07.000Z
|
2022-03-20T11:17:25.000Z
|
/////////////////////////////////////////////////////////////////////////
// $Id: cdrom.cc,v 1.91 2008/02/15 22:05:41 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/////////////////////////////////////////////////////////////////////////
// These are the low-level CDROM functions which are called
// from 'harddrv.cc'. They effect the OS specific functionality
// needed by the CDROM emulation in 'harddrv.cc'. Mostly, just
// ioctl() calls and such. Should be fairly easy to add support
// for your OS if it is not supported yet.
#ifndef BX_IODEV_CDROM_H
#define BX_IODEV_CDROM_H
// Define BX_PLUGGABLE in files that can be compiled into plugins. For
// platforms that require a special tag on exported symbols, BX_PLUGGABLE
// is used to know when we are exporting symbols and when we are importing.
#define BX_PLUGGABLE
#include "bochs.h"
#if BX_SUPPORT_CDROM
#include "cdrom.h"
#define LOG_THIS /* no SMF tricks here, not needed */
extern "C" {
#include <errno.h>
}
#ifdef __linux__
extern "C" {
#include <sys/ioctl.h>
#include <linux/cdrom.h>
// I use the framesize in non OS specific code too
#define BX_CD_FRAMESIZE CD_FRAMESIZE
}
#elif defined(__GNU__) || (defined(__CYGWIN32__) && !defined(WIN32))
extern "C" {
#include <sys/ioctl.h>
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
}
#elif BX_WITH_MACOS
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
#elif defined(__sun)
extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/cdio.h>
#define BX_CD_FRAMESIZE CDROM_BLK_2048
}
#elif defined(__DJGPP__)
extern "C" {
#include <sys/ioctl.h>
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
}
#elif defined(__BEOS__)
#include "cdrom_beos.h"
#define BX_CD_FRAMESIZE 2048
#elif (defined(__NetBSD__) || defined(__NetBSD_kernel__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
// OpenBSD pre version 2.7 may require extern "C" { } structure around
// all the includes, because the i386 sys/disklabel.h contains code which
// c++ considers invalid.
#include <sys/types.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/cdio.h>
#include <sys/ioctl.h>
#include <sys/disklabel.h>
// ntohl(x) et al have been moved out of sys/param.h in FreeBSD 5
#include <netinet/in.h>
// XXX
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
#elif defined(__APPLE__)
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#if defined (__GNUC__) && (__GNUC__ >= 4)
#include <sys/disk.h>
#else
#include <dev/disk.h>
#endif
#include <errno.h>
#include <paths.h>
#include <sys/param.h>
#define Float32 KLUDGE_Float32
#define Float64 KLUDGE_Float64
#include <IOKit/IOKitLib.h>
#include <IOKit/IOBSD.h>
#include <IOKit/storage/IOCDMedia.h>
#include <IOKit/storage/IOMedia.h>
#include <IOKit/storage/IOCDTypes.h>
#include <CoreFoundation/CoreFoundation.h>
#undef Float32
#undef Float64
// These definitions were taken from mount_cd9660.c
// There are some similar definitions in IOCDTypes.h
// however there seems to be some dissagreement in
// the definition of CDTOC.length
struct _CDMSF {
u_char minute;
u_char second;
u_char frame;
};
#define MSF_TO_LBA(msf) \
(((((msf).minute * 60UL) + (msf).second) * 75UL) + (msf).frame - 150)
struct _CDTOC_Desc {
u_char session;
u_char ctrl_adr; /* typed to be machine and compiler independent */
u_char tno;
u_char point;
struct _CDMSF address;
u_char zero;
struct _CDMSF p;
};
struct _CDTOC {
u_short length; /* in native cpu endian */
u_char first_session;
u_char last_session;
struct _CDTOC_Desc trackdesc[1];
};
static kern_return_t FindEjectableCDMedia(io_iterator_t *mediaIterator, mach_port_t *masterPort);
static kern_return_t GetDeviceFilePath(io_iterator_t mediaIterator, char *deviceFilePath, CFIndex maxPathSize);
//int OpenDrive(const char *deviceFilePath);
static struct _CDTOC *ReadTOC(const char *devpath);
static char CDDevicePath[MAXPATHLEN];
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
#elif defined(WIN32)
// windows.h included by bochs.h
#include <winioctl.h>
#include "aspi-win32.h"
#include "scsidefs.h"
DWORD (*GetASPI32SupportInfo)(void);
DWORD (*SendASPI32Command)(LPSRB);
BOOL (*GetASPI32Buffer)(PASPI32BUFF);
BOOL (*FreeASPI32Buffer)(PASPI32BUFF);
BOOL (*TranslateASPI32Address)(PDWORD,PDWORD);
DWORD (*GetASPI32DLLVersion)(void);
static OSVERSIONINFO osinfo;
static BOOL isWindowsXP;
static BOOL bHaveDev;
static UINT cdromCount = 0;
static HINSTANCE hASPI = NULL;
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
// READ_TOC_EX structure(s) and #defines
#define CDROM_READ_TOC_EX_FORMAT_TOC 0x00
#define CDROM_READ_TOC_EX_FORMAT_SESSION 0x01
#define CDROM_READ_TOC_EX_FORMAT_FULL_TOC 0x02
#define CDROM_READ_TOC_EX_FORMAT_PMA 0x03
#define CDROM_READ_TOC_EX_FORMAT_ATIP 0x04
#define CDROM_READ_TOC_EX_FORMAT_CDTEXT 0x05
#define IOCTL_CDROM_BASE FILE_DEVICE_CD_ROM
#define IOCTL_CDROM_READ_TOC_EX CTL_CODE(IOCTL_CDROM_BASE, 0x0015, METHOD_BUFFERED, FILE_READ_ACCESS)
#ifndef IOCTL_DISK_GET_LENGTH_INFO
#define IOCTL_DISK_GET_LENGTH_INFO CTL_CODE(IOCTL_DISK_BASE, 0x0017, METHOD_BUFFERED, FILE_READ_ACCESS)
#endif
typedef struct _CDROM_READ_TOC_EX {
UCHAR Format : 4;
UCHAR Reserved1 : 3; // future expansion
UCHAR Msf : 1;
UCHAR SessionTrack;
UCHAR Reserved2; // future expansion
UCHAR Reserved3; // future expansion
} CDROM_READ_TOC_EX, *PCDROM_READ_TOC_EX;
typedef struct _TRACK_DATA {
UCHAR Reserved;
UCHAR Control : 4;
UCHAR Adr : 4;
UCHAR TrackNumber;
UCHAR Reserved1;
UCHAR Address[4];
} TRACK_DATA, *PTRACK_DATA;
typedef struct _CDROM_TOC_SESSION_DATA {
// Header
UCHAR Length[2]; // add two bytes for this field
UCHAR FirstCompleteSession;
UCHAR LastCompleteSession;
// One track, representing the first track
// of the last finished session
TRACK_DATA TrackData[1];
} CDROM_TOC_SESSION_DATA, *PCDROM_TOC_SESSION_DATA;
// End READ_TOC_EX structure(s) and #defines
#else // all others (Irix, Tru64)
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#define BX_CD_FRAMESIZE 2048
#define CD_FRAMESIZE 2048
#endif
#include <stdio.h>
#ifdef __APPLE__
static kern_return_t FindEjectableCDMedia(io_iterator_t *mediaIterator,
mach_port_t *masterPort)
{
kern_return_t kernResult;
CFMutableDictionaryRef classesToMatch;
kernResult = IOMasterPort(bootstrap_port, masterPort);
if (kernResult != KERN_SUCCESS)
{
fprintf (stderr, "IOMasterPort returned %d\n", kernResult);
return kernResult;
}
// CD media are instances of class kIOCDMediaClass.
classesToMatch = IOServiceMatching(kIOCDMediaClass);
if (classesToMatch == NULL)
fprintf (stderr, "IOServiceMatching returned a NULL dictionary.\n");
else
{
// Each IOMedia object has a property with key kIOMediaEjectableKey
// which is true if the media is indeed ejectable. So add property
// to CFDictionary for matching.
CFDictionarySetValue(classesToMatch,
CFSTR(kIOMediaEjectableKey), kCFBooleanTrue);
}
kernResult = IOServiceGetMatchingServices(*masterPort,
classesToMatch, mediaIterator);
if ((kernResult != KERN_SUCCESS) || (*mediaIterator == NULL))
fprintf(stderr, "No ejectable CD media found.\n kernResult = %d\n", kernResult);
return kernResult;
}
static kern_return_t GetDeviceFilePath(io_iterator_t mediaIterator,
char *deviceFilePath, CFIndex maxPathSize)
{
io_object_t nextMedia;
kern_return_t kernResult = KERN_FAILURE;
nextMedia = IOIteratorNext(mediaIterator);
if (nextMedia == NULL)
{
*deviceFilePath = '\0';
}
else
{
CFTypeRef deviceFilePathAsCFString;
deviceFilePathAsCFString = IORegistryEntryCreateCFProperty(nextMedia, CFSTR(kIOBSDNameKey),
kCFAllocatorDefault, 0);
*deviceFilePath = '\0';
if (deviceFilePathAsCFString)
{
size_t devPathLength = strlen(_PATH_DEV);
strcpy(deviceFilePath, _PATH_DEV);
if (CFStringGetCString((const __CFString *) deviceFilePathAsCFString,
deviceFilePath + devPathLength,
maxPathSize - devPathLength,
kCFStringEncodingASCII))
{
// fprintf(stderr, "BSD path: %s\n", deviceFilePath);
kernResult = KERN_SUCCESS;
}
CFRelease(deviceFilePathAsCFString);
}
}
IOObjectRelease(nextMedia);
return kernResult;
}
static int OpenDrive(const char *deviceFilePath)
{
int fileDescriptor = open(deviceFilePath, O_RDONLY);
if (fileDescriptor == -1)
fprintf(stderr, "Error %d opening device %s.\n", errno, deviceFilePath);
return fileDescriptor;
}
static struct _CDTOC * ReadTOC(const char *devpath)
{
struct _CDTOC * toc_p = NULL;
io_iterator_t iterator = 0;
io_registry_entry_t service = 0;
CFDictionaryRef properties = 0;
CFDataRef data = 0;
mach_port_t port = 0;
char *devname;
if ((devname = strrchr(devpath, '/')) != NULL) {
++devname;
}
else {
devname = (char *) devpath;
}
if (IOMasterPort(bootstrap_port, &port) != KERN_SUCCESS) {
fprintf(stderr, "IOMasterPort failed\n");
goto Exit;
}
if (IOServiceGetMatchingServices(port, IOBSDNameMatching(port, 0, devname),
&iterator) != KERN_SUCCESS) {
fprintf(stderr, "IOServiceGetMatchingServices failed\n");
goto Exit;
}
service = IOIteratorNext(iterator);
IOObjectRelease(iterator);
iterator = 0;
while (service && !IOObjectConformsTo(service, "IOCDMedia")) {
if (IORegistryEntryGetParentIterator(service, kIOServicePlane,
&iterator) != KERN_SUCCESS)
{
fprintf(stderr, "IORegistryEntryGetParentIterator failed\n");
goto Exit;
}
IOObjectRelease(service);
service = IOIteratorNext(iterator);
IOObjectRelease(iterator);
}
if (service == NULL) {
fprintf(stderr, "CD media not found\n");
goto Exit;
}
if (IORegistryEntryCreateCFProperties(service, (__CFDictionary **) &properties,
kCFAllocatorDefault,
kNilOptions) != KERN_SUCCESS)
{
fprintf(stderr, "IORegistryEntryGetParentIterator failed\n");
goto Exit;
}
data = (CFDataRef) CFDictionaryGetValue(properties, CFSTR(kIOCDMediaTOCKey));
if (data == NULL) {
fprintf(stderr, "CFDictionaryGetValue failed\n");
goto Exit;
}
else {
CFRange range;
CFIndex buflen;
buflen = CFDataGetLength(data) + 1;
range = CFRangeMake(0, buflen);
toc_p = (struct _CDTOC *) malloc(buflen);
if (toc_p == NULL) {
fprintf(stderr, "Out of memory\n");
goto Exit;
}
else {
CFDataGetBytes(data, range, (unsigned char *) toc_p);
}
/*
fprintf(stderr, "Table of contents\n length %d first %d last %d\n",
toc_p->length, toc_p->first_session, toc_p->last_session);
*/
CFRelease(properties);
}
Exit:
if (service) {
IOObjectRelease(service);
}
return toc_p;
}
#endif
#ifdef WIN32
bool ReadCDSector(unsigned int hid, unsigned int tid, unsigned int lun, unsigned long frame, unsigned char *buf, int bufsize)
{
HANDLE hEventSRB;
SRB_ExecSCSICmd srb;
DWORD dwStatus;
hEventSRB = CreateEvent(NULL, TRUE, FALSE, NULL);
memset(&srb,0,sizeof(SRB_ExecSCSICmd));
srb.SRB_Cmd = SC_EXEC_SCSI_CMD;
srb.SRB_HaId = hid;
srb.SRB_Target = tid;
srb.SRB_Lun = lun;
srb.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
srb.SRB_SenseLen = SENSE_LEN;
srb.SRB_PostProc = hEventSRB;
srb.SRB_BufPointer = buf;
srb.SRB_BufLen = bufsize;
srb.SRB_CDBLen = 10;
srb.CDBByte[0] = SCSI_READ10;
srb.CDBByte[2] = (unsigned char) (frame>>24);
srb.CDBByte[3] = (unsigned char) (frame>>16);
srb.CDBByte[4] = (unsigned char) (frame>>8);
srb.CDBByte[5] = (unsigned char) (frame);
srb.CDBByte[7] = 0;
srb.CDBByte[8] = 1; /* read 1 frames */
ResetEvent(hEventSRB);
dwStatus = SendASPI32Command((SRB *)&srb);
if(dwStatus == SS_PENDING) {
WaitForSingleObject(hEventSRB, 100000);
}
CloseHandle(hEventSRB);
return (srb.SRB_TargStat == STATUS_GOOD);
}
int GetCDCapacity(unsigned int hid, unsigned int tid, unsigned int lun)
{
HANDLE hEventSRB;
SRB_ExecSCSICmd srb;
DWORD dwStatus;
unsigned char buf[8];
hEventSRB = CreateEvent(NULL, TRUE, FALSE, NULL);
memset(&buf, 0, sizeof(buf));
memset(&srb,0,sizeof(SRB_ExecSCSICmd));
srb.SRB_Cmd = SC_EXEC_SCSI_CMD;
srb.SRB_HaId = hid;
srb.SRB_Target = tid;
srb.SRB_Lun = lun;
srb.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
srb.SRB_SenseLen = SENSE_LEN;
srb.SRB_PostProc = hEventSRB;
srb.SRB_BufPointer = (unsigned char *)buf;
srb.SRB_BufLen = 8;
srb.SRB_CDBLen = 10;
srb.CDBByte[0] = SCSI_READCDCAP;
srb.CDBByte[2] = 0;
srb.CDBByte[3] = 0;
srb.CDBByte[4] = 0;
srb.CDBByte[5] = 0;
srb.CDBByte[8] = 0;
ResetEvent(hEventSRB);
dwStatus = SendASPI32Command((SRB *)&srb);
if(dwStatus == SS_PENDING) {
WaitForSingleObject(hEventSRB, 100000);
}
CloseHandle(hEventSRB);
return ((buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]) * ((buf[4] << 24) + (buf[5] << 16) + (buf[6] << 8) + buf[7]);
}
#endif
cdrom_interface::cdrom_interface(char *dev)
{
put("CD");
settype(CDLOG);
fd = -1; // File descriptor not yet allocated
if (dev == NULL) {
path = NULL;
} else {
path = strdup(dev);
}
using_file=0;
#ifdef WIN32
bUseASPI = FALSE;
osinfo.dwOSVersionInfoSize = sizeof(osinfo);
GetVersionEx(&osinfo);
isWindowsXP = (osinfo.dwMajorVersion >= 5) && (osinfo.dwMinorVersion >= 1);
#endif
}
void
cdrom_interface::init(void) {
BX_DEBUG(("Init $Id: cdrom.cc,v 1.91 2008/02/15 22:05:41 sshwarts Exp $"));
BX_INFO(("file = '%s'",path));
}
cdrom_interface::~cdrom_interface(void)
{
#ifdef WIN32
#else
if (fd >= 0)
close(fd);
#endif
if (path)
free(path);
BX_DEBUG(("Exit"));
}
bx_bool
cdrom_interface::insert_cdrom(char *dev)
{
unsigned char buffer[BX_CD_FRAMESIZE];
#ifndef WIN32
ssize_t ret;
#endif
// Load CD-ROM. Returns 0 if CD is not ready.
if (dev != NULL) path = strdup(dev);
BX_INFO (("load cdrom with path=%s", path));
#ifdef WIN32
char drive[256];
if ((path[1] == ':') && (strlen(path) == 2))
{
if(osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
// Use direct device access under windows NT/2k/XP
// With all the backslashes it's hard to see, but to open D: drive
// the name would be: \\.\d:
sprintf(drive, "\\\\.\\%s", path);
BX_INFO (("Using direct access for cdrom."));
// This trick only works for Win2k and WinNT, so warn the user of that.
} else {
BX_INFO(("Using ASPI for cdrom. Drive letters are unused yet."));
bUseASPI = TRUE;
}
using_file = 0;
}
else
{
strcpy(drive,path);
using_file = 1;
BX_INFO (("Opening image file as a cd"));
}
if(bUseASPI) {
DWORD d;
UINT cdr, cnt, max;
UINT i, j, k;
SRB_HAInquiry sh;
SRB_GDEVBlock sd;
if (!hASPI) {
hASPI = LoadLibrary("WNASPI32.DLL");
if (hASPI) {
SendASPI32Command = (DWORD(*)(LPSRB))GetProcAddress(hASPI, "SendASPI32Command");
GetASPI32DLLVersion = (DWORD(*)(void))GetProcAddress(hASPI, "GetASPI32DLLVersion");
GetASPI32SupportInfo = (DWORD(*)(void))GetProcAddress(hASPI, "GetASPI32SupportInfo");
d = GetASPI32DLLVersion();
BX_INFO(("WNASPI32.DLL version %d.%02d initialized", d & 0xff, (d >> 8) & 0xff));
} else {
BX_PANIC(("Could not load ASPI drivers, so cdrom access will fail"));
return 0;
}
}
cdr = 0;
bHaveDev = FALSE;
d = GetASPI32SupportInfo();
cnt = LOBYTE(LOWORD(d));
for(i = 0; i < cnt; i++) {
memset(&sh, 0, sizeof(sh));
sh.SRB_Cmd = SC_HA_INQUIRY;
sh.SRB_HaId = i;
SendASPI32Command((LPSRB)&sh);
if(sh.SRB_Status != SS_COMP)
continue;
max = (int)sh.HA_Unique[3];
for(j = 0; j < max; j++) {
for(k = 0; k < 8; k++) {
memset(&sd, 0, sizeof(sd));
sd.SRB_Cmd = SC_GET_DEV_TYPE;
sd.SRB_HaId = i;
sd.SRB_Target = j;
sd.SRB_Lun = k;
SendASPI32Command((LPSRB)&sd);
if(sd.SRB_Status == SS_COMP) {
if(sd.SRB_DeviceType == DTYPE_CDROM) {
cdr++;
if(cdr > cdromCount) {
hid = i;
tid = j;
lun = k;
cdromCount++;
bHaveDev = TRUE;
}
}
}
if(bHaveDev) break;
}
if(bHaveDev) break;
}
}
fd=1;
} else {
hFile=CreateFile((char *)&drive, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
if (hFile !=(void *)0xFFFFFFFF)
fd=1;
if (!using_file) {
DWORD lpBytesReturned;
DeviceIoControl(hFile, IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &lpBytesReturned, NULL);
}
}
#elif defined(__APPLE__)
if(strcmp(path, "drive") == 0)
{
mach_port_t masterPort = NULL;
io_iterator_t mediaIterator;
kern_return_t kernResult;
BX_INFO(("Insert CDROM"));
kernResult = FindEjectableCDMedia(&mediaIterator, &masterPort);
if (kernResult != KERN_SUCCESS) {
BX_INFO(("Unable to find CDROM"));
return 0;
}
kernResult = GetDeviceFilePath(mediaIterator, CDDevicePath, sizeof(CDDevicePath));
if (kernResult != KERN_SUCCESS) {
BX_INFO(("Unable to get CDROM device file path"));
return 0;
}
// Here a cdrom was found so see if we can read from it.
// At this point a failure will result in panic.
if (strlen(CDDevicePath)) {
fd = open(CDDevicePath, O_RDONLY);
}
}
else {
fd = open(path, O_RDONLY);
}
#else
// all platforms except win32
fd = open(path, O_RDONLY);
#endif
if (fd < 0) {
BX_ERROR(("open cd failed for %s: %s", path, strerror(errno)));
return 0;
}
#ifndef WIN32
// do fstat to determine if it's a file or a device, then set using_file.
struct stat stat_buf;
ret = fstat (fd, &stat_buf);
if (ret) {
BX_PANIC (("fstat cdrom file returned error: %s", strerror (errno)));
}
if (S_ISREG (stat_buf.st_mode)) {
using_file = 1;
BX_INFO (("Opening image file %s as a cd.", path));
} else {
using_file = 0;
BX_INFO (("Using direct access for cdrom."));
}
#endif
// I just see if I can read a sector to verify that a
// CD is in the drive and readable.
return read_block(buffer, 0, 2048);
}
bx_bool
cdrom_interface::start_cdrom()
{
// Spin up the cdrom drive.
if (fd >= 0) {
#if defined(__NetBSD__) || defined(__NetBSD_kernel__)
if (ioctl (fd, CDIOCSTART) < 0)
BX_DEBUG(("start_cdrom: start returns error: %s", strerror (errno)));
return 1;
#else
BX_INFO(("start_cdrom: your OS is not supported yet"));
return 0; // OS not supported yet, return 0 always
#endif
}
return 0;
}
void
cdrom_interface::eject_cdrom()
{
// Logically eject the CD. I suppose we could stick in
// some ioctl() calls to really eject the CD as well.
if (fd >= 0) {
#if (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
(void) ioctl (fd, CDIOCALLOW);
if (ioctl (fd, CDIOCEJECT) < 0)
BX_DEBUG(("eject_cdrom: eject returns error"));
#endif
#ifdef WIN32
if (using_file == 0)
{
if(bUseASPI) {
} else {
DWORD lpBytesReturned;
DeviceIoControl(hFile, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &lpBytesReturned, NULL);
}
}
#else // WIN32
#if __linux__
if (!using_file)
ioctl (fd, CDROMEJECT, NULL);
#endif
close(fd);
#endif // WIN32
fd = -1;
}
}
bx_bool
cdrom_interface::read_toc(Bit8u* buf, int* length, bx_bool msf, int start_track, int format)
{
unsigned i;
// Read CD TOC. Returns 0 if start track is out of bounds.
if (fd < 0) {
BX_PANIC(("cdrom: read_toc: file not open."));
return 0;
}
// This is a hack and works okay if there's one rom track only
#if defined(WIN32)
if (!isWindowsXP || using_file) {
#else
if (using_file || (format != 0)) {
#endif
Bit32u blocks;
int len = 4;
switch (format) {
case 0:
// From atapi specs : start track can be 0-63, AA
if ((start_track > 1) && (start_track != 0xaa))
return 0;
buf[2] = 1;
buf[3] = 1;
if (start_track <= 1) {
buf[len++] = 0; // Reserved
buf[len++] = 0x14; // ADR, control
buf[len++] = 1; // Track number
buf[len++] = 0; // Reserved
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = 0; // minute
buf[len++] = 2; // second
buf[len++] = 0; // frame
} else {
buf[len++] = 0;
buf[len++] = 0;
buf[len++] = 0;
buf[len++] = 0; // logical sector 0
}
}
// Lead out track
buf[len++] = 0; // Reserved
buf[len++] = 0x16; // ADR, control
buf[len++] = 0xaa; // Track number
buf[len++] = 0; // Reserved
blocks = capacity();
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = (Bit8u)(((blocks + 150) / 75) / 60); // minute
buf[len++] = (Bit8u)(((blocks + 150) / 75) % 60); // second
buf[len++] = (Bit8u)((blocks + 150) % 75); // frame;
} else {
buf[len++] = (blocks >> 24) & 0xff;
buf[len++] = (blocks >> 16) & 0xff;
buf[len++] = (blocks >> 8) & 0xff;
buf[len++] = (blocks >> 0) & 0xff;
}
buf[0] = ((len-2) >> 8) & 0xff;
buf[1] = (len-2) & 0xff;
break;
case 1:
// multi session stuff - emulate a single session only
buf[0] = 0;
buf[1] = 0x0a;
buf[2] = 1;
buf[3] = 1;
for (i = 0; i < 8; i++)
buf[4+i] = 0;
len = 12;
break;
case 2:
// raw toc - emulate a single session only (ported from qemu)
buf[2] = 1;
buf[3] = 1;
for (i = 0; i < 4; i++) {
buf[len++] = 1;
buf[len++] = 0x14;
buf[len++] = 0;
if (i < 3) {
buf[len++] = 0xa0 + i;
} else {
buf[len++] = 1;
}
buf[len++] = 0;
buf[len++] = 0;
buf[len++] = 0;
if (i < 2) {
buf[len++] = 0;
buf[len++] = 1;
buf[len++] = 0;
buf[len++] = 0;
} else if (i == 2) {
blocks = capacity();
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = (Bit8u)(((blocks + 150) / 75) / 60); // minute
buf[len++] = (Bit8u)(((blocks + 150) / 75) % 60); // second
buf[len++] = (Bit8u)((blocks + 150) % 75); // frame;
} else {
buf[len++] = (blocks >> 24) & 0xff;
buf[len++] = (blocks >> 16) & 0xff;
buf[len++] = (blocks >> 8) & 0xff;
buf[len++] = (blocks >> 0) & 0xff;
}
} else {
buf[len++] = 0;
buf[len++] = 0;
buf[len++] = 0;
buf[len++] = 0;
}
}
buf[0] = ((len-2) >> 8) & 0xff;
buf[1] = (len-2) & 0xff;
break;
default:
BX_PANIC(("cdrom: read_toc: unknown format"));
return 0;
}
*length = len;
return 1;
}
// all these implementations below are the platform-dependent code required
// to read the TOC from a physical cdrom.
#ifdef WIN32
if (isWindowsXP)
{
// This only works with WinXP
CDROM_READ_TOC_EX input;
memset(&input, 0, sizeof(input));
input.Format = format;
input.Msf = msf;
input.SessionTrack = start_track;
// We have to allocate a chunk of memory to make sure it is aligned on a sector base.
UCHAR *data = (UCHAR *) VirtualAlloc(NULL, 2048*2, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
unsigned long iBytesReturned;
DeviceIoControl(hFile, IOCTL_CDROM_READ_TOC_EX, &input, sizeof(input), data, 804, &iBytesReturned, NULL);
// now copy it to the users buffer and free our buffer
*length = data[1] + (data[0] << 8) + 2;
memcpy(buf, data, *length);
VirtualFree(data, 0, MEM_RELEASE);
return 1;
} else {
return 0;
}
#elif __linux__ || defined(__sun)
{
struct cdrom_tochdr tochdr;
if (ioctl(fd, CDROMREADTOCHDR, &tochdr))
BX_PANIC(("cdrom: read_toc: READTOCHDR failed."));
if ((start_track > tochdr.cdth_trk1) && (start_track != 0xaa))
return 0;
buf[2] = tochdr.cdth_trk0;
buf[3] = tochdr.cdth_trk1;
if (start_track < tochdr.cdth_trk0)
start_track = tochdr.cdth_trk0;
int len = 4;
for (int i = start_track; i <= tochdr.cdth_trk1; i++) {
struct cdrom_tocentry tocentry;
tocentry.cdte_format = (msf) ? CDROM_MSF : CDROM_LBA;
tocentry.cdte_track = i;
if (ioctl(fd, CDROMREADTOCENTRY, &tocentry))
BX_PANIC(("cdrom: read_toc: READTOCENTRY failed."));
buf[len++] = 0; // Reserved
buf[len++] = (tocentry.cdte_adr << 4) | tocentry.cdte_ctrl ; // ADR, control
buf[len++] = i; // Track number
buf[len++] = 0; // Reserved
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = tocentry.cdte_addr.msf.minute;
buf[len++] = tocentry.cdte_addr.msf.second;
buf[len++] = tocentry.cdte_addr.msf.frame;
} else {
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 24) & 0xff;
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 16) & 0xff;
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 8) & 0xff;
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 0) & 0xff;
}
}
// Lead out track
struct cdrom_tocentry tocentry;
tocentry.cdte_format = (msf) ? CDROM_MSF : CDROM_LBA;
#ifdef CDROM_LEADOUT
tocentry.cdte_track = CDROM_LEADOUT;
#else
tocentry.cdte_track = 0xaa;
#endif
if (ioctl(fd, CDROMREADTOCENTRY, &tocentry))
BX_PANIC(("cdrom: read_toc: READTOCENTRY lead-out failed."));
buf[len++] = 0; // Reserved
buf[len++] = (tocentry.cdte_adr << 4) | tocentry.cdte_ctrl ; // ADR, control
buf[len++] = 0xaa; // Track number
buf[len++] = 0; // Reserved
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = tocentry.cdte_addr.msf.minute;
buf[len++] = tocentry.cdte_addr.msf.second;
buf[len++] = tocentry.cdte_addr.msf.frame;
} else {
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 24) & 0xff;
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 16) & 0xff;
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 8) & 0xff;
buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 0) & 0xff;
}
buf[0] = ((len-2) >> 8) & 0xff;
buf[1] = (len-2) & 0xff;
*length = len;
return 1;
}
#elif (defined(__NetBSD__) || defined(__NetBSD_kernel__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
{
struct ioc_toc_header h;
struct ioc_read_toc_entry t;
if (ioctl (fd, CDIOREADTOCHEADER, &h) < 0)
BX_PANIC(("cdrom: read_toc: READTOCHDR failed."));
if ((start_track > h.ending_track) && (start_track != 0xaa))
return 0;
buf[2] = h.starting_track;
buf[3] = h.ending_track;
if (start_track < h.starting_track)
start_track = h.starting_track;
int len = 4;
for (int i = start_track; i <= h.ending_track; i++) {
struct cd_toc_entry tocentry;
t.address_format = (msf) ? CD_MSF_FORMAT : CD_LBA_FORMAT;
t.starting_track = i;
t.data_len = sizeof(tocentry);
t.data = &tocentry;
if (ioctl (fd, CDIOREADTOCENTRYS, &t) < 0)
BX_PANIC(("cdrom: read_toc: READTOCENTRY failed."));
buf[len++] = 0; // Reserved
buf[len++] = (tocentry.addr_type << 4) | tocentry.control ; // ADR, control
buf[len++] = i; // Track number
buf[len++] = 0; // Reserved
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = tocentry.addr.msf.minute;
buf[len++] = tocentry.addr.msf.second;
buf[len++] = tocentry.addr.msf.frame;
} else {
buf[len++] = (((unsigned)tocentry.addr.lba) >> 24) & 0xff;
buf[len++] = (((unsigned)tocentry.addr.lba) >> 16) & 0xff;
buf[len++] = (((unsigned)tocentry.addr.lba) >> 8) & 0xff;
buf[len++] = (((unsigned)tocentry.addr.lba) >> 0) & 0xff;
}
}
// Lead out track
struct cd_toc_entry tocentry;
t.address_format = (msf) ? CD_MSF_FORMAT : CD_LBA_FORMAT;
t.starting_track = 0xaa;
t.data_len = sizeof(tocentry);
t.data = &tocentry;
if (ioctl (fd, CDIOREADTOCENTRYS, &t) < 0)
BX_PANIC(("cdrom: read_toc: READTOCENTRY lead-out failed."));
buf[len++] = 0; // Reserved
buf[len++] = (tocentry.addr_type << 4) | tocentry.control ; // ADR, control
buf[len++] = 0xaa; // Track number
buf[len++] = 0; // Reserved
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = tocentry.addr.msf.minute;
buf[len++] = tocentry.addr.msf.second;
buf[len++] = tocentry.addr.msf.frame;
} else {
buf[len++] = (((unsigned)tocentry.addr.lba) >> 24) & 0xff;
buf[len++] = (((unsigned)tocentry.addr.lba) >> 16) & 0xff;
buf[len++] = (((unsigned)tocentry.addr.lba) >> 8) & 0xff;
buf[len++] = (((unsigned)tocentry.addr.lba) >> 0) & 0xff;
}
buf[0] = ((len-2) >> 8) & 0xff;
buf[1] = (len-2) & 0xff;
*length = len;
return 1;
}
#elif defined(__APPLE__)
// Read CD TOC. Returns 0 if start track is out of bounds.
#if 1
{
struct _CDTOC *toc = ReadTOC(CDDevicePath);
if ((start_track > toc->last_session) && (start_track != 0xaa))
return 0;
buf[2] = toc->first_session;
buf[3] = toc->last_session;
if (start_track < toc->first_session)
start_track = toc->first_session;
int len = 4;
for (int i = start_track; i <= toc->last_session; i++) {
buf[len++] = 0; // Reserved
buf[len++] = toc->trackdesc[i].ctrl_adr ; // ADR, control
buf[len++] = i; // Track number
buf[len++] = 0; // Reserved
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = toc->trackdesc[i].address.minute;
buf[len++] = toc->trackdesc[i].address.second;
buf[len++] = toc->trackdesc[i].address.frame;
} else {
unsigned lba = (unsigned)(MSF_TO_LBA(toc->trackdesc[i].address));
buf[len++] = (lba >> 24) & 0xff;
buf[len++] = (lba >> 16) & 0xff;
buf[len++] = (lba >> 8) & 0xff;
buf[len++] = (lba >> 0) & 0xff;
}
}
// Lead out track
buf[len++] = 0; // Reserved
buf[len++] = 0x16; // ADR, control
buf[len++] = 0xaa; // Track number
buf[len++] = 0; // Reserved
Bit32u blocks = capacity();
// Start address
if (msf) {
buf[len++] = 0; // reserved
buf[len++] = (Bit8u)(((blocks + 150) / 75) / 60); // minute
buf[len++] = (Bit8u)(((blocks + 150) / 75) % 60); // second
buf[len++] = (Bit8u)((blocks + 150) % 75); // frame;
} else {
buf[len++] = (blocks >> 24) & 0xff;
buf[len++] = (blocks >> 16) & 0xff;
buf[len++] = (blocks >> 8) & 0xff;
buf[len++] = (blocks >> 0) & 0xff;
}
buf[0] = ((len-2) >> 8) & 0xff;
buf[1] = (len-2) & 0xff;
*length = len;
return 1;
}
#else
BX_INFO(("Read TOC - Not Implemented"));
return 0;
#endif
#else
BX_INFO(("read_toc: your OS is not supported yet"));
return 0; // OS not supported yet, return 0 always.
#endif
}
Bit32u cdrom_interface::capacity()
{
// Return CD-ROM capacity. I believe you want to return
// the number of blocks of capacity the actual media has.
#if !defined WIN32
// win32 has its own way of doing this
if (using_file) {
// return length of the image file
struct stat stat_buf;
int ret = fstat (fd, &stat_buf);
if (ret) {
BX_PANIC (("fstat on cdrom image returned err: %s", strerror(errno)));
}
if ((stat_buf.st_size % 2048) != 0) {
BX_ERROR (("expected cdrom image to be a multiple of 2048 bytes"));
}
return (stat_buf.st_size / 2048);
}
#endif
#ifdef __BEOS__
return GetNumDeviceBlocks(fd, BX_CD_FRAMESIZE);
#elif defined(__sun)
{
struct stat buf = {0};
if (fd < 0) {
BX_PANIC(("cdrom: capacity: file not open."));
}
if(fstat(fd, &buf) != 0)
BX_PANIC(("cdrom: capacity: stat() failed."));
return(buf.st_size);
}
#elif (defined(__NetBSD__) || defined(__NetBSD_kernel__) || defined(__OpenBSD__))
{
// We just read the disklabel, imagine that...
struct disklabel lp;
if (fd < 0)
BX_PANIC(("cdrom: capacity: file not open."));
if (ioctl(fd, DIOCGDINFO, &lp) < 0)
BX_PANIC(("cdrom: ioctl(DIOCGDINFO) failed"));
BX_DEBUG(("capacity: %u", lp.d_secperunit));
return(lp.d_secperunit);
}
#elif defined(__linux__)
{
// Read the TOC to get the data size, since BLKGETSIZE doesn't work on
// non-ATAPI drives. This is based on Keith Jones code below.
// <splite@purdue.edu> 21 June 2001
int i, dtrk_lba, num_sectors;
int dtrk = 0;
struct cdrom_tochdr td;
struct cdrom_tocentry te;
if (fd < 0)
BX_PANIC(("cdrom: capacity: file not open."));
if (ioctl(fd, CDROMREADTOCHDR, &td) < 0)
BX_PANIC(("cdrom: ioctl(CDROMREADTOCHDR) failed"));
num_sectors = -1;
dtrk_lba = -1;
for (i = td.cdth_trk0; i <= td.cdth_trk1; i++) {
te.cdte_track = i;
te.cdte_format = CDROM_LBA;
if (ioctl(fd, CDROMREADTOCENTRY, &te) < 0)
BX_PANIC(("cdrom: ioctl(CDROMREADTOCENTRY) failed"));
if (dtrk_lba != -1) {
num_sectors = te.cdte_addr.lba - dtrk_lba;
break;
}
if (te.cdte_ctrl & CDROM_DATA_TRACK) {
dtrk = i;
dtrk_lba = te.cdte_addr.lba;
}
}
if (num_sectors < 0) {
if (dtrk_lba != -1) {
te.cdte_track = CDROM_LEADOUT;
te.cdte_format = CDROM_LBA;
if (ioctl(fd, CDROMREADTOCENTRY, &te) < 0)
BX_PANIC(("cdrom: ioctl(CDROMREADTOCENTRY) failed"));
num_sectors = te.cdte_addr.lba - dtrk_lba;
} else
BX_PANIC(("cdrom: no data track found"));
}
BX_INFO(("cdrom: Data track %d, length %d", dtrk, num_sectors));
return(num_sectors);
}
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
{
// Read the TOC to get the size of the data track.
// Keith Jones <freebsd.dev@blueyonder.co.uk>, 16 January 2000
#define MAX_TRACKS 100
int i, num_tracks, num_sectors;
struct ioc_toc_header td;
struct ioc_read_toc_entry rte;
struct cd_toc_entry toc_buffer[MAX_TRACKS + 1];
if (fd < 0)
BX_PANIC(("cdrom: capacity: file not open."));
if (ioctl(fd, CDIOREADTOCHEADER, &td) < 0)
BX_PANIC(("cdrom: ioctl(CDIOREADTOCHEADER) failed"));
num_tracks = (td.ending_track - td.starting_track) + 1;
if (num_tracks > MAX_TRACKS)
BX_PANIC(("cdrom: TOC is too large"));
rte.address_format = CD_LBA_FORMAT;
rte.starting_track = td.starting_track;
rte.data_len = (num_tracks + 1) * sizeof(struct cd_toc_entry);
rte.data = toc_buffer;
if (ioctl(fd, CDIOREADTOCENTRYS, &rte) < 0)
BX_PANIC(("cdrom: ioctl(CDIOREADTOCENTRYS) failed"));
num_sectors = -1;
for (i = 0; i < num_tracks; i++) {
if (rte.data[i].control & 4) { /* data track */
num_sectors = ntohl(rte.data[i + 1].addr.lba)
- ntohl(rte.data[i].addr.lba);
BX_INFO(("cdrom: Data track %d, length %d",
rte.data[i].track, num_sectors));
break;
}
}
if (num_sectors < 0)
BX_PANIC(("cdrom: no data track found"));
return(num_sectors);
}
#elif defined WIN32
{
if (bUseASPI) {
return ((GetCDCapacity(hid, tid, lun) / 2352) + 1);
} else if (using_file) {
ULARGE_INTEGER FileSize;
FileSize.LowPart = GetFileSize(hFile, &FileSize.HighPart);
return (Bit32u)(FileSize.QuadPart / 2048);
} else { /* direct device access */
if (isWindowsXP) {
LARGE_INTEGER length;
DWORD iBytesReturned;
DeviceIoControl(hFile, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &length, sizeof(length), &iBytesReturned, NULL);
return (Bit32u)(length.QuadPart / 2048);
} else {
ULARGE_INTEGER FreeBytesForCaller;
ULARGE_INTEGER TotalNumOfBytes;
ULARGE_INTEGER TotalFreeBytes;
GetDiskFreeSpaceEx(path, &FreeBytesForCaller, &TotalNumOfBytes, &TotalFreeBytes);
return (Bit32u)(TotalNumOfBytes.QuadPart / 2048);
}
}
}
#elif defined __APPLE__
// Find the size of the first data track on the cd. This has produced
// the same results as the linux version on every cd I have tried, about
// 5. The differences here seem to be that the entries in the TOC when
// retrieved from the IOKit interface appear in a reversed order when
// compared with the linux READTOCENTRY ioctl.
{
// Return CD-ROM capacity. I believe you want to return
// the number of bytes of capacity the actual media has.
BX_INFO(("Capacity"));
struct _CDTOC *toc = ReadTOC(CDDevicePath);
if (toc == NULL) {
BX_PANIC(("capacity: Failed to read toc"));
}
size_t toc_entries = (toc->length - 2) / sizeof(struct _CDTOC_Desc);
BX_DEBUG(("reading %d toc entries\n", toc_entries));
int start_sector = -1;
int data_track = -1;
// Iterate through the list backward. Pick the first data track and
// get the address of the immediately previous (or following depending
// on how you look at it). The difference in the sector numbers
// is returned as the sized of the data track.
for (int i=toc_entries - 1; i>=0; i--) {
BX_DEBUG(("session %d ctl_adr %d tno %d point %d lba %d z %d p lba %d\n",
(int)toc->trackdesc[i].session,
(int)toc->trackdesc[i].ctrl_adr,
(int)toc->trackdesc[i].tno,
(int)toc->trackdesc[i].point,
MSF_TO_LBA(toc->trackdesc[i].address),
(int)toc->trackdesc[i].zero,
MSF_TO_LBA(toc->trackdesc[i].p)));
if (start_sector != -1) {
start_sector = MSF_TO_LBA(toc->trackdesc[i].p) - start_sector;
break;
}
if ((toc->trackdesc[i].ctrl_adr >> 4) != 1) continue;
if (toc->trackdesc[i].ctrl_adr & 0x04) {
data_track = toc->trackdesc[i].point;
start_sector = MSF_TO_LBA(toc->trackdesc[i].p);
}
}
free(toc);
if (start_sector == -1) {
start_sector = 0;
}
BX_INFO(("first data track %d data size is %d", data_track, start_sector));
return start_sector;
}
#else
BX_ERROR(("capacity: your OS is not supported yet"));
return(0);
#endif
}
bx_bool BX_CPP_AttrRegparmN(3)
cdrom_interface::read_block(Bit8u* buf, int lba, int blocksize)
{
// Read a single block from the CD
#ifdef WIN32
LARGE_INTEGER pos;
#else
off_t pos;
#endif
ssize_t n = 0;
Bit8u try_count = 3;
Bit8u* buf1;
if (blocksize == 2352) {
memset(buf, 0, 2352);
memset(buf+1, 0xff, 10);
int raw_block = lba + 150;
buf[12] = (raw_block / 75) / 60;
buf[13] = (raw_block / 75) % 60;
buf[14] = (raw_block % 75);
buf[15] = 0x01;
buf1 = buf + 16;
} else {
buf1 = buf;
}
do {
#ifdef WIN32
if(bUseASPI) {
ReadCDSector(hid, tid, lun, lba, buf1, BX_CD_FRAMESIZE);
n = BX_CD_FRAMESIZE;
} else {
pos.QuadPart = (LONGLONG)lba*BX_CD_FRAMESIZE;
pos.LowPart = SetFilePointer(hFile, pos.LowPart, &pos.HighPart, SEEK_SET);
if ((pos.LowPart == 0xffffffff) && (GetLastError() != NO_ERROR)) {
BX_PANIC(("cdrom: read_block: SetFilePointer returned error."));
} else {
ReadFile(hFile, (void *) buf1, BX_CD_FRAMESIZE, (unsigned long *) &n, NULL);
}
}
#elif defined(__APPLE__)
#define CD_SEEK_DISTANCE kCDSectorSizeWhole
if(using_file)
{
pos = lseek(fd, lba*BX_CD_FRAMESIZE, SEEK_SET);
if (pos < 0) {
BX_PANIC(("cdrom: read_block: lseek returned error."));
} else {
n = read(fd, buf1, BX_CD_FRAMESIZE);
}
}
else
{
// This seek will leave us 16 bytes from the start of the data
// hence the magic number.
pos = lseek(fd, lba*CD_SEEK_DISTANCE + 16, SEEK_SET);
if (pos < 0) {
BX_PANIC(("cdrom: read_block: lseek returned error."));
} else {
n = read(fd, buf1, CD_FRAMESIZE);
}
}
#else
pos = lseek(fd, lba*BX_CD_FRAMESIZE, SEEK_SET);
if (pos < 0) {
BX_PANIC(("cdrom: read_block: lseek returned error."));
} else {
n = read(fd, (char*) buf1, BX_CD_FRAMESIZE);
}
#endif
} while ((n != BX_CD_FRAMESIZE) && (--try_count > 0));
return (n == BX_CD_FRAMESIZE);
}
void cdrom_interface::seek(int lba)
{
unsigned char buffer[BX_CD_FRAMESIZE];
read_block(buffer, lba, BX_CD_FRAMESIZE);
}
#endif /* if BX_SUPPORT_CDROM */
#endif
| 28.745774
| 136
| 0.607809
|
bavison
|
88186ab5216e70a07cd9ba1bf0f18b94e9fc1707
| 6,854
|
cpp
|
C++
|
common/state/StateUtils.cpp
|
sambacha/private-data-objects
|
635049918b362ba81ad74469cbea6b2c53380d9e
|
[
"Apache-2.0"
] | 84
|
2018-05-04T15:07:53.000Z
|
2022-03-23T09:38:17.000Z
|
common/state/StateUtils.cpp
|
sambacha/private-data-objects
|
635049918b362ba81ad74469cbea6b2c53380d9e
|
[
"Apache-2.0"
] | 218
|
2018-05-07T20:10:25.000Z
|
2022-03-23T17:27:44.000Z
|
common/state/StateUtils.cpp
|
sambacha/private-data-objects
|
635049918b362ba81ad74469cbea6b2c53380d9e
|
[
"Apache-2.0"
] | 33
|
2018-03-02T20:32:18.000Z
|
2021-09-17T07:07:57.000Z
|
/* Copyright 2018, 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "parson.h"
#include "state.h"
namespace pstate = pdo::state;
pstate::StateBlockId& pdo::state::StateNode::GetBlockId()
{
return blockId_;
}
pstate::StateBlock& pdo::state::StateNode::GetBlock()
{
return stateBlock_;
}
void pdo::state::StateNode::AppendChild(StateNode& childNode)
{
try
{
ChildrenArray_.push_back(childNode.GetBlockId());
}
catch (const std::exception& e)
{
SAFE_LOG_EXCEPTION("StateNode::AppendChild, push_back error, out of memory");
throw;
}
childNode.SetHasParent();
}
void pdo::state::StateNode::AppendChildId(StateBlockId& childId)
{
try
{
ChildrenArray_.push_back(childId);
}
catch (const std::exception& e)
{
SAFE_LOG_EXCEPTION("StateNode::AppendChildId, push_back error, out of memory");
throw;
}
}
void pdo::state::StateNode::SetHasParent()
{
hasParent_ = true;
}
void pdo::state::StateNode::BlockifyChildren(const ByteArray& state_encryption_key)
{
try
{
// create the master block from scratch
stateBlock_.clear();
// insert a JSON blob containing the BlockIds array
JsonValue j_root_block_value(json_value_init_object());
pdo::error::ThrowIf<pdo::error::RuntimeError>(
!j_root_block_value.value, "Failed to create json root block value");
JSON_Object* j_root_block_object = json_value_get_object(j_root_block_value);
pdo::error::ThrowIfNull(
j_root_block_object, "Failed on retrieval of json root block object value");
JSON_Status jret;
jret = json_object_set_value(j_root_block_object, "BlockIds", json_value_init_array());
pdo::error::ThrowIf<pdo::error::RuntimeError>(
jret != JSONSuccess, "failed to serialize block ids");
JSON_Array* j_block_ids_array = json_object_get_array(j_root_block_object, "BlockIds");
pdo::error::ThrowIfNull(j_block_ids_array, "failed to serialize the block id array");
ByteArray cumulative_block_ids_hash;
// insert in the array the IDs of all blocks in the list
for (unsigned int i = 0; i < ChildrenArray_.size(); i++)
{
cumulative_block_ids_hash.insert(cumulative_block_ids_hash.end(),
ChildrenArray_[i].begin(), ChildrenArray_[i].end());
cumulative_block_ids_hash = pdo::crypto::ComputeMessageHash(cumulative_block_ids_hash);
jret = json_array_append_string(
j_block_ids_array, ByteArrayToBase64EncodedString(ChildrenArray_[i]).c_str());
}
//remove children blocks (reduce memory consumption)
ChildrenArray_.resize(0);
ChildrenArray_.shrink_to_fit();
//serialize authenticator
ByteArray block_ids_hmac = pdo::crypto::ComputeMessageHMAC(state_encryption_key, cumulative_block_ids_hash);
jret = json_object_dotset_string(j_root_block_object,
"BlockIdsAuth", ByteArrayToBase64EncodedString(block_ids_hmac).c_str());
pdo::error::ThrowIf<pdo::error::RuntimeError>(
jret != JSONSuccess, "failed to serialize the block-ids authenticator");
//serialized json blob
size_t serializedSize = json_serialization_size(j_root_block_value);
try
{
stateBlock_.resize(serializedSize);
}
catch (const std::exception& e)
{
SAFE_LOG_EXCEPTION("unable to resize root git statblock for json blob");
throw;
}
jret = json_serialize_to_buffer(
j_root_block_value, reinterpret_cast<char*>(stateBlock_.data()), stateBlock_.size());
pdo::error::ThrowIf<pdo::error::RuntimeError>(
jret != JSONSuccess, "json root block serialization failed");
}
catch (const std::exception& e)
{
SAFE_LOG_EXCEPTION("BlockifyChildren");
throw;
}
}
void pdo::state::StateNode::UnBlockifyChildren(const ByteArray& state_encryption_key)
{
if (stateBlock_.empty())
{
std::string msg("Can't unblockify state node, block is empty");
throw pdo::error::ValueError(msg);
}
JsonValue j_root_block_value(json_parse_string(ByteArrayToString(stateBlock_).c_str()));
pdo::error::ThrowIf<pdo::error::RuntimeError>(
!j_root_block_value.value, "Failed to parse json root block value");
JSON_Object* j_root_block_object = json_value_get_object(j_root_block_value);
pdo::error::ThrowIfNull(
j_root_block_object, "Failed on retrieval of json root block object value");
JSON_Array* j_block_ids_array = json_object_get_array(j_root_block_object, "BlockIds");
pdo::error::ThrowIfNull(j_block_ids_array, "Failed to parse the block ids, expecting array");
int block_ids_count = json_array_get_count(j_block_ids_array);
ByteArray cumulative_block_ids_hash;
for (int i = 0; i < block_ids_count; i++)
{
try
{
ChildrenArray_.push_back(StateBlockId(
Base64EncodedStringToByteArray(json_array_get_string(j_block_ids_array, i))));
}
catch (const std::exception& e)
{
SAFE_LOG_EXCEPTION("error allocating children in state node");
throw;
}
cumulative_block_ids_hash.insert(
cumulative_block_ids_hash.end(), ChildrenArray_[i].begin(), ChildrenArray_[i].end());
cumulative_block_ids_hash = pdo::crypto::ComputeMessageHash(cumulative_block_ids_hash);
}
//deserialize authenticator
const char *b64_auth = json_object_dotget_string(j_root_block_object, "BlockIdsAuth");
pdo::error::ThrowIfNull(b64_auth, "Failed to get BlockIdsAuth");
// verify authenticator
ByteArray expected_block_ids_hmac(Base64EncodedStringToByteArray(Base64EncodedString(b64_auth)));
ByteArray block_ids_hmac = pdo::crypto::ComputeMessageHMAC(state_encryption_key, cumulative_block_ids_hash);
pdo::error::ThrowIf<pdo::error::RuntimeError>(
expected_block_ids_hmac != block_ids_hmac, "invalid block-ids authenticator");
}
pstate::StateBlockIdArray pdo::state::StateNode::GetChildrenBlocks()
{
return ChildrenArray_;
}
void pdo::state::StateNode::ClearChildren()
{
ChildrenArray_.clear();
}
| 36.849462
| 116
| 0.688503
|
sambacha
|
88188a5e0d124303c5bd9fef3d117e60e38af905
| 392
|
cc
|
C++
|
src/gdb/gdb-7.11/gdb/testsuite/gdb.linespec/base/two/thefile.cc
|
aps337/unum-sdk
|
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
|
[
"Apache-2.0"
] | 31
|
2018-08-01T21:25:24.000Z
|
2022-02-14T07:52:34.000Z
|
src/gdb/gdb-7.11/gdb/testsuite/gdb.linespec/base/two/thefile.cc
|
aps337/unum-sdk
|
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
|
[
"Apache-2.0"
] | 40
|
2018-12-03T19:48:52.000Z
|
2021-03-10T06:34:26.000Z
|
src/gdb/gdb-7.11/gdb/testsuite/gdb.linespec/base/two/thefile.cc
|
aps337/unum-sdk
|
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
|
[
"Apache-2.0"
] | 20
|
2018-11-16T21:19:22.000Z
|
2021-10-18T23:08:24.000Z
|
/* The commented line must have the same line number in the other
"thefile.c". */
#define WANT_F2
#include "../../lspec.h"
static int dupname(int y)
{
label: return y;
}
static int twodup ()
{
return 0;
}
int n(int y)
{
int v = dupname(y) - 23; /* thefile breakpoint */
return v + twodup (); /* after dupname */
}
int NameSpace::overload(double x)
{
return (int) x - 23;
}
| 14.518519
| 65
| 0.617347
|
aps337
|
8818cfcc689f073b42bba15806349f2a6b9723ae
| 3,594
|
cpp
|
C++
|
main.cpp
|
rogii-com/SceneSample
|
df414805899a4ef7e76d62840c2173934bcc6dd6
|
[
"MIT"
] | 3
|
2019-12-23T12:36:18.000Z
|
2021-07-24T09:16:13.000Z
|
main.cpp
|
rogii-com/SceneSample
|
df414805899a4ef7e76d62840c2173934bcc6dd6
|
[
"MIT"
] | null | null | null |
main.cpp
|
rogii-com/SceneSample
|
df414805899a4ef7e76d62840c2173934bcc6dd6
|
[
"MIT"
] | 4
|
2019-12-23T11:35:21.000Z
|
2020-01-09T17:04:46.000Z
|
#include <QApplication>
#include <QQuickView>
#include <QQmlEngine>
#include "Scene.hpp"
#include "LogTrackSceneCameraManipulator.hpp"
#include "LineStrip.hpp"
class Helper : public QObject
{
Q_OBJECT
public:
enum Direction
{
Horizontal = 0x1,
Vertical = 0x2
};
Q_DECLARE_FLAGS(Directions, Direction)
public:
Helper(rogii::qt_quick::Scene * scene)
: QObject(scene)
, mScene(scene)
, mFlags(Directions().setFlag(Horizontal).setFlag(Vertical))
{
}
Directions & getFlags()
{
return mFlags;
}
public Q_SLOTS:
void onShift(double dx, double dy)
{
rogii::qt_quick::LogTrackSceneCameraManipulator m(mScene->getSceneCamera());
const double trueDx = (mFlags.testFlag(Horizontal) ? dx : 0);
const double trueDy = (mFlags.testFlag(Vertical) ? dy : 0);
m.shift(trueDx, trueDy);
}
void onZoom(double step, QPointF pivot)
{
rogii::qt_quick::LogTrackSceneCameraManipulator m(mScene->getSceneCamera());
const double trueX = (mFlags.testFlag(Horizontal) ? pivot.x() : 0);
const double trueY = (mFlags.testFlag(Vertical) ? pivot.y() : 0);
m.zoom(step, QPoint(trueX, trueY));
}
private:
rogii::qt_quick::Scene * mScene;
Directions mFlags;
};
int main(int argc, char * argv[])
{
QApplication::setAttribute(Qt::AA_UseOpenGLES);
QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
QApplication app(argc, argv);
qmlRegisterType<rogii::qt_quick::Scene>("ROGII.QtQuick", 1, 0, "Scene");
qmlRegisterType<LineStrip>("ROGII.QtQuick", 1, 0, "LineStrip");
QQuickView view;
view.engine()->addImportPath(QCoreApplication::applicationDirPath() + QStringLiteral("/qml"));
view.resize(800, 400);
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:///SceneSample/main.qml"));
view.show();
{
auto * scene1 = view.rootObject()->findChild<rogii::qt_quick::Scene *>(QLatin1String("scene1"));
auto * shiftArea = scene1->findChild<QQuickItem *>(QLatin1String("sceneMouseArea"));
auto * h = new Helper(scene1);
QObject::connect(shiftArea, SIGNAL(shift(double, double)),
h, SLOT(onShift(double, double)));
QObject::connect(shiftArea, SIGNAL(zoom(double, QPointF)),
h, SLOT(onZoom(double, QPointF)));
h->getFlags().setFlag(Helper::Horizontal, false);
}
{
auto * scene = view.rootObject()->findChild<rogii::qt_quick::Scene *>(QLatin1String("scene2"));
auto * shiftArea = scene->findChild<QQuickItem *>(QLatin1String("sceneMouseArea"));
auto * h = new Helper(scene);
QObject::connect(shiftArea, SIGNAL(shift(double, double)),
h, SLOT(onShift(double, double)));
QObject::connect(shiftArea, SIGNAL(zoom(double, QPointF)),
h, SLOT(onZoom(double, QPointF)));
h->getFlags().setFlag(Helper::Vertical, false);
}
{
auto * scene = view.rootObject()->findChild<rogii::qt_quick::Scene *>(QLatin1String("scene3"));
auto * shiftArea = scene->findChild<QQuickItem *>(QLatin1String("sceneMouseArea"));
auto * h = new Helper(scene);
QObject::connect(shiftArea, SIGNAL(shift(double, double)),
h, SLOT(onShift(double, double)));
QObject::connect(shiftArea, SIGNAL(zoom(double, QPointF)),
h, SLOT(onZoom(double, QPointF)));
}
return app.exec();
}
#include "main.moc"
| 31.526316
| 104
| 0.625765
|
rogii-com
|
881a60b3575d9e22c077bfd2cbb6b5d55ce32ad5
| 3,509
|
cxx
|
C++
|
Base/QTGUI/qSlicerCommandOptions.cxx
|
TheInterventionCentre/NorMIT-Plan-App
|
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
|
[
"MIT"
] | null | null | null |
Base/QTGUI/qSlicerCommandOptions.cxx
|
TheInterventionCentre/NorMIT-Plan-App
|
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
|
[
"MIT"
] | null | null | null |
Base/QTGUI/qSlicerCommandOptions.cxx
|
TheInterventionCentre/NorMIT-Plan-App
|
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
|
[
"MIT"
] | null | null | null |
/*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
#include "qSlicerCommandOptions.h"
#include "qSlicerCoreApplication.h"
// Slicer includes
//-----------------------------------------------------------------------------
// qSlicerCommandOptions methods
//-----------------------------------------------------------------------------
qSlicerCommandOptions::qSlicerCommandOptions():Superclass()
{
}
//-----------------------------------------------------------------------------
bool qSlicerCommandOptions::disableToolTips()const
{
return this->parsedArgs().value("disable-tooltips").toBool();
}
//-----------------------------------------------------------------------------
bool qSlicerCommandOptions::noSplash() const
{
return this->parsedArgs().value("no-splash").toBool();
}
//-----------------------------------------------------------------------------
bool qSlicerCommandOptions::noMainWindow() const
{
return this->parsedArgs().value("no-main-window").toBool();
}
//-----------------------------------------------------------------------------
bool qSlicerCommandOptions::showPythonInteractor() const
{
return this->parsedArgs().value("show-python-interactor").toBool();
}
//-----------------------------------------------------------------------------
bool qSlicerCommandOptions::enableQtTesting()const
{
#ifdef Slicer_USE_QtTesting
return this->parsedArgs().value("qt-testing").toBool();
#else
return false;
#endif
}
//-----------------------------------------------------------------------------
bool qSlicerCommandOptions::exitAfterStartup()const
{
return this->parsedArgs().value("exit-after-startup").toBool();
}
//-----------------------------------------------------------------------------
void qSlicerCommandOptions::addArguments()
{
this->Superclass::addArguments();
this->addArgument("disable-tooltips", "", QVariant::Bool,
"Disable toolstips in the user interface.");
this->addArgument("no-splash", "", QVariant::Bool,
"Disable the startup splash screen.");
this->addArgument("no-main-window", "", QVariant::Bool,
"Disable display of the main slicer window. Use with --python-script for alternate interface");
#ifdef Slicer_USE_PYTHONQT
if (!qSlicerCoreApplication::testAttribute(qSlicerCoreApplication::AA_DisablePython))
{
this->addArgument("show-python-interactor", "", QVariant::Bool,
"Show Python interactor at startup.");
}
#endif
#ifdef Slicer_USE_QtTesting
this->addArgument("qt-testing", "", QVariant::Bool,
"Enable QtTesting in the user interface");
#endif
this->addArgument("exit-after-startup", "", QVariant::Bool,
"Exit after startup is complete. Useful for measuring startup time");
}
| 33.740385
| 116
| 0.538615
|
TheInterventionCentre
|
881ac0e526f8969eddcaee9b751e246cf780bcca
| 3,383
|
cpp
|
C++
|
modules/cimg/tests/unittests/savetobuffer-test.cpp
|
alexanderbock/inviwo
|
5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c
|
[
"BSD-2-Clause"
] | 349
|
2015-01-30T09:21:52.000Z
|
2022-03-25T03:10:02.000Z
|
modules/cimg/tests/unittests/savetobuffer-test.cpp
|
alexanderbock/inviwo
|
5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c
|
[
"BSD-2-Clause"
] | 641
|
2015-09-23T08:54:06.000Z
|
2022-03-23T09:50:55.000Z
|
modules/cimg/tests/unittests/savetobuffer-test.cpp
|
alexanderbock/inviwo
|
5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c
|
[
"BSD-2-Clause"
] | 124
|
2015-02-27T23:45:02.000Z
|
2022-02-21T09:37:14.000Z
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>
#ifdef WIN32
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/exception.h>
#include <inviwo/core/io/tempfilehandle.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/cimg/cimgutils.h>
#include <modules/cimg/cimglayerreader.h>
#include <fstream>
#include <array>
#include <cstdio>
#include <algorithm>
namespace inviwo {
TEST(CImgUtils, cimgToBuffer) {
// load source image
std::string testExtension = "bmp";
const auto filename = filesystem::getPath(PathType::Tests, "/images/swirl." + testExtension);
CImgLayerReader reader;
auto layer = reader.readData(filename);
// write layer to a temporary file
util::TempFileHandle tmpFile("cimg", std::string(".") + testExtension);
cimgutil::saveLayer(tmpFile.getFileName(), layer.get());
// read file contents
std::vector<unsigned char> fileContents;
auto in = filesystem::ifstream(tmpFile.getFileName(), std::ios::binary);
if (in.is_open()) {
in.seekg(0, in.end);
size_t fileLen = in.tellg();
in.seekg(0, in.beg);
fileContents.resize(fileLen);
in.read(reinterpret_cast<char*>(fileContents.data()), fileLen);
in.close();
}
// write layer to buffer
auto imgBuffer = cimgutil::saveLayerToBuffer(testExtension, layer.get());
ASSERT_TRUE(imgBuffer != nullptr) << "buffer is empty";
// compare buffer and file contents
ASSERT_TRUE(fileContents.size() == imgBuffer->size()) << "buffer and file size does not match";
EXPECT_EQ(*imgBuffer.get(), fileContents) << "buffer and file contents do not match";
}
} // namespace inviwo
| 36.376344
| 99
| 0.691398
|
alexanderbock
|
881afe4df63cbad01e892ec69a5829f625bbdc71
| 5,329
|
cpp
|
C++
|
components/eam/src/physics/crm/samxx/shear_prod2D.cpp
|
katsmith133/E3SM
|
996c7e7aa3150822b81b0e34c427b820c74268a2
|
[
"BSD-3-Clause"
] | null | null | null |
components/eam/src/physics/crm/samxx/shear_prod2D.cpp
|
katsmith133/E3SM
|
996c7e7aa3150822b81b0e34c427b820c74268a2
|
[
"BSD-3-Clause"
] | null | null | null |
components/eam/src/physics/crm/samxx/shear_prod2D.cpp
|
katsmith133/E3SM
|
996c7e7aa3150822b81b0e34c427b820c74268a2
|
[
"BSD-3-Clause"
] | null | null | null |
#include "shear_prod2D.h"
void shear_prod2D(real4d &def2) {
YAKL_SCOPE( dx , :: dx );
YAKL_SCOPE( dz , :: dz );
YAKL_SCOPE( adz , :: adz );
YAKL_SCOPE( adzw , :: adzw );
YAKL_SCOPE( u , :: u );
YAKL_SCOPE( v , :: v );
YAKL_SCOPE( w , :: w );
YAKL_SCOPE( u0 , :: u0 );
YAKL_SCOPE( v0 , :: v0 );
YAKL_SCOPE( ncrms , :: ncrms );
// for (int k=0; k<nzm; k++) {
// for (int i=0; i<nx; i++) {
// for (int icrm=0; icrm<ncrms; icrm++) {
parallel_for( SimpleBounds<3>(nzm,nx,ncrms) , YAKL_LAMBDA (int k, int i, int icrm) {
real rdx0 = 1.0/dx;
int j = 0;
int kb, kc, ib, ic;
real rdz, rdzw_up, rdzw_dn, rdx, rdx_up, rdx_dn;
if (k>=1 && k <= nzm-2) {
kb = k-1;
kc = k+1;
rdz = 1.0/(dz(icrm)*adz(k,icrm));
rdzw_up = 1.0/(dz(icrm)*adzw(kc,icrm));
rdzw_dn = 1.0/(dz(icrm)*adzw(k,icrm));
rdx = rdx0*sqrt(dx*rdz);
rdx_up = rdx0 *sqrt(dx*rdzw_up);
rdx_dn = rdx0 *sqrt(dx*rdzw_dn);
ib = i-1;
ic = i+1;
real tmp1 = ((u(k,j+offy_u,ic+offx_u,icrm)-u(k,j+offy_u,i+offx_u,icrm))*rdx);
real tmp2 = ((w(kc,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdz);
real tmp3 = (v(k,j+offy_v,ic+offx_v,icrm)-v(k,j+offy_v,i+offx_v,icrm))*rdx;
real tmp4 = (v(k,j+offy_v,i+offx_v,icrm)-v(k,j+offy_v,ib+offx_v,icrm))*rdx;
real tmp5 = ( (u(kc,j+offy_u,ic+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,ic+offx_u,icrm)+u0(k,icrm))*rdzw_up +
(w(kc,j+offy_w,ic+offx_w,icrm)-w(kc,j+offy_w,i+offx_w,icrm))*rdx_up);
real tmp6 = ( (u(kc,j+offy_u,i+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,i+offx_u,icrm)+u0(k,icrm))*rdzw_up +
(w(kc,j+offy_w,i+offx_w,icrm)-w(kc,j+offy_w,ib+offx_w,icrm))*rdx_up);
real tmp7 = ( (u(k,j+offy_u,ic+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,ic+offx_u,icrm)+u0(kb,icrm))*rdzw_dn +
(w(k,j+offy_w,ic+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdx_dn);
real tmp8 = ( (u(k,j+offy_u,i+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,i+offx_u,icrm)+u0(kb,icrm))*rdzw_dn +
(w(k,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,ib+offx_w,icrm))*rdx_dn);
real tmp9 = ( (v(kc,j+offy_v,i+offx_v,icrm)-v0(kc,icrm)-v(k,j+offy_v,i+offx_v,icrm)+v0(k,icrm))*rdzw_up);
real tmp10 = ( (v(k,j+offy_v,i+offx_v,icrm)-v0(k,icrm)-v(kb,j+offy_v,i+offx_v,icrm)+v0(kb,icrm))*rdzw_dn);
def2(k,j,i,icrm) = 2.0 * ( tmp1*tmp1 + tmp2*tmp2 ) + 0.5 * ( tmp3*tmp3 + tmp4*tmp4 + tmp5*tmp5 + tmp6 *tmp6 +
tmp7*tmp7 + tmp8*tmp8 + tmp9*tmp9 + tmp10*tmp10 );
} else if (k==0) {
kc = k+1;
rdz = 1.0/(dz(icrm)*adz(k,icrm));
rdzw_up = 1.0/(dz(icrm)*adzw(kc,icrm));
rdx = rdx0*sqrt(dx*rdz);
rdx_up = rdx0 *sqrt(dx*rdzw_up);
ib = i-1;
ic = i+1;
real tmp1 = ((u(k,j+offy_u,ic+offx_u,icrm)-u(k,j+offy_u,i+offx_u,icrm))*rdx);
real tmp2 = ((w(kc,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdz);
real tmp3 = ( (v(k,j+offy_v,ic+offx_v,icrm)-v(k,j+offy_v,i+offx_v,icrm))*rdx);
real tmp4 = ( (v(k,j+offy_v,i+offx_v,icrm)-v(k,j+offy_v,ib+offx_v,icrm))*rdx);
real tmp5 = ( (v(kc,j+offy_v,i+offx_v,icrm)-v0(kc,icrm)-v(k,j+offy_v,i+offx_v,icrm)+v0(k,icrm))*rdzw_up);
real tmp6 = ( (u(kc,j+offy_u,ic+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,ic+offx_u,icrm)+u0(k,icrm))*rdzw_up +
(w(kc,j+offy_w,ic+offx_w,icrm)-w(kc,j+offy_w,i+offx_w,icrm))*rdx_up);
real tmp7 = ( (u(kc,j+offy_u,i+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,i+offx_u,icrm)+u0(k,icrm))*rdzw_up +
(w(kc,j+offy_w,i+offx_w,icrm)-w(kc,j+offy_w,ib+offx_w,icrm))*rdx_up);
def2(k,j,i,icrm) = 2.0* ( tmp1*tmp1 + tmp2*tmp2 ) + 0.5 * ( tmp3*tmp3 + tmp4*tmp4 ) + tmp5*tmp5 +
0.5 * ( tmp6*tmp6 + tmp7*tmp7 );
} else if (k==nzm-1) {
kc = k+1;
kb = k-1;
rdz = 1.0/(dz(icrm)*adz(k,icrm));
rdzw_dn = 1.0/(dz(icrm)*adzw(k,icrm));
rdx = rdx0*sqrt(dx*rdz);
rdx_dn = rdx0 *sqrt(dx*rdzw_dn);
ib = i-1;
ic = i+1;
real tmp1 = ( (u(k,j+offy_u,ic+offx_u,icrm)-u(k,j+offy_u,i+offx_u,icrm))*rdx);
real tmp2 = ( (w(kc,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdz);
real tmp3 = ( (v(k,j+offy_v,ic+offx_v,icrm)-v(k,j+offy_v,i+offx_v,icrm))*rdx);
real tmp4 = ( (v(k,j+offy_v,i+offx_v,icrm)-v(k,j+offy_v,ib+offx_v,icrm))*rdx);
real tmp5 = ( (v(k,j+offy_v,i+offx_v,icrm)-v0(k,icrm)-v(kb,j+offy_v,i+offx_v,icrm)+v0(kb,icrm))*rdzw_dn);
real tmp6 = ( (u(k,j+offy_u,ic+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,ic+offx_u,icrm)+u0(kb,icrm))*rdzw_dn);
real tmp7 = ( (w(k,j+offy_w,ic+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdx_dn);
real tmp8 = ( (u(k,j+offy_u,i+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,i+offx_u,icrm)+u0(kb,icrm))*rdzw_dn+
(w(k,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,ib+offx_w,icrm))*rdx_dn);
def2(k,j,i,icrm) = 2.0 * ( tmp1*tmp1 + tmp2*tmp2 ) + 0.5 * ( tmp3*tmp3 + tmp4*tmp4 ) + tmp5*tmp5
+ 0.5 * ( tmp6*tmp6 + tmp7*tmp7 + tmp8*tmp8 );
}
});
}
| 52.245098
| 117
| 0.536874
|
katsmith133
|
881bcd5f5848285edc638fdb9594440aa969d9cd
| 2,317
|
cpp
|
C++
|
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/string/compare_icase.cpp
|
bingmann/distributed-string-sorting
|
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
|
[
"BSD-2-Clause"
] | 284
|
2017-02-26T08:49:15.000Z
|
2022-03-30T21:55:37.000Z
|
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/string/compare_icase.cpp
|
bingmann/distributed-string-sorting
|
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
|
[
"BSD-2-Clause"
] | 24
|
2017-09-05T21:02:41.000Z
|
2022-03-07T10:09:59.000Z
|
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/string/compare_icase.cpp
|
bingmann/distributed-string-sorting
|
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
|
[
"BSD-2-Clause"
] | 62
|
2017-02-23T12:29:27.000Z
|
2022-03-31T07:45:59.000Z
|
/*******************************************************************************
* tlx/string/compare_icase.cpp
*
* Part of tlx - http://panthema.net/tlx
*
* Copyright (C) 2007-2017 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the Boost Software License, Version 1.0
******************************************************************************/
#include <tlx/string/compare_icase.hpp>
#include <tlx/string/to_lower.hpp>
#include <algorithm>
namespace tlx {
int compare_icase(const char* a, const char* b) {
while (*a != 0 && *b != 0)
{
int ca = to_lower(*a++);
int cb = to_lower(*b++);
if (ca == cb) continue;
if (ca < cb) return -1;
else return +1;
}
if (*a == 0 && *b != 0) return +1;
else if (*a != 0 && *b == 0) return -1;
else return 0;
}
int compare_icase(const char* a, const std::string& b) {
std::string::const_iterator bi = b.begin();
while (*a != 0 && bi != b.end())
{
int ca = to_lower(*a++);
int cb = to_lower(*bi++);
if (ca == cb) continue;
if (ca < cb) return -1;
else return +1;
}
if (*a == 0 && bi != b.end()) return +1;
else if (*a != 0 && bi == b.end()) return -1;
else return 0;
}
int compare_icase(const std::string& a, const char* b) {
std::string::const_iterator ai = a.begin();
while (ai != a.end() && *b != 0)
{
int ca = to_lower(*ai++);
int cb = to_lower(*b++);
if (ca == cb) continue;
if (ca < cb) return -1;
else return +1;
}
if (ai == a.end() && *b != 0) return +1;
else if (ai != a.end() && *b == 0) return -1;
else return 0;
}
int compare_icase(const std::string& a, const std::string& b) {
std::string::const_iterator ai = a.begin();
std::string::const_iterator bi = b.begin();
while (ai != a.end() && bi != b.end())
{
int ca = to_lower(*ai++);
int cb = to_lower(*bi++);
if (ca == cb) continue;
if (ca < cb) return -1;
else return +1;
}
if (ai == a.end() && bi != b.end()) return +1;
else if (ai != a.end() && bi == b.end()) return -1;
else return 0;
}
} // namespace tlx
/******************************************************************************/
| 24.648936
| 80
| 0.45792
|
bingmann
|
881c429235adc29f370d5f644492664e29004cc0
| 697
|
cpp
|
C++
|
Test/FastFourierTransform.test.cpp
|
tkmst201/library
|
3abe841f5dde6078e8f26c9fd5d1a0716d4edc7d
|
[
"CC0-1.0"
] | null | null | null |
Test/FastFourierTransform.test.cpp
|
tkmst201/library
|
3abe841f5dde6078e8f26c9fd5d1a0716d4edc7d
|
[
"CC0-1.0"
] | null | null | null |
Test/FastFourierTransform.test.cpp
|
tkmst201/library
|
3abe841f5dde6078e8f26c9fd5d1a0716d4edc7d
|
[
"CC0-1.0"
] | null | null | null |
#define PROBLEM "https://judge.yosupo.jp/problem/frequency_table_of_tree_distance"
#include "GraphTheory/CentroidDecomposition.hpp"
#include "Convolution/FastFourierTransform.hpp"
#include "Algorithm/frequency_table_of_tree_distance.hpp"
#include <cstdio>
#include <vector>
int main() {
int N;
scanf("%d", &N);
CentroidDecomposition::Graph g(N);
for (int i = 0; i < N - 1; ++i) {
int a, b;
scanf("%d %d", &a, &b);
g[a].emplace_back(b);
g[b].emplace_back(a);
}
auto table = tk::frequency_table_of_tree_distance<CentroidDecomposition, FastFourierTransform>(g);
for (int i = 1; i < N; ++i) printf("%lld%c", i < table.size() ? table[i] : 0, " \n"[i + 1 == N]);
}
| 31.681818
| 100
| 0.658537
|
tkmst201
|
881d56651aeecec4bc2890f12242657b3b70e0fc
| 15,572
|
cpp
|
C++
|
math/vectorfunction.cpp
|
smeng9/KrisLibrary
|
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
|
[
"BSD-3-Clause"
] | 57
|
2015-05-07T18:07:11.000Z
|
2022-03-18T18:44:39.000Z
|
math/vectorfunction.cpp
|
smeng9/KrisLibrary
|
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
|
[
"BSD-3-Clause"
] | 7
|
2018-12-10T21:46:52.000Z
|
2022-01-20T19:49:11.000Z
|
math/vectorfunction.cpp
|
smeng9/KrisLibrary
|
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
|
[
"BSD-3-Clause"
] | 36
|
2015-01-10T18:36:45.000Z
|
2022-01-20T19:49:24.000Z
|
#include <KrisLibrary/Logger.h>
#include "vectorfunction.h"
#include "metric.h"
#include "indexing.h"
#include <errors.h>
#include <iostream>
using namespace Math;
using namespace std;
std::string NormScalarFieldFunction::Label() const
{
if(degree == Two) return "L2Norm";
else if(degree == One) return "L1Norm";
else if(degree == Inf) return "LInfNorm";
else {
char buf[32];
sprintf(buf,"%f",degree);
std::string str;
str = "L("; str+=buf; str+=")Norm";
return str;
}
}
void NormScalarFieldFunction::PreEval(const Vector& x)
{
norm=Norm(x,degree);
}
Real NormScalarFieldFunction::Eval(const Vector& x)
{
return norm;
}
void NormScalarFieldFunction::Gradient(const Vector& x,Vector& grad)
{
if(degree == Two) {
if(norm == Zero) grad.setZero();
else grad.div(x,norm);
}
else
AssertNotReached();
}
Real NormScalarFieldFunction::Gradient_i(const Vector& x,int i)
{
if(degree == Two) {
if(norm == Zero) return Zero;
return x(i)/norm;
}
else
AssertNotReached();
return Zero;
}
void NormScalarFieldFunction::Hessian(const Vector& x,Matrix& H)
{
for(int i=0;i<x.n;i++) {
for(int j=0;j<x.n;j++) {
if(i==j)
H(i,j) = (One - Sqr(x(i)/norm))/norm;
else
H(i,j) = -(x(i)/norm)*(x(j)/norm)/norm;
}
}
}
Real NormScalarFieldFunction::Hessian_ij(const Vector& x,int i,int j)
{
if(i==j)
return (One - Sqr(x(i)/norm))/norm;
else
return -(x(i)/norm)*(x(j)/norm)/norm;
}
void MinimumScalarFieldFunction::PreEval(const Vector& x) { xmin = x.minElement(&index); }
Real MinimumScalarFieldFunction::Eval(const Vector& x) { return xmin; }
void MinimumScalarFieldFunction::Gradient(const Vector& x,Vector& grad) { grad.setZero(); grad(index)=One; }
Real MinimumScalarFieldFunction::Gradient_i(const Vector& x,int i) { return Delta(i,index); }
void MaximumScalarFieldFunction::PreEval(const Vector& x) { xmax = x.maxElement(&index); }
Real MaximumScalarFieldFunction::Eval(const Vector& x) { return xmax; }
void MaximumScalarFieldFunction::Gradient(const Vector& x,Vector& grad) { grad.setZero(); grad(index)=One; }
Real MaximumScalarFieldFunction::Gradient_i(const Vector& x,int i) { return Delta(i,index); }
std::string ComposeScalarFieldFunction::Label() const
{
std::string sf=f->Label(), sg=g->Label();
std::string str=sf;
str+="(";
str+=sg;
str+="(x))";
return str;
}
void ComposeScalarFieldFunction::PreEval(const Vector& x)
{
g->PreEval(x);
gx=g->Eval(x);
f->PreEval(gx);
}
void ComposeScalarFieldFunction::Gradient(const Vector& x,Vector& grad)
{
g->Gradient(x,grad);
grad *= f->Deriv(gx);
}
Real ComposeScalarFieldFunction::Gradient_i(const Vector& x,int i)
{
return f->Deriv(gx)*g->Gradient_i(x,i);
}
void ComposeScalarFieldFunction::Hessian(const Vector& x,Matrix& H)
{
//f''*g'*g'^t + f'*g''
Assert(H.m == x.n);
Assert(H.n == x.n);
Vector grad(x.n);
Real df = f->Deriv(gx);
Real ddf = f->Deriv2(gx);
g->Gradient(x,grad);
g->Hessian(x,H);
H.inplaceMul(df);
for(int i=0;i<H.m;i++)
for(int j=0;j<H.n;j++)
H(i,j) += ddf*grad(i)*grad(j);
}
Real ComposeScalarFieldFunction::Hessian_ij(const Vector& x,int i,int j)
{
return f->Deriv(gx)*g->Hessian_ij(x,i,j) + f->Deriv2(gx)*g->Gradient_i(x,i)*g->Gradient_i(x,j);
}
std::string Compose_SF_VF_Function::Label() const
{
std::string sf=f->Label(), sg=g->Label();
std::string str=sf;
str+="(";
str+=sg;
str+="(x))";
return str;
}
void Compose_SF_VF_Function::PreEval(const Vector& x)
{
gx.resize(g->NumDimensions());
g->PreEval(x);
g->Eval(x,gx);
f->PreEval(gx);
}
void Compose_SF_VF_Function::Gradient(const Vector& x,Vector& grad)
{
Jg.resize(gx.n,x.n);
gradf.resize(gx.n);
g->Jacobian(x,Jg);
f->Gradient(gx,gradf);
Jg.mulTranspose(gradf,grad);
}
Real Compose_SF_VF_Function::Gradient_i(const Vector& x,int i)
{
Vector Jj(gx.n);
g->Jacobian_j(x,i,Jj);
f->Gradient(gx,gradf);
return Jj.dot(gradf);
}
void Compose_SF_VF_Function::Hessian(const Vector& x,Matrix& H)
{
//f''*g'*g'^t + f'*g''
f->Gradient(gx,gradf);
g->Jacobian(x,Jg);
Matrix Hf(gx.n,gx.n);
Matrix Hgi(x.n,x.n);
Matrix temp;
//first term
f->Hessian(gx,Hf);
temp.mul(Jg,Hf);
H.mulTransposeB(temp,Jg);
//second term
for(int i=0;i<x.n;i++) {
g->Hessian_i(x,i,Hgi);
Vector Hgit_gradf;
Hgi.mulTranspose(gradf,Hgit_gradf);
for(int j=0;j<x.n;i++) {
H(i,j) += Hgit_gradf(j);
}
}
}
Real Compose_SF_VF_Function::Hessian_ij(const Vector& x,int i,int j)
{
LOG4CXX_INFO(KrisLibrary::logger(),"Hessian_ij: this is totally inefficient!!!");
AssertNotReached();
return 0;
}
std::string Compose_VF_VF_Function::Label() const
{
std::string sf=f->Label(), sg=g->Label();
std::string str=sf;
str+="(";
str+=sg;
str+="(x))";
return str;
}
void Compose_VF_VF_Function::PreEval(const Vector& x)
{
gx.resize(g->NumDimensions());
g->PreEval(x);
g->Eval(x,gx);
f->PreEval(gx);
}
void Compose_VF_VF_Function::Jacobian(const Vector& x,Matrix& J)
{
g->Jacobian(x,Jg);
f->Jacobian(gx,Jf);
J.mul(Jf,Jg);
}
void Compose_VF_VF_Function::Jacobian_i(const Vector& x,int i,Vector& Ji)
{
Vector Jfi(gx.n);
g->Jacobian(x,Jg);
f->Jacobian_i(gx,i,Jfi);
Jg.mulTranspose(Jfi,Ji);
}
void Compose_VF_VF_Function::Jacobian_j(const Vector& x,int j,Vector& Jj)
{
Vector Jgj(gx.n);
g->Jacobian_j(x,j,Jgj);
f->Jacobian(gx,Jf);
Jf.mul(Jgj,Jj);
}
ScalarFieldDirectionalFunction::ScalarFieldDirectionalFunction(ScalarFieldFunction& _f,const Vector& _x,const Vector& _n,bool ref)
:f(&_f)
{
if(ref) {
x.setRef(_x);
n.setRef(_n);
}
else {
x = _x;
n = _n;
}
tmp.resize(x.n);
}
std::string ScalarFieldDirectionalFunction::Label() const
{
std::string sf=f->Label();
std::string str=sf; str+="(x+tn)";
return str;
}
void ScalarFieldDirectionalFunction::PreEval(Real t)
{
tmp=x; tmp.madd(n,t);
f->PreEval(tmp);
}
Real ScalarFieldDirectionalFunction::Eval(Real t)
{
return f->Eval(tmp);
}
Real ScalarFieldDirectionalFunction::Deriv(Real t)
{
return f->DirectionalDeriv(tmp,n);
}
Real ScalarFieldDirectionalFunction::Deriv2(Real t)
{
return f->DirectionalDeriv2(tmp,n);
}
ScalarFieldProjectionFunction::ScalarFieldProjectionFunction(ScalarFieldFunction& _f,const Vector& _x,int _i)
:f(&_f),i(_i)
{
tmp = _x;
xi0= _x(_i);
}
std::string ScalarFieldProjectionFunction::Label() const
{
char buf[32];
sprintf(buf,"(x+e%d)",i);
std::string sf=f->Label();
std::string str=sf; str+=buf;
return str;
}
void ScalarFieldProjectionFunction::PreEval(Real t)
{
tmp[i] = xi0+t;
f->PreEval(tmp);
}
Real ScalarFieldProjectionFunction::Eval(Real t)
{
return f->Eval(tmp);
}
Real ScalarFieldProjectionFunction::Deriv(Real t)
{
return f->Gradient_i(tmp,i);
}
Real ScalarFieldProjectionFunction::Deriv2(Real t)
{
return f->Hessian_ij(tmp,i,i);
}
VectorFieldProjectionFunction::VectorFieldProjectionFunction(VectorFieldFunction& _f,int _i)
:f(&_f),i(_i)
{}
std::string VectorFieldProjectionFunction::Label() const
{
char buf[32];
sprintf(buf,"(x+e%d)",i);
std::string sf=f->Label();
std::string str=sf; str+=buf;
return str;
}
Real VectorFieldProjectionFunction::Eval(const Vector& x)
{
return f->Eval_i(x,i);
}
void VectorFieldProjectionFunction::Gradient(const Vector& x,Vector& grad)
{
f->Jacobian_i(x,i,grad);
}
std::string ComponentVectorFieldFunction::Label() const
{
std::string str="Components(";
for(size_t i=0;i<functions.size();i++) {
str+=functions[i]->Label();
if(i+1 < functions.size())
str+=",";
}
str+=")";
return str;
}
std::string ComponentVectorFieldFunction::Label(int i) const
{
return functions[i]->Label();
}
int ComponentVectorFieldFunction::NumDimensions() const
{
return (int)functions.size();
}
void ComponentVectorFieldFunction::PreEval(const Vector& x)
{
for(size_t i=0;i<functions.size();i++) {
functions[i]->PreEval(x);
}
}
void ComponentVectorFieldFunction::Eval(const Vector& x, Vector& v)
{
for(size_t i=0;i<functions.size();i++)
v(i) = functions[i]->Eval(x);
}
Real ComponentVectorFieldFunction::Eval_i(const Vector& x,int i)
{
return functions[i]->Eval(x);
}
void ComponentVectorFieldFunction::Jacobian(const Vector& x,Matrix& J)
{
J.resize((int)functions.size(),x.n);
Vector vtemp;
for(size_t i=0;i<functions.size();i++) {
J.getRowRef(i,vtemp);
functions[i]->Gradient(x,vtemp);
}
}
void ComponentVectorFieldFunction::Jacobian_i(const Vector& x,int i,Vector& Ji)
{
functions[i]->Gradient(x,Ji);
}
void ComponentVectorFieldFunction::Hessian_i(const Vector& x,int i,Matrix& Hi)
{
functions[i]->Hessian(x,Hi);
}
void ComponentVectorFieldFunction::DirectionalDeriv(const Vector& x,const Vector& h,Vector& v)
{
for(size_t i=0;i<functions.size();i++)
v(i) = functions[i]->DirectionalDeriv(x,h);
}
CompositeVectorFieldFunction::CompositeVectorFieldFunction()
{}
CompositeVectorFieldFunction::CompositeVectorFieldFunction(std::shared_ptr<VectorFieldFunction> f1,std::shared_ptr<VectorFieldFunction>& f2)
{
functions.resize(2);
functions[0] = f1;
functions[1] = f2;
}
CompositeVectorFieldFunction::CompositeVectorFieldFunction(const std::vector<std::shared_ptr<VectorFieldFunction> >& fs)
:functions(fs)
{}
std::string CompositeVectorFieldFunction::Label() const
{
std::string str="Compose(";
for(size_t i=0;i<functions.size();i++) {
str+=functions[i]->Label();
if(i+1 < functions.size())
str+=",";
}
str+=")";
return str;
}
std::string CompositeVectorFieldFunction::Label(int i) const
{
int f=GetFunction(i);
return functions[f]->Label(i);
}
int CompositeVectorFieldFunction::NumDimensions() const
{
int nd=0;
for(size_t i=0;i<functions.size();i++) {
nd+=functions[i]->NumDimensions();
}
return nd;
}
void CompositeVectorFieldFunction::PreEval(const Vector& x)
{
for(size_t i=0;i<functions.size();i++) {
functions[i]->PreEval(x);
}
}
void CompositeVectorFieldFunction::Eval(const Vector& x, Vector& v)
{
Vector vtemp;
int nd=0;
for(size_t i=0;i<functions.size();i++) {
int idims=functions[i]->NumDimensions();
vtemp.setRef(v,nd,1,idims);
functions[i]->Eval(x,vtemp);
Assert(vtemp.n==idims);
nd += idims;
}
Assert(nd == v.n);
}
Real CompositeVectorFieldFunction::Eval_i(const Vector& x,int i)
{
int f= GetFunction(i);
return functions[f]->Eval_i(x,i);
}
void CompositeVectorFieldFunction::Jacobian(const Vector& x,Matrix& J)
{
J.resize(NumDimensions(),x.n);
Matrix mtemp;
int offset=0;
for(size_t i=0;i<functions.size();i++) {
mtemp.setRef(J,offset,0,1,1,functions[i]->NumDimensions(),x.n);
functions[i]->Jacobian(x,mtemp);
offset += mtemp.m;
}
}
void CompositeVectorFieldFunction::Jacobian_i(const Vector& x,int i,Vector& Ji)
{
int f=GetFunction(i);
functions[f]->Jacobian_i(x,i,Ji);
}
void CompositeVectorFieldFunction::Hessian_i(const Vector& x,int i,Matrix& Hi)
{
int f=GetFunction(i);
functions[f]->Hessian_i(x,i,Hi);
}
void CompositeVectorFieldFunction::DirectionalDeriv(const Vector& x,const Vector& h,Vector& v)
{
Vector vtemp;
int nd=0;
for(size_t i=0;i<functions.size();i++) {
vtemp.setRef(v,nd,1,functions[i]->NumDimensions());
functions[i]->DirectionalDeriv(x,h,vtemp);
nd+=vtemp.n;
}
Assert(v.n == nd);
}
int CompositeVectorFieldFunction::GetFunction(int& i) const
{
int iorig = i;
for(size_t k=0;k<functions.size();k++) {
int nd=functions[k]->NumDimensions();
if(i < nd) {
return (int)k;
}
else {
i -= nd;
}
}
LOG4CXX_INFO(KrisLibrary::logger(),"Shouldn't ever get here! i="<<iorig<<" must be out of range 0->"<<NumDimensions());
AssertNotReached();
return -1;
}
std::string IndexedVectorFieldFunction::Label() const
{
return std::string("indexed(")+function->Label()+")";
}
std::string IndexedVectorFieldFunction::Label(int i) const
{
if(findices.empty()) return function->Label(i);
return function->Label(findices[i]);
}
int IndexedVectorFieldFunction::NumDimensions() const
{
if(findices.empty()) return function->NumDimensions();
else return (int)findices.size();
}
void IndexedVectorFieldFunction::PreEval(const Vector& x)
{
function->PreEval(x);
if(!xindices.empty()) {
xsub.resize(xindices.size());
GetElements(x,xindices,xsub);
}
}
void IndexedVectorFieldFunction::Eval(const Vector& x, Vector& v)
{
if(xindices.empty())
function->Eval(x,vf);
else
function->Eval(xsub,vf);
if(findices.empty())
v=vf;
else {
v.resize(findices.size());
GetElements(vf,findices,v);
}
}
Real IndexedVectorFieldFunction::Eval_i(const Vector& x,int i)
{
int k=i;
if(!findices.empty()) k=findices[i];
if(xindices.empty())
return function->Eval_i(x,k);
else
return function->Eval_i(xsub,k);
}
void IndexedVectorFieldFunction::Jacobian(const Vector& x,Matrix& J)
{
if(xindices.empty()) {
function->Jacobian(x,Jf);
if(!findices.empty()) {
J.resize(findices.size(),x.n);
GetRows(Jf,findices,J);
}
else J = Jf;
}
else {
function->Jacobian(xsub,Jf);
if(!findices.empty()) {
J.resize(findices.size(),x.n,Zero);
for(size_t i=0;i<findices.size();i++) {
for(size_t j=0;j<xindices.size();j++)
J(i,xindices[j]) = Jf(findices[i],j);
}
}
else {
J.resize(Jf.m,x.n,Zero);
Vector a,b;
for(size_t j=0;j<xindices.size();j++) {
Jf.getColRef(j,a);
J.getColRef(xindices[j],b);
b = a;
}
}
}
}
void IndexedVectorFieldFunction::Jacobian_i(const Vector& x,int i,Vector& Ji)
{
int k=i;
if(!findices.empty()) k=findices[i];
if(xindices.empty()) {
function->Jacobian_i(x,k,Ji);
}
else {
function->Jacobian_i(x,i,vf);
Ji.resize(x.n,Zero);
SetElements(Ji,xindices,vf);
}
}
void IndexedVectorFieldFunction::DirectionalDeriv(const Vector& x,const Vector& h,Vector& v)
{
FatalError("Not done yet");
}
void IndexedVectorFieldFunction::Hessian_i(const Vector& x,int i,Matrix& Hi)
{
FatalError("Not done yet");
}
std::string SliceVectorFieldFunction::Label() const
{
return std::string("slice(")+function->Label()+")";
}
std::string SliceVectorFieldFunction::Label(int i) const
{
return function->Label(i);
}
int SliceVectorFieldFunction::NumDimensions() const
{
return function->NumDimensions();
}
void SliceVectorFieldFunction::PreEval(const Vector& x)
{
assert(x.n == (int)xindices.size());
xfull = x0;
SetElements(xfull,xindices,x);
function->PreEval(xfull);
}
void SliceVectorFieldFunction::Eval(const Vector& x, Vector& v)
{
function->Eval(xfull,v);
}
Real SliceVectorFieldFunction::Eval_i(const Vector& x,int i)
{
return function->Eval_i(xfull,i);
}
void SliceVectorFieldFunction::Jacobian(const Vector& x,Matrix& J)
{
function->Jacobian(xfull,Jf);
J.resize(Jf.m,(int)xindices.size());
GetColumns(Jf,xindices,J);
}
void SliceVectorFieldFunction::Jacobian_i(const Vector& x,int i,Vector& Ji)
{
function->Jacobian_i(xfull,i,vf);
Ji.resize(xindices.size());
GetElements(vf,xindices,Ji);
}
void SliceVectorFieldFunction::DirectionalDeriv(const Vector& x,const Vector& h,Vector& v)
{
Vector hfull(xfull.n,Zero);
SetElements(hfull,xindices,h);
function->DirectionalDeriv(xfull,hfull,vf);
v.resize(xindices.size());
GetElements(vf,xindices,v);
}
void SliceVectorFieldFunction::Hessian_i(const Vector& x,int i,Matrix& Hi)
{
Matrix Hf;
function->Hessian_i(x,i,Hf);
Hi.resize(xindices.size(),xindices.size());
GetElements(Hf,xindices,xindices,Hi);
}
| 21.597781
| 140
| 0.671654
|
smeng9
|
881fe9b8b9420a66c28f4be777b79ec61f7a32ac
| 6,224
|
cpp
|
C++
|
PopcornTime_Desktop-src/Import/QtAV/src/opengl/SubImagesGeometry.cpp
|
officialrafsan/POPCORNtime
|
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
|
[
"MIT"
] | null | null | null |
PopcornTime_Desktop-src/Import/QtAV/src/opengl/SubImagesGeometry.cpp
|
officialrafsan/POPCORNtime
|
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
|
[
"MIT"
] | null | null | null |
PopcornTime_Desktop-src/Import/QtAV/src/opengl/SubImagesGeometry.cpp
|
officialrafsan/POPCORNtime
|
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
|
[
"MIT"
] | null | null | null |
/******************************************************************************
QtAV: Multimedia framework based on Qt and FFmpeg
Copyright (C) 2012-2016 Wang Bin <wbsecg1@gmail.com>
* This file is part of QtAV (from 2016)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "SubImagesGeometry.h"
#include "utils/Logger.h"
namespace QtAV {
#define U8COLOR 0
static const int kMaxTexWidth = 4096; //FIXME: glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max);
// if texture1d, we can directly copy ASS_Image.bitmap without line by line copy, i.e. tiled, and upload only once
typedef struct {
float x, y; // depends on target rect
float tx, ty; // depends on texture size and rects layout
#if U8COLOR
union {
quint8 r, g, b, a; //to be normalized
quint32 rgba;
};
#else
float r, g, b, a;
#endif
} VertexData;
static VertexData* SetUnnormalizedVertexData(VertexData* v, int tx, int ty, int tw, int th, quint32 color, bool useIndecies)
{
#if U8COLOR
union {
quint8 r, g, b, a;
quint32 rgba;
};
r = color >> 24;
g = (color >> 16) & 0xff;
b = (color >> 8) & 0xff;
a = 255 - (color & 0xff);
#else
float r, g, b, a;
r = (float)(color >> 24)/255.0;
g = (float)((color >> 16) & 0xff)/255.0;
b = (float)((color >> 8) & 0xff)/255.0;
a = (float)(255 - (color & 0xff))/255.0;
#endif
// normalize later
v[0].tx = tx;
v[0].ty = ty;
v[1].tx = tx;
v[1].ty = ty + th;
v[2].tx = tx + tw;
v[2].ty = ty;
v[3].tx = tx + tw;
v[3].ty = ty + th;
#if U8COLOR
v[0].rgba = rgba;
v[1].rgba = rgba;
v[2].rgba = rgba;
v[3].rgba = rgba;
#else
#define SETC(x) x.r = r; x.g=g; x.b=b; x.a=a;
SETC(v[0]);
SETC(v[1]);
SETC(v[2]);
SETC(v[3]);
#endif
if (!useIndecies) {
v[4] = v[1];
v[5] = v[2];
return v + 6;
}
return v + 4;
}
static VertexData* SetVertexPositionAndNormalize(VertexData* v, float x, float y, float w, float h, float texW, float texH, bool useIndecies)
{
v[0].x = x;
v[0].y = y;
v[1].x = x;
v[1].y = y + h;
v[2].x = x + w;
v[2].y = y;
v[3].x = x + w;
v[3].y = y + h;
v[0].tx /= texW;
v[0].ty /= texH;
v[1].tx /= texW;
v[1].ty /= texH;
v[2].tx /= texW;
v[2].ty /= texH;
v[3].tx /= texW;
v[3].ty /= texH;
//qDebug("%f,%f<=%f,%f; %u,%u,%u,%u", v[3].x, v[3].y, v[3].tx, v[3].ty, v[3].r, v[3].g, v[3].b, v[3].a);
if (!useIndecies) {
v[4] = v[1];
v[5] = v[2];
return v + 6;
}
return v + 4;
}
SubImagesGeometry::SubImagesGeometry()
: Geometry()
, m_normalized(false)
, m_w(0)
, m_h(0)
{
setPrimitive(Geometry::Triangles);
m_attributes << Attribute(TypeF32, 2)
<< Attribute(TypeF32, 2, 2*sizeof(float))
#if U8COLOR
<< Attribute(TypeU8, 4, 4*sizeof(float), true);
#else
<< Attribute(TypeF32, 4, 4*sizeof(float));
#endif
}
bool SubImagesGeometry::setSubImages(const SubImageSet &images)
{
// TODO: operator ==
if (m_images == images)
return false;
m_images = images;
return true;
}
bool SubImagesGeometry::generateVertexData(const QRect &rect, bool useIndecies, int maxWidth)
{
if (maxWidth < 0)
maxWidth = kMaxTexWidth;
if (useIndecies)
allocate(4*m_images.images.size(), 6*m_images.images.size());
else
allocate(6*m_images.images.size());
qDebug("images: %d/%d, %dx%d", m_images.isValid(), m_images.images.size(), m_images.width(), m_images.height());
m_rects_upload.clear();
m_w = m_h = 0;
m_normalized = false;
if (!m_images.isValid())
return false;
int W = 0, H = 0;
int x = 0, h = 0;
VertexData* vd = (VertexData*)vertexData();
int index = 0;
foreach (const SubImage& i, m_images.images) {
if (x + i.stride > maxWidth && maxWidth > 0) {
W = qMax(W, x);
H += h;
x = 0;
h = 0;
}
// we use w instead of stride even if we must upload stride. when maping texture coordinates and view port coordinates, we can use the visual rects instead of stride, i.e. the geometry vertices are (x, y, w, h), not (x, y, stride, h)
m_rects_upload.append(QRect(x, H, i.stride, i.h));
vd = SetUnnormalizedVertexData(vd, x, H, i.w, i.h, i.color, useIndecies);
if (useIndecies) { // TODO: set only once because it never changes, use IBO
const int v0 = index*4/6;
setIndexValue(index, v0, v0+1, v0+2);
setIndexValue(index+3, v0+1, v0+2, v0+3);
index += 6;
}
x += i.w;
h = qMax(h, i.h);
}
W = qMax(W, x);
H += h;
m_w = W;
m_h = H;
//qDebug("sub texture %dx%d", m_w, m_h);
const float dx0 = rect.x();
const float dy0 = rect.y();
const float sx = float(rect.width())/float(m_images.width());
const float sy = float(rect.height())/float(m_images.height());
vd = (VertexData*)vertexData();
foreach (const SubImage& i, m_images.images) {
//qDebug() << rect;
//qDebug("i: %d,%d", i.x, i.y);
vd = SetVertexPositionAndNormalize(vd, dx0 + float(i.x)*sx, dy0 + float(i.y)*sy, i.w*sx, i.h*sy, m_w, m_h, useIndecies);
m_normalized = true;
}
return true;
}
int SubImagesGeometry::stride() const
{
return sizeof(VertexData);
}
} //namespace QtAV
| 30.213592
| 241
| 0.560893
|
officialrafsan
|
8820d7c40c0d4b7395950dbe80bb81a78815f8f5
| 1,225
|
cpp
|
C++
|
src/executors/loadmatrix.cpp
|
bhavyajeet/Project-PreQL
|
9a8fffe450a37b324f09b53fbc1bc762aa7cc556
|
[
"MIT"
] | null | null | null |
src/executors/loadmatrix.cpp
|
bhavyajeet/Project-PreQL
|
9a8fffe450a37b324f09b53fbc1bc762aa7cc556
|
[
"MIT"
] | null | null | null |
src/executors/loadmatrix.cpp
|
bhavyajeet/Project-PreQL
|
9a8fffe450a37b324f09b53fbc1bc762aa7cc556
|
[
"MIT"
] | null | null | null |
#include "global.h"
/**
* @brief
* SYNTAX: LOAD relation_name
*/
bool syntacticParseLOADMATRIX()
{
logger.log("syntacticParseLOADMATRIX");
if (tokenizedQuery.size() != 3)
{
cout << "SYNTAX ERROR PLEASE SPECIFY MATRIX NAME" << endl;
return false;
}
parsedQuery.queryType = LOADMATRIX;
parsedQuery.loadMatrixRelationName = tokenizedQuery[2];
return true;
}
bool semanticParseLOADMATRIX()
{
logger.log("semanticParseLOADMATRIX");
if (matrixCatalogue.isMatrix(parsedQuery.loadMatrixRelationName))
{
cout << "SEMANTIC ERROR: Relation already exists" << endl;
return false;
}
if (!isFileExists(parsedQuery.loadMatrixRelationName))
{
cout << "SEMANTIC ERROR: Data file doesn't exist" << endl;
return false;
}
return true;
}
void executeLOADMATRIX()
{
Matrix *matrix = new Matrix(parsedQuery.loadMatrixRelationName);
if (matrix->load())
{
matrixCatalogue.insertMatrix(matrix);
cout << "Loaded Matrix. Column Count: " << matrix->columnCount << " Row Count: " << matrix->rowCount << endl;
}
logger.log("executeLOADMATRIX");
return;
}
| 26.06383
| 118
| 0.62449
|
bhavyajeet
|
88220f53e046ce6c80b1138b272aac1adbc5884b
| 1,502
|
cpp
|
C++
|
regression/advection_pdbott_prepare_tracers.cpp
|
aurianer/gridtools
|
5f99471bf36215e2a53317d2c7844bf057231ffa
|
[
"BSD-3-Clause"
] | null | null | null |
regression/advection_pdbott_prepare_tracers.cpp
|
aurianer/gridtools
|
5f99471bf36215e2a53317d2c7844bf057231ffa
|
[
"BSD-3-Clause"
] | null | null | null |
regression/advection_pdbott_prepare_tracers.cpp
|
aurianer/gridtools
|
5f99471bf36215e2a53317d2c7844bf057231ffa
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <vector>
#include <gtest/gtest.h>
#include <gridtools/stencil_composition/cartesian.hpp>
#include <gridtools/tools/cartesian_regression_fixture.hpp>
using namespace gridtools;
using namespace cartesian;
struct prepare_tracers {
using data = inout_accessor<0>;
using data_nnow = in_accessor<1>;
using rho = in_accessor<2>;
using param_list = make_param_list<data, data_nnow, rho>;
template <typename Evaluation>
GT_FUNCTION static void apply(Evaluation eval) {
eval(data()) = eval(rho()) * eval(data_nnow());
}
};
using advection_pdbott_prepare_tracers = regression_fixture<>;
TEST_F(advection_pdbott_prepare_tracers, test) {
std::vector<storage_type> in, out;
for (size_t i = 0; i < 11; ++i) {
out.push_back(make_storage());
in.push_back(make_storage(i));
}
auto comp = [grid = make_grid(), &in, &out, rho = make_const_storage(1.1)] {
expandable_run<2>(
[](auto out, auto in, auto rho) { return execute_parallel().stage(prepare_tracers(), out, in, rho); },
backend_t(),
grid,
out,
in,
rho);
};
comp();
for (size_t i = 0; i != out.size(); ++i)
verify([i](int, int, int) { return 1.1 * i; }, out[i]);
benchmark(comp);
}
| 25.033333
| 114
| 0.62783
|
aurianer
|
88225addc320c91a69c06e582c018e8bc49de7b2
| 226
|
hpp
|
C++
|
libraries/singularity/singularity/include/graphene/poi/singularity.hpp
|
petrkotegov/gravity-core
|
52c9a96126739c33ee0681946e1d88c5be9a6190
|
[
"MIT"
] | 8
|
2018-05-25T17:58:46.000Z
|
2018-06-23T21:13:26.000Z
|
libraries/singularity/singularity/include/graphene/poi/singularity.hpp
|
petrkotegov/gravity-core
|
52c9a96126739c33ee0681946e1d88c5be9a6190
|
[
"MIT"
] | 14
|
2018-05-25T19:44:30.000Z
|
2018-08-03T11:35:27.000Z
|
libraries/singularity/singularity/include/graphene/poi/singularity.hpp
|
petrkotegov/gravity-core
|
52c9a96126739c33ee0681946e1d88c5be9a6190
|
[
"MIT"
] | 6
|
2018-05-30T04:37:46.000Z
|
2019-03-05T14:47:34.000Z
|
#ifndef SINGULARITY_HPP
#define SINGULARITY_HPP
#include <graphene/singularity/emission.hpp>
#include <graphene/singularity/gravity_index_calculator.hpp>
#include <graphene/singularity/activity_index_calculator.hpp>
#endif
| 22.6
| 61
| 0.845133
|
petrkotegov
|
882407e038138ed1b82282d20ca8912d00060b27
| 17,985
|
cc
|
C++
|
plugin_injector/plugin_injector.cc
|
teamsimplepay/sorbet
|
8c2053b1b1e2e6d1f721e7b52335fbba478ef114
|
[
"Apache-2.0"
] | null | null | null |
plugin_injector/plugin_injector.cc
|
teamsimplepay/sorbet
|
8c2053b1b1e2e6d1f721e7b52335fbba478ef114
|
[
"Apache-2.0"
] | null | null | null |
plugin_injector/plugin_injector.cc
|
teamsimplepay/sorbet
|
8c2053b1b1e2e6d1f721e7b52335fbba478ef114
|
[
"Apache-2.0"
] | 1
|
2021-12-02T07:50:49.000Z
|
2021-12-02T07:50:49.000Z
|
// These violate our poisons so have to happen first
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Host.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "absl/cleanup/cleanup.h"
#include "absl/strings/str_split.h"
#include "absl/synchronization/mutex.h"
#include "ast/ast.h"
#include "cfg/CFG.h"
#include "common/FileOps.h"
#include "common/typecase.h"
#include "compiler/Core/AbortCompilation.h"
#include "compiler/Core/CompilerState.h"
#include "compiler/Core/FailCompilation.h"
#include "compiler/Core/OptimizerException.h"
#include "compiler/Errors/Errors.h"
#include "compiler/IREmitter/IREmitter.h"
#include "compiler/IREmitter/IREmitterHelpers.h"
#include "compiler/IREmitter/Payload/PayloadLoader.h"
#include "compiler/ObjectFileEmitter/ObjectFileEmitter.h"
#include "core/ErrorQueue.h"
#include "main/options/options.h"
#include "main/pipeline/semantic_extension/SemanticExtension.h"
#include <cxxopts.hpp>
#include <optional>
using namespace std;
namespace sorbet::pipeline::semantic_extension {
namespace {
string objectFileName(const core::GlobalState &gs, const core::FileRef &f) {
string sourceFile(f.data(gs).path());
if (sourceFile[0] == '.' && sourceFile[1] == '/') {
sourceFile = sourceFile.substr(2);
}
return sourceFile;
}
void ensureOutputDir(const string_view outputDir, string_view fileName) {
string path(outputDir);
auto finalSlashPos = fileName.rfind('/');
if (finalSlashPos == string_view::npos) {
return;
}
// Trim the filename so that we only iterate directory parts below
fileName.remove_suffix(fileName.size() - finalSlashPos);
for (auto part : absl::StrSplit(fileName, '/')) {
absl::StrAppend(&path, "/", part);
FileOps::ensureDir(path);
}
}
} // namespace
// Sorbet's pipeline is architected such that one thread is typechecking one file at a time.
// This struct allows us to store state local to one typechecking thread.
class TypecheckThreadState {
public:
// Creating an LLVMContext is somewhat expensive, so we don't want to create more than one per thread.
llvm::LLVMContext lctx;
// The file this thread is currently typechecking
core::FileRef file;
// The output of IREmitter for a file.
//
// "Combined" because all the methods in this file get compiled and accumulated into this Module,
// but each method is typechecked (and thus compiled) individually.
unique_ptr<llvm::Module> combinedModule;
unique_ptr<llvm::DIBuilder> debugInfo;
llvm::DICompileUnit *compileUnit = nullptr;
// The basic-block that holds the initialization of string constants.
llvm::BasicBlock *allocRubyIdsEntry = nullptr;
compiler::StringTable stringTable;
compiler::IDTable idTable;
// The function that holds calls to global constructors
//
// This works as a replacement to llvm.global_ctors so that we can delay initialization until after
// our sorbet_ruby version check.
llvm::BasicBlock *globalConstructorsEntry = nullptr;
bool aborted = false;
const unique_ptr<const llvm::Module> codegenPayload;
TypecheckThreadState() : codegenPayload(compiler::PayloadLoader::readDefaultModule(lctx)) {}
};
class LLVMSemanticExtension : public SemanticExtension {
optional<string> compiledOutputDir;
optional<string> irOutputDir;
bool forceCompiled;
mutable struct {
UnorderedMap<std::thread::id, shared_ptr<TypecheckThreadState>> states;
absl::Mutex mtx;
} mutableState;
shared_ptr<TypecheckThreadState> getTypecheckThreadState() const {
{
absl::ReaderMutexLock lock(&mutableState.mtx);
if (mutableState.states.contains(std::this_thread::get_id())) {
return mutableState.states.at(std::this_thread::get_id());
}
}
{
absl::WriterMutexLock lock(&mutableState.mtx);
return mutableState.states[std::this_thread::get_id()] = make_shared<TypecheckThreadState>();
}
}
bool shouldCompile(const core::GlobalState &gs, const core::FileRef &f) const {
if (!compiledOutputDir.has_value()) {
return false;
}
if (forceCompiled) {
return true;
}
// TODO parse this the same way as `typed:`
return isCompiledTrue(gs, f);
}
bool isCompiledTrue(const core::GlobalState &gs, const core::FileRef &f) const {
return f.data(gs).compiledLevel == core::CompiledLevel::True;
}
// There are a certain class of method calls that sorbet generates for auxiliary
// information for IDEs that do not have meaning at runtime. These calls are all
// of the form `foo(bar(baz))`, i.e. straight line code with no variables.
// We take advantage of this special knowledge to do a simple form of dead code
// elimination.
void deleteDoNothingSends(cfg::CFG &cfg) const {
for (auto &block : cfg.basicBlocks) {
UnorderedSet<cfg::LocalRef> refsToDelete;
for (auto i = block->exprs.rbegin(), e = block->exprs.rend(); i != e; ++i) {
auto &binding = *i;
if (auto *send = cfg::cast_instruction<cfg::Send>(binding.value)) {
switch (send->fun.rawId()) {
case core::Names::keepForIde().rawId():
case core::Names::keepForTypechecking().rawId():
// TODO: figure out why we can't delete this.
// case core::Names::keepForCfg().rawId():
refsToDelete.emplace(binding.bind.variable);
break;
default:
if (!refsToDelete.contains(binding.bind.variable)) {
continue;
}
break;
}
// We're binding a ref that is unneeded, so anything that this
// instruction requires must be unneeded as well.
for (auto &arg : send->args) {
refsToDelete.emplace(arg.variable);
}
refsToDelete.emplace(send->recv.variable);
}
}
auto e = std::remove_if(block->exprs.begin(), block->exprs.end(),
[&](auto &binding) { return refsToDelete.contains(binding.bind.variable); });
block->exprs.erase(e, block->exprs.end());
}
}
public:
LLVMSemanticExtension(optional<string> compiledOutputDir, optional<string> irOutputDir, bool forceCompiled) {
this->compiledOutputDir = move(compiledOutputDir);
this->irOutputDir = move(irOutputDir);
this->forceCompiled = forceCompiled;
}
virtual void run(core::MutableContext &ctx, ast::ClassDef *klass) const override{};
virtual void typecheck(const core::GlobalState &gs, cfg::CFG &cfg, ast::MethodDef &md) const override {
if (!shouldCompile(gs, cfg.file)) {
return;
}
// This method will be handled as a VM_METHOD_TYPE_IVAR method by the
// standard VM mechanisms, so we don't need to generate code for it.
if (md.flags.isAttrReader && !md.symbol.data(gs)->flags.isFinal) {
return;
}
if (md.symbol.data(gs)->name == core::Names::staticInit()) {
auto attachedClass = md.symbol.data(gs)->owner.data(gs)->attachedClass(gs);
if (attachedClass.exists() && attachedClass.data(gs)->name.isTEnumName(gs)) {
return;
}
}
auto threadState = getTypecheckThreadState();
if (threadState->aborted) {
return;
}
deleteDoNothingSends(cfg);
llvm::LLVMContext &lctx = threadState->lctx;
unique_ptr<llvm::Module> &module = threadState->combinedModule;
unique_ptr<llvm::DIBuilder> &debug = threadState->debugInfo;
llvm::DICompileUnit *&compUnit = threadState->compileUnit;
// TODO: Figure out why this isn't true
// ENFORCE(absl::c_find(cfg.symbol.data(gs)->locs(), md->loc) != cfg.symbol.data(gs)->locs().end(),
// loc.toString(gs));
ENFORCE(cfg.file.exists());
if (!module) {
ENFORCE(threadState->globalConstructorsEntry == nullptr);
ENFORCE(debug == nullptr);
ENFORCE(compUnit == nullptr);
module = llvm::CloneModule(*threadState->codegenPayload);
module->addModuleFlag(llvm::Module::Warning, "Debug Info Version", llvm::DEBUG_METADATA_VERSION);
module->addModuleFlag(llvm::Module::Override, "cf-protection-return", 1);
module->addModuleFlag(llvm::Module::Override, "cf-protection-branch", 1);
if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
// osx only supports dwarf2
module->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
}
debug = std::make_unique<llvm::DIBuilder>(*module);
// NOTE: we use C here because our generated functions follow its abi
auto language = llvm::dwarf::DW_LANG_C;
auto filename = cfg.file.data(gs).path();
auto isOptimized = false;
auto runtimeVersion = 0;
compUnit = debug->createCompileUnit(
language, debug->createFile(llvm::StringRef(filename.data(), filename.size()), "."), "Sorbet LLVM",
isOptimized, "", runtimeVersion);
threadState->file = cfg.file;
threadState->stringTable.clear();
threadState->idTable.clear();
{
auto linkageType = llvm::Function::InternalLinkage;
auto argTys = std::vector<llvm::Type *>{llvm::Type::getInt64Ty(lctx)};
auto varArgs = false;
auto ft = llvm::FunctionType::get(llvm::Type::getVoidTy(lctx), argTys, varArgs);
auto globalConstructors = llvm::Function::Create(ft, linkageType, "sorbet_globalConstructors", *module);
threadState->allocRubyIdsEntry = llvm::BasicBlock::Create(lctx, "allocRubyIds", globalConstructors);
threadState->globalConstructorsEntry =
llvm::BasicBlock::Create(lctx, "globalConstructors", globalConstructors);
}
} else {
ENFORCE(threadState->file == cfg.file);
ENFORCE(threadState->globalConstructorsEntry != nullptr);
}
ENFORCE(threadState->file.exists());
compiler::CompilerState state(gs, lctx, module.get(), debug.get(), compUnit, threadState->file,
threadState->allocRubyIdsEntry, threadState->globalConstructorsEntry,
threadState->stringTable, threadState->idTable);
absl::Cleanup dropInternalState = [&] {
threadState->aborted = true;
module = nullptr;
threadState->file = core::FileRef();
};
try {
compiler::IREmitter::run(state, cfg, md);
string fileName = objectFileName(gs, cfg.file);
compiler::IREmitter::buildInitFor(state, cfg.symbol, fileName);
std::move(dropInternalState).Cancel();
} catch (sorbet::compiler::AbortCompilation &) {
threadState->aborted = true;
std::move(dropInternalState).Cancel();
} catch (sorbet::compiler::OptimizerException &oe) {
threadState->aborted = true;
std::move(dropInternalState).Cancel();
// This exception is thrown from within an optimizer pass, where GlobalState
// is not available, so we need to emit an error here, where we do have
// access to GlobalState.
if (auto e = gs.beginError(core::Loc(cfg.file, 0, 0), core::errors::Compiler::OptimizerFailure)) {
e.setHeader("{}", oe.what());
}
}
};
virtual void finishTypecheckFile(const core::GlobalState &gs, const core::FileRef &f) const override {
if (!shouldCompile(gs, f)) {
return;
}
if (f.data(gs).minErrorLevel() >= core::StrictLevel::True) {
if (f.data(gs).source().find("frozen_string_literal: true"sv) == string_view::npos) {
compiler::failCompilation(gs, core::Loc(f, 0, 0),
"Compiled files need to have '# frozen_string_literal: true'");
}
} else {
compiler::failCompilation(gs, core::Loc(f, 0, 0),
"Compiled files must be at least '# typed: true' or above");
}
auto threadState = getTypecheckThreadState();
llvm::LLVMContext &lctx = threadState->lctx;
unique_ptr<llvm::Module> module = move(threadState->combinedModule);
unique_ptr<llvm::DIBuilder> debug = move(threadState->debugInfo);
threadState->compileUnit = nullptr;
// It is possible, though unusual, to never have typecheck() called.
if (!module) {
ENFORCE(!threadState->file.exists());
return;
}
if (threadState->aborted) {
threadState->file = core::FileRef();
return;
}
{
llvm::IRBuilder<> builder(lctx);
threadState->stringTable.defineGlobalVariables(lctx, *module);
builder.SetInsertPoint(threadState->allocRubyIdsEntry);
threadState->idTable.defineGlobalVariables(lctx, *module, builder);
builder.CreateBr(threadState->globalConstructorsEntry);
builder.SetInsertPoint(threadState->globalConstructorsEntry);
builder.CreateRetVoid();
}
threadState->globalConstructorsEntry = nullptr;
ENFORCE(threadState->file.exists());
ENFORCE(f == threadState->file);
ENFORCE(threadState->combinedModule == nullptr);
ENFORCE(threadState->globalConstructorsEntry == nullptr);
threadState->file = core::FileRef();
debug->finalize();
string fileName = objectFileName(gs, f);
ensureOutputDir(compiledOutputDir.value(), fileName);
if (irOutputDir.has_value()) {
ensureOutputDir(irOutputDir.value(), fileName);
}
if (!compiler::ObjectFileEmitter::run(gs.tracer(), lctx, move(module), compiledOutputDir.value(), irOutputDir,
fileName)) {
compiler::failCompilation(gs, core::Loc(f, 0, 0), "Object file emitter failed");
}
};
virtual void finishTypecheck(const core::GlobalState &gs) const override {}
virtual ~LLVMSemanticExtension(){};
virtual std::unique_ptr<SemanticExtension> deepCopy(const core::GlobalState &from, core::GlobalState &to) override {
return make_unique<LLVMSemanticExtension>(this->compiledOutputDir, this->irOutputDir, this->forceCompiled);
};
virtual void merge(const core::GlobalState &from, core::GlobalState &to, core::NameSubstitution &subst) override {}
};
class LLVMSemanticExtensionProvider : public SemanticExtensionProvider {
public:
virtual void injectOptions(cxxopts::Options &optsBuilder) const override {
optsBuilder.add_options("compiler")(
"compiled-out-dir", "Output compiled code (*.rb.so or *.rb.bundle) to directory, which must already exist",
cxxopts::value<string>());
optsBuilder.add_options("compiler")("llvm-ir-dir", "Output LLVM IR to directory, which must already exist",
cxxopts::value<string>());
optsBuilder.add_options("compiler")("force-compiled", "Force all files to this compiled level",
cxxopts::value<bool>());
};
virtual std::unique_ptr<SemanticExtension> readOptions(cxxopts::ParseResult &providedOptions) const override {
if (providedOptions["version"].as<bool>()) {
fmt::print("Sorbet compiler {}\n", sorbet_full_version_string);
throw EarlyReturnWithCode(0);
}
optional<string> compiledOutputDir;
optional<string> irOutputDir;
bool forceCompiled = false;
if (providedOptions.count("compiled-out-dir") > 0) {
auto outputDir = providedOptions["compiled-out-dir"].as<string>();
if (!FileOps::dirExists(outputDir)) {
fmt::print("Missing output directory {}\n", outputDir);
throw EarlyReturnWithCode(1);
}
compiledOutputDir = outputDir;
}
if (providedOptions.count("llvm-ir-dir") > 0) {
auto outputDir = providedOptions["llvm-ir-dir"].as<string>();
if (!FileOps::dirExists(outputDir)) {
fmt::print("Missing output directory {}\n", outputDir);
throw EarlyReturnWithCode(1);
}
irOutputDir = outputDir;
}
if (providedOptions.count("force-compiled") > 0) {
forceCompiled = providedOptions["force-compiled"].as<bool>();
}
return make_unique<LLVMSemanticExtension>(compiledOutputDir, irOutputDir, forceCompiled);
};
virtual std::unique_ptr<SemanticExtension> defaultInstance() const override {
optional<string> compiledOutputDir;
optional<string> irOutputDir;
auto forceCompile = false;
return make_unique<LLVMSemanticExtension>(compiledOutputDir, irOutputDir, forceCompile);
}
virtual ~LLVMSemanticExtensionProvider(){};
};
vector<SemanticExtensionProvider *> SemanticExtensionProvider::getProviders() {
static LLVMSemanticExtensionProvider provider;
return {&provider};
}
} // namespace sorbet::pipeline::semantic_extension
| 41.923077
| 120
| 0.617125
|
teamsimplepay
|
88243da6da01aa28eae1f7e434b85f789ab9feaa
| 2,757
|
hpp
|
C++
|
include/tmxlite/ObjectGroup.hpp
|
jsundgren/MindTheGap
|
baddbf2b50bd0b136f303402bcf2e26f3e089ba9
|
[
"MIT"
] | 9
|
2018-11-11T12:56:29.000Z
|
2021-11-14T20:38:00.000Z
|
UrsusEngine/tmxlite/include/tmxlite/ObjectGroup.hpp
|
l1ttl3-Sh4m4n/UrsusEngine
|
a18074a6aae118ad6321ab6b352ad9904eff2070
|
[
"MIT"
] | null | null | null |
UrsusEngine/tmxlite/include/tmxlite/ObjectGroup.hpp
|
l1ttl3-Sh4m4n/UrsusEngine
|
a18074a6aae118ad6321ab6b352ad9904eff2070
|
[
"MIT"
] | 5
|
2018-11-11T21:16:29.000Z
|
2021-09-13T14:59:22.000Z
|
/*********************************************************************
Matt Marchant 2016
http://trederia.blogspot.com
tmxlite - Zlib license.
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*********************************************************************/
#ifndef TMXLITE_OBJECTGROUP_HPP_
#define TMXLITE_OBJECTGROUP_HPP_
#include <tmxlite/Config.hpp>
#include <tmxlite/Layer.hpp>
#include <tmxlite/Object.hpp>
#include <vector>
namespace tmx
{
/*!
\brief ObjectGroup layers contain a series of Objects
which may be made up of shapes or images.
*/
class TMXLITE_EXPORT_API ObjectGroup final : public Layer
{
public:
enum class DrawOrder
{
Index, //< objects should be drawn in the order in which they appear
TopDown //< objects should be drawn sorted by their Y position
};
ObjectGroup();
~ObjectGroup() = default;
Type getType() const override { return Layer::Type::Object; }
void parse(const pugi::xml_node&) override;
/*!
\brief Returns the colour associated with this layer
*/
const Colour& getColour() const { return m_colour; }
/*!
\brief Returns the DrawOrder for the objects in this group.
Defaults to TopDown, where Objects are drawn sorted by Y position
*/
DrawOrder getDrawOrder() const { return m_drawOrder; }
/*!
\brief Returns a reference to the vector of properties for
the ObjectGroup
*/
const std::vector<Property>& getProperties() const { return m_properties; }
/*!
\brief Returns a reference to the vector of Objects which belong to the group
*/
const std::vector<Object>& getObjects() const { return m_objects; }
private:
Colour m_colour;
DrawOrder m_drawOrder;
std::vector<Property> m_properties;
std::vector<Object> m_objects;
};
}
#endif //TMXLITE_OBJECTGROUP_HPP_
| 32.05814
| 85
| 0.65506
|
jsundgren
|
88270e6a33ee9696f778d082a73fe4ba2efbac20
| 751
|
cpp
|
C++
|
Practice Programs/chef_and_rainbow_array.cpp
|
C-Nikks/CPP_Language_Programs
|
e3ed1990aedd6b41f2746cdab7661c40f24d5588
|
[
"MIT"
] | 3
|
2021-02-04T17:59:00.000Z
|
2022-01-29T17:21:42.000Z
|
Practice Programs/chef_and_rainbow_array.cpp
|
C-Nikks/CPP_Language_Programs
|
e3ed1990aedd6b41f2746cdab7661c40f24d5588
|
[
"MIT"
] | null | null | null |
Practice Programs/chef_and_rainbow_array.cpp
|
C-Nikks/CPP_Language_Programs
|
e3ed1990aedd6b41f2746cdab7661c40f24d5588
|
[
"MIT"
] | 3
|
2021-10-02T14:38:21.000Z
|
2021-10-05T06:19:22.000Z
|
#include <iostream>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int N, half, flag = 0;
cin >> N;
int arr[N];
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
int count = 0;
if (arr[N / 2] == 7 && arr[0] == 1)
{
for (int i = 0; i < N / 2; i++)
{
if ((arr[i] == arr[N - 1 - i]) && (arr[i] == arr[i + 1] || arr[i] + 1 == arr[i + 1]))
{
count++;
}
}
}
if (count == N / 2)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
}
return 0;
}
| 19.763158
| 101
| 0.274301
|
C-Nikks
|
88272ef7427fbb6c6403d5ae5bcaea95374d8bb7
| 6,023
|
hh
|
C++
|
src/include/cpu.hh
|
tomblackwhite/alpha-emu
|
a371f7d094acbf02c83aa3940ff043f033b7cfe8
|
[
"BSD-2-Clause"
] | null | null | null |
src/include/cpu.hh
|
tomblackwhite/alpha-emu
|
a371f7d094acbf02c83aa3940ff043f033b7cfe8
|
[
"BSD-2-Clause"
] | null | null | null |
src/include/cpu.hh
|
tomblackwhite/alpha-emu
|
a371f7d094acbf02c83aa3940ff043f033b7cfe8
|
[
"BSD-2-Clause"
] | null | null | null |
#pragma once
#include <bitset>
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <vector>
using std::uint16_t;
using std::uint8_t;
using std::int8_t;
using std::int16_t;
/* 寻址方式 6502为小端 */
enum class AddressMode {
// accumulator impiled single byte instruction
// operand is AC (implied single byte instruction)
accumulator,
// operand is address $HHLL
absolute,
// OPC $LLHH,X operand is address;
// effective address is address incremented by X with carry
absolute_x,
// OPC $LLHH,Y operand is address;
// effective address is address incremented by Y with carry **
absolute_y,
// OPC #$BB operand is byte BB
immediate,
// OPC operand implied
implied,
// OPC ($LLHH) operand is address;
// effective address is contents of word at address: C.w($HHLL)
indirect,
// OPC ($LL,X) operand is zeropage address;
// effective address is word in (LL + X, LL + X + 1), inc. without carry:
// C.w($00LL + X)
// An 8-bit zero-page address and the X register are added, without carry
//(if the addition overflows, the address wraps around within page 0).
x_indirect,
// OPC ($LL),Y operand is zeropage address;
// effective address is word in (LL, LL + 1) incremented by Y with carry:
// C.w($00LL) + Y
indirect_y,
// OPC $BB branch target is PC + signed offset BB ***
relative,
// OPC $LL operand is zeropage address (hi-byte is zero, address = $00LL)
zeropage,
// OPC $LL,X operand is zeropage address;
// effective address is address incremented by X without carry **
zeropage_x,
// OPC $LL,Y operand is zeropage address;
// effective address is address incremented by Y without carry **
zeropage_y
/*
* 所以不带进位的加法,不会影响到地址位的高位。
* 通常来说, increments of 16-bit addresses include a carry,
* increments of zeropage addresses don't.
* 这个和累加器的carry bit 无关
*/
};
enum class InstructionType {
ADC,AND,ASL,BCC,BCS,BEQ,BIT,BMI,BNE,BPL,BRK,BVC,BVS,CLC,CLD,CLI,CLV,CMP,
CPX,CPY,DEC,DEX,DEY,EOR,INC,INX,INY,JMP,JSR,LDA,LDX,LDY,LSR,NOP,ORA,PHA,
PHP,PLA,PLP,ROL,ROR,RTI,RTS,SBC,SEC,SED,SEI,STA,STX,STY,TAX,TAY,TSX,TXA,
TXS,TYA
};
//指令
struct Instruction {
//周期数
int m_cycleCount;
//指令的值
uint8_t m_operatorCode;
AddressMode m_addressMode;
InstructionType m_instructionType;
//执行实际的命令并设置相关寄存器
//在初始化时自动捕获当前上下文变量
std::function<void(uint16_t &memoryValue)> m_executor;
};
/*
** CPU负责读取内存中的命令
** 依次读取命令并执行命令并且设置相应
** 的寄存器,状态之类的。
** 需要根据命令读取内存中的数据,根据寻址方式,获取操作数,设置对应
** 的pc count
*/
class CPU {
private:
// memory instructions
/*
* status register
* N V - B D I Z C from bit 7 to bit 0
* N ... Negative
* V ... Overflow
* - ...ignored
* B ...Break
* D ... Decimal (use BCD for arithmetics)
* I ... Interrupt (IRQ disable)
* Z ... Zero
* C ... Carry
*/
std::bitset<8> m_SR = 0;
// accumulator register
uint8_t m_AC = 0;
// X register
uint8_t m_X = 0;
// Y register
uint8_t m_Y = 0;
// stack pointer
uint8_t m_statckPointer = 0;
// program counter
uint16_t m_PC = 0;
/*
* 内存
*/
std::vector<uint8_t> m_memory;
/*指令集*/
std::unordered_map<uint8_t, Instruction> m_instructionMap;
public:
//初始化指令集设置相关参数
void InitInstructionSet();
//开始执行内存中的代码
void Run();
/*
* 需要根据寻址模式获取值并且递增当前的program counter
* 首先获取opertor code 然后根据operator code 判断
* 寻址方式,获取实际的值
*/
uint8_t GetValue() { return 0; }
public:
CPU() { InitInstructionSet(); };
void test() {}
private:
auto NegativeFlag() { return m_SR[7]; }
auto OverflowFlag() { return m_SR[6]; }
auto BreakFlag() { return m_SR[4]; }
auto DecimalFlag() { return m_SR[3]; }
auto InterruptFlag() { return m_SR[2]; }
auto ZeroFlag() { return m_SR[1]; }
auto CarryFlag() { return m_SR[0]; }
/*寻址方式*/
/*获取指令使用的有效地址或者能直接使用的值*/
uint16_t GetAddressOrMemoryValue(AddressMode mode) {
uint16_t result = 0;
switch (mode) {
case AddressMode::accumulator: {
//取累加器中的值
result = m_X;
break;
}
case AddressMode::absolute: {
//取有效地址
result = m_memory[m_PC] + (m_memory[m_PC + 1] << 4);
m_PC += 2;
break;
}
case AddressMode::absolute_x: {
//取有效地址
result = m_memory[m_PC] + (m_memory[m_PC + 1] << 4) + m_X;
m_PC += 2;
break;
}
case AddressMode::absolute_y: {
//取有效地址
result = m_memory[m_PC] + (m_memory[m_PC + 1] << 4) + m_Y;
m_PC += 2;
break;
}
case AddressMode::immediate: {
//直接取值
result = m_memory[m_PC];
m_PC += 1;
break;
}
case AddressMode::implied: {
//直接返回
break;
}
case AddressMode::indirect: {
//取有效地址
uint16_t middleAddress = m_memory[m_PC] + (m_memory[m_PC + 1] << 4);
result = m_memory[middleAddress] + (m_memory[middleAddress + 1] << 4);
m_PC += 2;
break;
}
case AddressMode::x_indirect: {
//取有效地址
uint16_t middleAddress = m_memory[m_PC] + m_X;
middleAddress &= 0xFF;
result = m_memory[middleAddress] + (m_memory[middleAddress + 1] << 4);
m_PC += 1;
break;
}
case AddressMode::indirect_y: {
//取有效地址
uint16_t middleAddress = m_memory[m_PC] + (m_memory[m_PC + 1] << 4);
result = middleAddress + m_Y;
m_PC += 1;
break;
}
case AddressMode::relative: {
//取偏移量
result = m_memory[m_PC];
m_PC += 1;
break;
}
case AddressMode::zeropage: {
//取地址
result = m_memory[m_PC];
m_PC += 1;
break;
}
case AddressMode::zeropage_x: {
//取地址
result = m_memory[m_PC] + m_X;
result &= 0xFF;
m_PC += 1;
break;
}
case AddressMode::zeropage_y: {
//取地址
result = m_memory[m_PC] + m_Y;
result &= 0xFF;
m_PC += 1;
break;
}
default: {
static_assert(true, "未知的寻址类型");
}
}
return result;
}
/*获取根据寻址模式获取的值,获取指令执行时需要传的参数。*/
uint16_t GetInstructionParameter(uint16_t addressModeValue) { return 0;}
};
| 22.307407
| 76
| 0.618297
|
tomblackwhite
|
88279010049a442451ff74bcd4820086458b91df
| 7,105
|
hpp
|
C++
|
bits.hpp
|
YagoMello/bits
|
0d82845930ee71b78a995eca59d470ae29f58f02
|
[
"Apache-2.0"
] | null | null | null |
bits.hpp
|
YagoMello/bits
|
0d82845930ee71b78a995eca59d470ae29f58f02
|
[
"Apache-2.0"
] | null | null | null |
bits.hpp
|
YagoMello/bits
|
0d82845930ee71b78a995eca59d470ae29f58f02
|
[
"Apache-2.0"
] | null | null | null |
#ifndef BIT_HPP
#define BIT_HPP
/* Bit abstraction library
* Author: Yago T. de Mello
* e-mail: yago.t.mello@gmail.com
* Version: 2.6.0 2021-11-24
* License: Apache 2.0
* C++20
*/
/*
Copyright 2021 Yago Teodoro de Mello
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 <type_traits>
namespace bits {
// Used by bits::make_bit to select the correct template
// when reg_type is a pointer
template <typename T>
concept is_not_pointer = !std::is_pointer<typename std::remove_reference<T>::type>::value;
template <typename T>
concept is_const = std::is_const<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::value;
template <typename T>
concept is_not_const = !is_const<T>;
class bit {
public:
// The mutator and accessor function-pointers
using func_write_type = void (*)(const bool value);
using func_read_type = bool (*)();
// Allows the creation of uninitialized instances
bit() = default;
// Used by bits::make_bit
bit(
func_write_type func_write,
func_read_type func_read
) noexcept {
func_write_ = func_write;
func_read_ = func_read;
}
// Copy constructor
// Copies the value but not the function pointers
bit(const bit & obj) {
this->write(obj.read());
}
// Move constructor
// Makes no sense
bit(bit && obj) = delete;
// Sets the bit value
constexpr bit & operator =(const bool value) {
this->func_write_(value);
return *this;
}
// Forbid copy assignment
// forcing conversion to bool
bit & operator =(const bit &) = delete;
// Forces this object to use the other object's
// function pointers
constexpr void same_as(const bit & obj) noexcept {
this->func_write_ = obj.func_write_;
this->func_read_ = obj.func_read_;
}
// Gets the bit value
constexpr operator bool() const {
return this->func_read_();
}
// Explicit way to set the value to true
constexpr void set() {
this->func_write_(true);
}
// Explicit way to set the value to false
constexpr void clr() {
this->func_write_(false);
}
// Explicit way to set the value
constexpr void write(const bool value) {
this->func_write_(value);
}
// Explicit way to read the value
[[nodiscard]] constexpr bool read() const {
return this->func_read_();
}
// Template polymorphism generator
// Writes the value to a compile-time known variable
// If the variable is not const
template <auto & reg, auto offset>
static constexpr void default_write_static(const bool value)
requires is_not_const<decltype(reg)> {
using reg_type = std::remove_reference<decltype(reg)>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit masks to select/clear the bit
constexpr value_type mask_bit = value_type(1) << offset;
constexpr value_type mask_clear = ~mask_bit;
// The clear result is stored in a temporary
// to prevent unnecessary writes/reads to reg
// when reg is volatile
const value_type reg_clr = reg & mask_clear;
reg = reg_clr | value_type(value_type(value) * mask_bit);
}
// Template polymorphism generator
// If the variable is const, do not write to it
template <auto & reg, auto offset>
static constexpr void default_write_static(const bool)
requires is_const<decltype(reg)> { }
// Template polymorphism generator
// Reads the value of a compile-time known variable
template <auto & reg, auto offset>
static constexpr bool default_read_static() {
using reg_type = std::remove_reference<decltype(reg)>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit mask to select the bit
constexpr value_type mask_bit = value_type(1) << offset;
return (reg & mask_bit) != value_type(0);
}
// Template polymorphism generator
// Writes the value to a variable in a compile-time known pointer
template <auto * & reg_ptr, auto offset>
static constexpr void default_write_dynamic(const bool value)
requires is_not_const<decltype(reg_ptr)> {
using ptr_type = std::remove_reference<decltype(reg_ptr)>::type;
using reg_type = std::remove_pointer<ptr_type>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit masks to select/clear the bit
constexpr value_type mask_bit = value_type(1) << offset;
constexpr value_type mask_clear = ~mask_bit;
// The clear result is stored in a temporary
// to prevent unnecessary writes/reads to reg
// when reg is volatile
const value_type reg_clr = *reg_ptr & mask_clear;
*reg_ptr = reg_clr | value_type(value_type(value) * mask_bit);
}
template <auto & reg, auto offset>
static constexpr void default_write_dynamic(const bool)
requires is_const<decltype(reg)> { }
// Template polymorphism generator
// Reads the value of a variable in a compile-time known pointer
template <auto * & reg_ptr, auto offset>
static constexpr bool default_read_dynamic() {
using ptr_type = std::remove_reference<decltype(reg_ptr)>::type;
using reg_type = std::remove_pointer<ptr_type>::type;
using value_type = std::remove_volatile<reg_type>::type;
// Bit mask to select the bit
constexpr value_type mask_bit = value_type(1) << offset;
return (*reg_ptr & mask_bit) != value_type(0);
}
private:
// The function pointers
func_write_type func_write_;
func_read_type func_read_;
};
// Creates a bit object to access a compile-time known variable
template <auto & reg, auto offset>
bits::bit make_bit(
bit::func_write_type func_write = &bit::default_write_static<reg, offset>,
bit::func_read_type func_read = &bit::default_read_static<reg, offset>
) requires is_not_pointer<decltype(reg)> {
return bits::bit(func_write, func_read);
}
// Creates a bit object to access a variable in a compile-time known pointer
template <auto * & reg_ptr, auto offset>
bits::bit make_bit(
bit::func_write_type func_write = &bit::default_write_dynamic<reg_ptr, offset>,
bit::func_read_type func_read = &bit::default_read_dynamic<reg_ptr, offset>
) {
return bits::bit(func_write, func_read);
}
} // namespace bits
#endif // BIT_HPP
| 32.741935
| 117
| 0.666854
|
YagoMello
|
882840de7ca880ea01a5975c6dab60fba4d17445
| 15,689
|
cc
|
C++
|
src/global.cc
|
mk12/ledger
|
a285b2ad43f918cb80e24d2eef5b6739c325d769
|
[
"BSD-3-Clause"
] | null | null | null |
src/global.cc
|
mk12/ledger
|
a285b2ad43f918cb80e24d2eef5b6739c325d769
|
[
"BSD-3-Clause"
] | null | null | null |
src/global.cc
|
mk12/ledger
|
a285b2ad43f918cb80e24d2eef5b6739c325d769
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2003-2016, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "global.h"
#if HAVE_BOOST_PYTHON
#include "pyinterp.h"
#else
#include "session.h"
#endif
#include "item.h"
#include "journal.h"
#include "pool.h"
namespace ledger {
static bool args_only = false;
std::string _init_file;
global_scope_t::global_scope_t(char ** envp)
{
epoch = CURRENT_TIME();
#if HAVE_BOOST_PYTHON
if (! python_session.get()) {
python_session.reset(new ledger::python_interpreter_t);
session_ptr = python_session;
}
#else
session_ptr.reset(new session_t);
#endif
set_session_context(session_ptr.get());
// Create the report object, which maintains state relating to each
// command invocation. Because we're running from main(), the
// distinction between session and report doesn't really matter, but if
// a GUI were calling into Ledger it would have one session object per
// open document, with a separate report_t object for each report it
// generated.
report_stack.push_front(new report_t(*session_ptr));
scope_t::default_scope = &report();
scope_t::empty_scope = &empty_scope;
// Read the user's options, in the following order:
//
// 1. environment variables (LEDGER_<option>)
// 2. initialization file (~/.ledgerrc)
// 3. command-line (--option or -o)
//
// Before processing command-line options, we must notify the session object
// that such options are beginning, since options like -f cause a complete
// override of files found anywhere else.
if (! args_only) {
session().set_flush_on_next_data_file(true);
read_environment_settings(envp);
session().set_flush_on_next_data_file(true);
read_init();
} else {
session().HANDLER(price_db_).off();
}
TRACE_CTOR(global_scope_t, "");
}
global_scope_t::~global_scope_t()
{
TRACE_DTOR(global_scope_t);
// If memory verification is being performed (which can be very slow),
// clean up everything by closing the session and deleting the session
// object, and then shutting down the memory tracing subsystem.
// Otherwise, let it all leak because we're about to exit anyway.
IF_VERIFY() set_session_context(NULL);
#if HAVE_BOOST_PYTHON
python_session.reset();
#endif
}
void global_scope_t::parse_init(path init_file)
{
TRACE_START(init, 1, "Read initialization file");
parse_context_stack_t parsing_context;
parsing_context.push(init_file);
parsing_context.get_current().journal = session().journal.get();
parsing_context.get_current().scope = &report();
if (session().journal->read(parsing_context) > 0 ||
session().journal->auto_xacts.size() > 0 ||
session().journal->period_xacts.size() > 0) {
throw_(parse_error, _f("Transactions found in initialization file '%1%'")
% init_file);
}
TRACE_FINISH(init, 1);
}
void global_scope_t::read_init()
{
// if specified on the command line init_file_ is filled in
// global_scope_t::handle_debug_options. If it was specified on the command line
// fail if the file doesn't exist. If no init file was specified
// on the command-line then try the default values, but don't fail if there
// isn't one.
path init_file;
if (HANDLED(init_file_)) {
init_file=HANDLER(init_file_).str();
if (exists(init_file)) {
parse_init(init_file);
} else {
throw_(parse_error, _f("Could not find specified init file %1%") % init_file);
}
} else {
if (const char * home_var = std::getenv("HOME")) {
init_file = (path(home_var) / ".ledgerrc");
if (! exists(init_file)) {
init_file = ("./.ledgerrc");
}
} else {
init_file = ("./.ledgerrc");
}
}
if (exists(init_file)) {
parse_init(init_file);
}
}
char * global_scope_t::prompt_string()
{
static char prompt[32];
std::size_t i;
for (i = 0; i < report_stack.size(); i++)
prompt[i] = ']';
prompt[i++] = ' ';
prompt[i] = '\0';
return prompt;
}
void global_scope_t::report_error(const std::exception& err)
{
std::cout.flush(); // first display anything that was pending
if (caught_signal == NONE_CAUGHT) {
// Display any pending error context information
string context = error_context();
if (! context.empty())
std::cerr << context << std::endl;
std::cerr << _("Error: ") << err.what() << std::endl;
} else {
caught_signal = NONE_CAUGHT;
}
}
void global_scope_t::execute_command(strings_list args, bool at_repl)
{
session().set_flush_on_next_data_file(true);
// Process the command verb, arguments and options
if (at_repl) {
args = read_command_arguments(report(), args);
if (args.empty())
return;
}
strings_list::iterator arg = args.begin();
string verb = *arg++;
// Look for a precommand first, which is defined as any defined function
// whose name starts with "ledger_precmd_". The difference between a
// precommand and a regular command is that precommands ignore the journal
// data file completely, nor is the user's init file read.
//
// Here are some examples of pre-commands:
//
// parse STRING ; show how a value expression is parsed
// eval STRING ; simply evaluate a value expression
// format STRING ; show how a format string is parsed
//
// If such a command is found, create the output stream for the result and
// then invoke the command.
expr_t::func_t command;
bool is_precommand = false;
bind_scope_t bound_scope(*this, report());
if (bool(command = look_for_precommand(bound_scope, verb)))
is_precommand = true;
// If it is not a pre-command, then parse the user's ledger data at this
// time if not done already (i.e., if not at a REPL). Then patch up the
// report options based on the command verb.
if (! is_precommand) {
if (! at_repl)
session().read_journal_files();
report().normalize_options(verb);
if (! bool(command = look_for_command(bound_scope, verb)))
throw_(std::logic_error, _f("Unrecognized command '%1%'") % verb);
}
// Create the output stream (it might be a file, the console or a PAGER
// subprocess) and invoke the report command. The output stream is closed
// by the caller of this function.
report().output_stream
.initialize(report().HANDLED(output_) ?
optional<path>(path(report().HANDLER(output_).str())) :
optional<path>(),
report().HANDLED(pager_) ?
optional<path>(path(report().HANDLER(pager_).str())) :
optional<path>());
// Now that the output stream is initialized, report the options that will
// participate in this report, if the user specified --options
if (HANDLED(options))
report_options(report(), report().output_stream);
// Create an argument scope containing the report command's arguments, and
// then invoke the command. The bound scope causes lookups to happen
// first in the global scope, and then in the report scope.
call_scope_t command_args(bound_scope);
for (strings_list::iterator i = arg; i != args.end(); i++)
command_args.push_back(string_value(*i));
INFO_START(command, "Finished executing command");
command(command_args);
INFO_FINISH(command);
}
int global_scope_t::execute_command_wrapper(strings_list args, bool at_repl)
{
int status = 1;
try {
if (at_repl) push_report();
execute_command(args, at_repl);
if (at_repl) pop_report();
// If we've reached this point, everything succeeded fine. Ledger uses
// exceptions to notify of error conditions, so if you're using gdb,
// just type "catch throw" to find the source point of any error.
status = 0;
}
catch (const std::exception& err) {
if (at_repl) pop_report();
report_error(err);
}
return status;
}
void global_scope_t::report_options(report_t& report, std::ostream& out)
{
out << "==============================================================================="
<< std::endl;
out << "[Global scope options]" << std::endl;
HANDLER(args_only).report(out);
HANDLER(debug_).report(out);
HANDLER(init_file_).report(out);
HANDLER(script_).report(out);
HANDLER(trace_).report(out);
HANDLER(verbose).report(out);
HANDLER(verify).report(out);
HANDLER(verify_memory).report(out);
out << std::endl << "[Session scope options]" << std::endl;
report.session.report_options(out);
out << std::endl << "[Report scope options]" << std::endl;
report.report_options(out);
out << "==============================================================================="
<< std::endl;
}
option_t<global_scope_t> * global_scope_t::lookup_option(const char * p)
{
switch (*p) {
case 'a':
OPT(args_only);
break;
case 'd':
OPT(debug_);
break;
case 'h':
OPT_(help);
break;
case 'i':
OPT_(init_file_);
break;
case 'o':
OPT(options);
break;
case 's':
OPT(script_);
break;
case 't':
OPT(trace_);
break;
case 'v':
OPT_(verbose);
else OPT(verify);
else OPT(verify_memory);
else OPT(version);
break;
}
return NULL;
}
expr_t::ptr_op_t global_scope_t::lookup(const symbol_t::kind_t kind,
const string& name)
{
switch (kind) {
case symbol_t::FUNCTION:
if (option_t<global_scope_t> * handler = lookup_option(name.c_str()))
return MAKE_OPT_FUNCTOR(global_scope_t, handler);
break;
case symbol_t::OPTION:
if (option_t<global_scope_t> * handler = lookup_option(name.c_str()))
return MAKE_OPT_HANDLER(global_scope_t, handler);
break;
case symbol_t::PRECOMMAND: {
const char * p = name.c_str();
switch (*p) {
case 'p':
if (is_eq(p, "push"))
return MAKE_FUNCTOR(global_scope_t::push_command);
else if (is_eq(p, "pop"))
return MAKE_FUNCTOR(global_scope_t::pop_command);
break;
}
}
default:
break;
}
// If you're wondering how symbols from report() will be found, it's
// because of the bind_scope_t object in execute_command() below.
return NULL;
}
void global_scope_t::read_environment_settings(char * envp[])
{
TRACE_START(environment, 1, "Processed environment variables");
process_environment(const_cast<const char **>(envp), "LEDGER_", report());
#if 1
// These are here for backwards compatibility, but are deprecated.
if (const char * p = std::getenv("LEDGER")) {
if (! std::getenv("LEDGER_FILE"))
process_option("environ", "file", report(), p, "LEDGER");
}
if (const char * p = std::getenv("LEDGER_INIT")) {
if (! std::getenv("LEDGER_INIT_FILE"))
process_option("environ", "init-file", report(), p, "LEDGER_INIT");
}
if (const char * p = std::getenv("PRICE_HIST")) {
if (! std::getenv("LEDGER_PRICE_DB"))
process_option("environ", "price-db", report(), p, "PRICE_HIST");
}
if (const char * p = std::getenv("PRICE_EXP")) {
if (! std::getenv("LEDGER_PRICE_EXP"))
process_option("environ", "price-exp", report(), p, "PRICE_EXP");
}
#endif
TRACE_FINISH(environment, 1);
}
strings_list
global_scope_t::read_command_arguments(scope_t& scope, strings_list args)
{
TRACE_START(arguments, 1, "Processed command-line arguments");
strings_list remaining = process_arguments(args, scope);
TRACE_FINISH(arguments, 1);
return remaining;
}
void global_scope_t::normalize_session_options()
{
#if LOGGING_ON
INFO("Initialization file is " << HANDLER(init_file_).str());
INFO("Price database is " << session().HANDLER(price_db_).str());
foreach (const path& pathname, session().HANDLER(file_).data_files)
INFO("Journal file is " << pathname.string());
#endif // LOGGING_ON
}
expr_t::func_t global_scope_t::look_for_precommand(scope_t& scope,
const string& verb)
{
if (expr_t::ptr_op_t def = scope.lookup(symbol_t::PRECOMMAND, verb))
return def->as_function();
else
return expr_t::func_t();
}
expr_t::func_t global_scope_t::look_for_command(scope_t& scope,
const string& verb)
{
if (expr_t::ptr_op_t def = scope.lookup(symbol_t::COMMAND, verb))
return def->as_function();
else
return expr_t::func_t();
}
void global_scope_t::visit_man_page() const
{
#if !defined(_WIN32) && !defined(__CYGWIN__)
int pid = fork();
if (pid < 0) {
throw std::logic_error(_("Failed to fork child process"));
}
else if (pid == 0) { // child
execlp("man", "man", "1", "ledger", NULL);
// We should never, ever reach here
perror("execlp: man");
exit(1);
}
int status = -1;
wait(&status);
#endif
exit(0); // parent
}
void handle_debug_options(int argc, char * argv[])
{
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
if (std::strcmp(argv[i], "--args-only") == 0) {
args_only = true;
}
else if (std::strcmp(argv[i], "--verify-memory") == 0) {
#if VERIFY_ON
verify_enabled = true;
_log_level = LOG_DEBUG;
_log_category = "memory\\.counts";
#endif
}
else if (std::strcmp(argv[i], "--verify") == 0) {
#if VERIFY_ON
verify_enabled = true;
#endif
}
else if (std::strcmp(argv[i], "--verbose") == 0 ||
std::strcmp(argv[i], "-v") == 0) {
#if LOGGING_ON
_log_level = LOG_INFO;
#endif
}
else if (i + 1 < argc && std::strcmp(argv[i], "--init-file") == 0) {
_init_file = argv[i + 1];
i++;
}
else if (i + 1 < argc && std::strcmp(argv[i], "--debug") == 0) {
#if DEBUG_ON
_log_level = LOG_DEBUG;
_log_category = argv[i + 1];
i++;
#endif
}
else if (i + 1 < argc && std::strcmp(argv[i], "--trace") == 0) {
#if TRACING_ON
_log_level = LOG_TRACE;
try {
_trace_level = boost::lexical_cast<uint16_t>(argv[i + 1]);
}
catch (const boost::bad_lexical_cast&) {
throw std::logic_error(_("Argument to --trace must be an integer"));
}
i++;
#endif
}
}
}
}
} // namespace ledger
| 29.770398
| 90
| 0.648161
|
mk12
|
882c699df89729f87108858b2ed7f0db4c1a6597
| 3,098
|
hpp
|
C++
|
include/ghost/connection/Reader.hpp
|
mathieunassar/ghostmodule
|
8e9a9e958ec3cfa3494b49211920e3f669a9c8bd
|
[
"Apache-2.0"
] | 2
|
2019-10-05T06:51:49.000Z
|
2020-10-11T11:20:59.000Z
|
include/ghost/connection/Reader.hpp
|
mathieunassar/ghostmodule
|
8e9a9e958ec3cfa3494b49211920e3f669a9c8bd
|
[
"Apache-2.0"
] | 24
|
2019-06-19T21:33:23.000Z
|
2020-10-04T11:36:41.000Z
|
include/ghost/connection/Reader.hpp
|
mathieunassar/ghostmodule
|
8e9a9e958ec3cfa3494b49211920e3f669a9c8bd
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019 Mathieu Nassar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GHOST_READER_HPP
#define GHOST_READER_HPP
#include <ghost/connection/ReaderSink.hpp>
#include <memory>
namespace ghost
{
/**
* @brief Interface for reading through a connection.
*
* Reader objects are obtained from connection objects.
*
* The type of message being read by the Reader is provided
* by the template parameter "MessageType", which can be one of
* the following:
* - a Google Protobuf message type (including google.protobuf.Any)
* - A user-defined object type derived from the Message class.
*
* @tparam MessageType the type of messages that will be read
* by the Reader.
*/
template <typename MessageType>
class Reader
{
public:
virtual ~Reader() = default;
/**
* Creates a ghost::Reader bound to the provided connection.
* @return a ghost::Reader object that can read from the provided connection.
*/
static std::shared_ptr<ghost::Reader<MessageType>> create(const std::shared_ptr<ghost::ReaderSink>& sink,
bool blocking);
/**
* @brief Reads a message from the reader.
*
* If a message handler was added to the connection bound to this reader,
* then calling read will always return false.
* Read will also return false if the connection was set to not block during
* I/O calls.
* Finally, the method will return false if the incoming message does not match
* the expected type MessageType.
* In all the other cases, this method returns true.
*
* @param message the message to read (input)
* @return true if a message of the given type was actually read
* @return false if no message was read during this call.
*/
virtual bool read(MessageType& message) = 0;
/**
* @brief Gets the last read message.
*
* @param message the message to read (input)
* @return true if a message of the given type was actually read
* @return false if no message could be returned
*/
virtual bool lastRead(MessageType& message) = 0;
};
template <>
std::shared_ptr<ghost::Reader<google::protobuf::Any>> ghost::Reader<google::protobuf::Any>::create(
const std::shared_ptr<ghost::ReaderSink>& sink, bool blocking);
} // namespace ghost
#include <ghost/connection/internal/GenericReader.hpp>
// Template definition //
template <typename MessageType>
std::shared_ptr<ghost::Reader<MessageType>> ghost::Reader<MessageType>::create(
const std::shared_ptr<ghost::ReaderSink>& sink, bool blocking)
{
return std::make_shared<ghost::internal::GenericReader<MessageType>>(sink, blocking);
}
#endif // GHOST_WRITER_HPP
| 32.610526
| 106
| 0.732085
|
mathieunassar
|
882ef531b862ea0fc1050a04cd5bf921230d4b02
| 7,330
|
cpp
|
C++
|
src/grt/src/Grid.cpp
|
erictaur/OpenROAD
|
438dbb41316fc7fe27e2c405078aa465395125ba
|
[
"BSD-3-Clause"
] | 525
|
2019-11-20T00:21:42.000Z
|
2022-03-31T05:38:44.000Z
|
src/grt/src/Grid.cpp
|
erictaur/OpenROAD
|
438dbb41316fc7fe27e2c405078aa465395125ba
|
[
"BSD-3-Clause"
] | 741
|
2019-11-20T15:19:38.000Z
|
2022-03-31T23:09:17.000Z
|
src/grt/src/Grid.cpp
|
erictaur/OpenROAD
|
438dbb41316fc7fe27e2c405078aa465395125ba
|
[
"BSD-3-Clause"
] | 215
|
2019-11-25T13:37:43.000Z
|
2022-03-28T00:51:29.000Z
|
/////////////////////////////////////////////////////////////////////////////
//
// BSD 3-Clause License
//
// Copyright (c) 2019, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////
#include "Grid.h"
#include <complex>
namespace grt {
void Grid::init(const long lower_left_x,
const long lower_left_y,
const long upper_right_x,
const long upper_right_y,
const long tile_width,
const long tile_height,
const int x_grids,
const int y_grids,
const bool perfect_regular_x,
const bool perfect_regular_y,
const int num_layers,
const std::vector<int>& spacings,
const std::vector<int>& min_widths,
const std::vector<int>& horizontal_capacities,
const std::vector<int>& vertical_capacities,
const std::map<int, std::vector<odb::Rect>>& obstructions)
{
lower_left_x_ = lower_left_x;
lower_left_y_ = lower_left_y;
upper_right_x_ = upper_right_x;
upper_right_y_ = upper_right_y;
tile_width_ = tile_width;
tile_height_ = tile_height;
x_grids_ = x_grids;
y_grids_ = y_grids;
perfect_regular_x_ = perfect_regular_x;
perfect_regular_y_ = perfect_regular_y;
num_layers_ = num_layers;
spacings_ = spacings;
min_widths_ = min_widths;
horizontal_edges_capacities_ = horizontal_capacities;
vertical_edges_capacities_ = vertical_capacities;
obstructions_ = obstructions;
}
void Grid::clear()
{
spacings_.clear();
min_widths_.clear();
horizontal_edges_capacities_.clear();
vertical_edges_capacities_.clear();
obstructions_.clear();
}
odb::Point Grid::getPositionOnGrid(const odb::Point& position)
{
int x = position.x();
int y = position.y();
// Computing x and y center:
int gcell_id_x = floor((float) ((x - lower_left_x_) / tile_width_));
int gcell_id_y = floor((float) ((y - lower_left_y_) / tile_height_));
if (gcell_id_x >= x_grids_)
gcell_id_x--;
if (gcell_id_y >= y_grids_)
gcell_id_y--;
int center_x = (gcell_id_x * tile_width_) + (tile_width_ / 2) + lower_left_x_;
int center_y
= (gcell_id_y * tile_height_) + (tile_height_ / 2) + lower_left_y_;
return odb::Point(center_x, center_y);
}
std::pair<Grid::TILE, Grid::TILE> Grid::getBlockedTiles(
const odb::Rect& obstruction,
odb::Rect& first_tile_bds,
odb::Rect& last_tile_bds)
{
std::pair<TILE, TILE> tiles;
TILE first_tile;
TILE last_tile;
odb::Point lower = obstruction.ll(); // lower bound of obstruction
odb::Point upper = obstruction.ur(); // upper bound of obstruction
lower
= getPositionOnGrid(lower); // translate lower bound of obstruction to
// the center of the tile where it is inside
upper
= getPositionOnGrid(upper); // translate upper bound of obstruction to
// the center of the tile where it is inside
// Get x and y indices of first blocked tile
first_tile._x = (lower.x() - (getTileWidth() / 2)) / getTileWidth();
first_tile._y = (lower.y() - (getTileHeight() / 2)) / getTileHeight();
// Get x and y indices of last blocked tile
last_tile._x = (upper.x() - (getTileWidth() / 2)) / getTileWidth();
last_tile._y = (upper.y() - (getTileHeight() / 2)) / getTileHeight();
tiles = std::make_pair(first_tile, last_tile);
odb::Point ll_first_tile = odb::Point(lower.x() - (getTileWidth() / 2),
lower.y() - (getTileHeight() / 2));
odb::Point ur_first_tile = odb::Point(lower.x() + (getTileWidth() / 2),
lower.y() + (getTileHeight() / 2));
odb::Point ll_last_tile = odb::Point(upper.x() - (getTileWidth() / 2),
upper.y() - (getTileHeight() / 2));
odb::Point ur_last_tile = odb::Point(upper.x() + (getTileWidth() / 2),
upper.y() + (getTileHeight() / 2));
if ((upper_right_x_ - ur_last_tile.x()) / getTileWidth() < 1) {
ur_last_tile.setX(upper_right_x_);
}
if ((upper_right_y_ - ur_last_tile.y()) / getTileHeight() < 1) {
ur_last_tile.setY(upper_right_y_);
}
first_tile_bds = odb::Rect(ll_first_tile, ur_first_tile);
last_tile_bds = odb::Rect(ll_last_tile, ur_last_tile);
return tiles;
}
int Grid::computeTileReduce(const odb::Rect& obs,
const odb::Rect& tile,
int track_space,
bool first,
odb::dbTechLayerDir direction)
{
int reduce = -1;
if (direction == odb::dbTechLayerDir::VERTICAL) {
if (obs.xMin() >= tile.xMin() && obs.xMax() <= tile.xMax()) {
reduce = ceil(std::abs(obs.xMax() - obs.xMin()) / track_space);
} else if (first) {
reduce = ceil(std::abs(tile.xMax() - obs.xMin()) / track_space);
} else {
reduce = ceil(std::abs(obs.xMax() - tile.xMin()) / track_space);
}
} else {
if (obs.yMin() >= tile.yMin() && obs.yMax() <= tile.yMax()) {
reduce = ceil(std::abs(obs.yMax() - obs.yMin()) / track_space);
} else if (first) {
reduce = ceil(std::abs(tile.yMax() - obs.yMin()) / track_space);
} else {
reduce = ceil(std::abs(obs.yMax() - tile.yMin()) / track_space);
}
}
return reduce;
}
odb::Point Grid::getMiddle()
{
return odb::Point((lower_left_x_ + (upper_right_x_ - lower_left_x_) / 2.0),
(lower_left_y_ + (upper_right_y_ - lower_left_y_) / 2.0));
}
odb::Rect Grid::getGridArea() const
{
return odb::Rect(
lower_left_x_, lower_left_y_, upper_right_x_, upper_right_y_);
}
} // namespace grt
| 36.467662
| 80
| 0.629059
|
erictaur
|
8830fb955023a846e2bba1fe3f46edf3e85ebf78
| 1,796
|
hpp
|
C++
|
src/cc/Books/ElementsOfProgrammingInterviews/reference/ch16.hpp
|
nuggetwheat/study
|
1e438a995c3c6ce783af9ae6a537c349afeedbb8
|
[
"MIT"
] | null | null | null |
src/cc/Books/ElementsOfProgrammingInterviews/reference/ch16.hpp
|
nuggetwheat/study
|
1e438a995c3c6ce783af9ae6a537c349afeedbb8
|
[
"MIT"
] | null | null | null |
src/cc/Books/ElementsOfProgrammingInterviews/reference/ch16.hpp
|
nuggetwheat/study
|
1e438a995c3c6ce783af9ae6a537c349afeedbb8
|
[
"MIT"
] | null | null | null |
#ifndef Books_ElementsOfProgrammingInterviews_reference_ch16_hpp
#define Books_ElementsOfProgrammingInterviews_reference_ch16_hpp
#include "Common/Tree.hpp"
#include <array>
#include <cstdlib>
#include <memory>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
namespace reference {
extern void MoveTowerOfHanoi(std::vector<std::stack<int>> &pegs, int to_peg);
extern void MoveTowerOfHanoiIterative(std::vector<std::stack<int>> &pegs, int to_peg);
extern std::vector<std::vector<int>> NQueens(int n);
extern std::vector<std::vector<int>> NQueensIterative(int n);
extern std::vector<std::vector<int>> Permutations(std::vector<int> A);
extern std::vector<std::vector<int>> PermutationsIterative(std::vector<int> A);
extern std::vector<std::vector<int>> GeneratePowerSet(const std::vector<int> &input);
extern std::vector<std::vector<int>> GeneratePowerSetIterative(const std::vector<int> &input);
extern std::vector<std::vector<int>> Combinations(int n, int k);
extern std::vector<std::vector<int>> CombinationsIterative(int n, int k);
extern std::vector<std::string> GenerateBalancedParenthesis(int num_pairs);
extern std::vector<std::string> GenerateBalancedParenthesisIterative(int num_pairs);
extern std::vector<std::vector<std::string>> PalindromePartitioning(const std::string &input);
extern std::vector<std::unique_ptr<study::BSTNode<int>>> GenerateAllBinaryTrees(int num_nodes);
extern bool SolveSudoku(std::vector<std::vector<int>> *partial_assignment);
extern std::vector<int> GrayCode(int num_bits);
extern std::vector<int> GrayCodeIterative(int num_bits);
extern int ComputeDiameter(const std::unique_ptr<study::BSTNode<int>> &tree);
}
#endif // Books_ElementsOfProgrammingInterviews_reference_ch16_hpp
| 32.071429
| 97
| 0.763363
|
nuggetwheat
|
883143a10ab0b7c390135c75b87f00ae8742b0ce
| 1,504
|
cpp
|
C++
|
src/Zelta/Concurrency/Worker.cpp
|
RafaelGC/ese
|
95868d2f7221334271d4a74ef38b2ed3478a8b91
|
[
"MIT"
] | 1
|
2018-01-28T21:35:14.000Z
|
2018-01-28T21:35:14.000Z
|
src/Zelta/Concurrency/Worker.cpp
|
RafaelGC/ese
|
95868d2f7221334271d4a74ef38b2ed3478a8b91
|
[
"MIT"
] | 1
|
2017-04-05T00:41:53.000Z
|
2017-04-05T00:41:53.000Z
|
src/Zelta/Concurrency/Worker.cpp
|
rafaelgc/ESE
|
95868d2f7221334271d4a74ef38b2ed3478a8b91
|
[
"MIT"
] | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Worker.cpp
* Author: rafa
*
* Created on January 14, 2018, 3:42 PM
*/
#include <thread>
#include <Zelta/Concurrency/Worker.hpp>
#include <Zelta/Concurrency/Task.hpp>
namespace zt {
Worker::Worker(std::condition_variable& poolCv) : uniqueLock(mtx) {
task = nullptr;
this->poolCv = &poolCv;
thread = std::thread(&Worker::work, this);
stopped = false;
}
Worker::~Worker() {
}
bool Worker::setTask(Task& task) {
if (isFree()) {
this->task = &task;
cv.notify_all();
return true;
}
return false;
}
bool Worker::isFree() const {
return !task;
}
void Worker::work() {
while (!stopped) {
if (!isFree()) {
if (this->task->work()) {
task = nullptr;
// When the task is done (it returns true) we notify
// the pool so that it knows there is a free worker.
if (poolCv) {
poolCv->notify_all();
cv.wait(uniqueLock);
}
}
}
}
}
void Worker::join() {
thread.join();
}
void Worker::stop() {
stopped = true;
}
}
| 20.888889
| 79
| 0.490691
|
RafaelGC
|
88324f4e7f3faa4b463c0f8817ec3aca16b6bcd6
| 15,738
|
cpp
|
C++
|
VirtualBox-5.0.0/src/VBox/Main/src-all/AutoCaller.cpp
|
egraba/vbox_openbsd
|
6cb82f2eed1fa697d088cecc91722b55b19713c2
|
[
"MIT"
] | 1
|
2015-04-30T14:18:45.000Z
|
2015-04-30T14:18:45.000Z
|
VirtualBox-5.0.0/src/VBox/Main/src-all/AutoCaller.cpp
|
egraba/vbox_openbsd
|
6cb82f2eed1fa697d088cecc91722b55b19713c2
|
[
"MIT"
] | null | null | null |
VirtualBox-5.0.0/src/VBox/Main/src-all/AutoCaller.cpp
|
egraba/vbox_openbsd
|
6cb82f2eed1fa697d088cecc91722b55b19713c2
|
[
"MIT"
] | null | null | null |
/* $Id: AutoCaller.cpp $ */
/** @file
*
* VirtualBox object state implementation
*/
/*
* Copyright (C) 2006-2014 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <iprt/semaphore.h>
#include "VirtualBoxBase.h"
#include "AutoCaller.h"
#include "Logging.h"
////////////////////////////////////////////////////////////////////////////////
//
// ObjectState methods
//
////////////////////////////////////////////////////////////////////////////////
ObjectState::ObjectState() : mStateLock(LOCKCLASS_OBJECTSTATE)
{
AssertFailed();
}
ObjectState::ObjectState(VirtualBoxBase *aObj) :
mObj(aObj), mStateLock(LOCKCLASS_OBJECTSTATE)
{
Assert(mObj);
mState = NotReady;
mStateChangeThread = NIL_RTTHREAD;
mCallers = 0;
mZeroCallersSem = NIL_RTSEMEVENT;
mInitUninitSem = NIL_RTSEMEVENTMULTI;
mInitUninitWaiters = 0;
}
ObjectState::~ObjectState()
{
Assert(mInitUninitWaiters == 0);
Assert(mInitUninitSem == NIL_RTSEMEVENTMULTI);
if (mZeroCallersSem != NIL_RTSEMEVENT)
RTSemEventDestroy(mZeroCallersSem);
mCallers = 0;
mStateChangeThread = NIL_RTTHREAD;
mState = NotReady;
mObj = NULL;
}
ObjectState::State ObjectState::getState()
{
AutoReadLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
return mState;
}
/**
* Increments the number of calls to this object by one.
*
* After this method succeeds, it is guaranteed that the object will remain
* in the Ready (or in the Limited) state at least until #releaseCaller() is
* called.
*
* This method is intended to mark the beginning of sections of code within
* methods of COM objects that depend on the readiness (Ready) state. The
* Ready state is a primary "ready to serve" state. Usually all code that
* works with component's data depends on it. On practice, this means that
* almost every public method, setter or getter of the object should add
* itself as an object's caller at the very beginning, to protect from an
* unexpected uninitialization that may happen on a different thread.
*
* Besides the Ready state denoting that the object is fully functional,
* there is a special Limited state. The Limited state means that the object
* is still functional, but its functionality is limited to some degree, so
* not all operations are possible. The @a aLimited argument to this method
* determines whether the caller represents this limited functionality or
* not.
*
* This method succeeds (and increments the number of callers) only if the
* current object's state is Ready. Otherwise, it will return E_ACCESSDENIED
* to indicate that the object is not operational. There are two exceptions
* from this rule:
* <ol>
* <li>If the @a aLimited argument is |true|, then this method will also
* succeed if the object's state is Limited (or Ready, of course).
* </li>
* <li>If this method is called from the same thread that placed
* the object to InInit or InUninit state (i.e. either from within the
* AutoInitSpan or AutoUninitSpan scope), it will succeed as well (but
* will not increase the number of callers).
* </li>
* </ol>
*
* Normally, calling addCaller() never blocks. However, if this method is
* called by a thread created from within the AutoInitSpan scope and this
* scope is still active (i.e. the object state is InInit), it will block
* until the AutoInitSpan destructor signals that it has finished
* initialization.
*
* When this method returns a failure, the caller must not use the object
* and should return the failed result code to its own caller.
*
* @param aLimited |true| to add a limited caller.
*
* @return S_OK on success or E_ACCESSDENIED on failure.
*
* @sa #releaseCaller()
*/
HRESULT ObjectState::addCaller(bool aLimited /* = false */)
{
AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
HRESULT rc = E_ACCESSDENIED;
if (mState == Ready || (aLimited && mState == Limited))
{
/* if Ready or allows Limited, increase the number of callers */
++mCallers;
rc = S_OK;
}
else
if (mState == InInit || mState == InUninit)
{
if (mStateChangeThread == RTThreadSelf())
{
/* Called from the same thread that is doing AutoInitSpan or
* AutoUninitSpan, just succeed */
rc = S_OK;
}
else if (mState == InInit)
{
/* addCaller() is called by a "child" thread while the "parent"
* thread is still doing AutoInitSpan/AutoReinitSpan, so wait for
* the state to become either Ready/Limited or InitFailed (in
* case of init failure).
*
* Note that we increase the number of callers anyway -- to
* prevent AutoUninitSpan from early completion if we are
* still not scheduled to pick up the posted semaphore when
* uninit() is called.
*/
++mCallers;
/* lazy semaphore creation */
if (mInitUninitSem == NIL_RTSEMEVENTMULTI)
{
RTSemEventMultiCreate(&mInitUninitSem);
Assert(mInitUninitWaiters == 0);
}
++mInitUninitWaiters;
LogFlowThisFunc(("Waiting for AutoInitSpan/AutoReinitSpan to finish...\n"));
stateLock.release();
RTSemEventMultiWait(mInitUninitSem, RT_INDEFINITE_WAIT);
stateLock.acquire();
if (--mInitUninitWaiters == 0)
{
/* destroy the semaphore since no more necessary */
RTSemEventMultiDestroy(mInitUninitSem);
mInitUninitSem = NIL_RTSEMEVENTMULTI;
}
if (mState == Ready || (aLimited && mState == Limited))
rc = S_OK;
else
{
Assert(mCallers != 0);
--mCallers;
if (mCallers == 0 && mState == InUninit)
{
/* inform AutoUninitSpan ctor there are no more callers */
RTSemEventSignal(mZeroCallersSem);
}
}
}
}
if (FAILED(rc))
{
if (mState == Limited)
rc = mObj->setError(rc, "The object functionality is limited");
else
rc = mObj->setError(rc, "The object is not ready");
}
return rc;
}
/**
* Decreases the number of calls to this object by one.
*
* Must be called after every #addCaller() when protecting the object
* from uninitialization is no more necessary.
*/
void ObjectState::releaseCaller()
{
AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
if (mState == Ready || mState == Limited)
{
/* if Ready or Limited, decrease the number of callers */
AssertMsgReturn(mCallers != 0, ("mCallers is ZERO!"), (void) 0);
--mCallers;
return;
}
if (mState == InInit || mState == InUninit)
{
if (mStateChangeThread == RTThreadSelf())
{
/* Called from the same thread that is doing AutoInitSpan or
* AutoUninitSpan: just succeed */
return;
}
if (mState == InUninit)
{
/* the caller is being released after AutoUninitSpan has begun */
AssertMsgReturn(mCallers != 0, ("mCallers is ZERO!"), (void) 0);
--mCallers;
if (mCallers == 0)
/* inform the Auto*UninitSpan ctor there are no more callers */
RTSemEventSignal(mZeroCallersSem);
return;
}
}
AssertMsgFailed(("mState = %d!", mState));
}
bool ObjectState::autoInitSpanConstructor(ObjectState::State aExpectedState)
{
AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
if (mState == aExpectedState)
{
setState(InInit);
return true;
}
else
return false;
}
void ObjectState::autoInitSpanDestructor(State aNewState)
{
AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
Assert(mState == InInit);
if (mCallers > 0 && mInitUninitWaiters > 0)
{
/* We have some pending addCaller() calls on other threads (created
* during InInit), signal that InInit is finished and they may go on. */
RTSemEventMultiSignal(mInitUninitSem);
}
setState(aNewState);
}
ObjectState::State ObjectState::autoUninitSpanConstructor()
{
AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
Assert(mState != InInit);
if (mState == NotReady)
{
/* do nothing if already uninitialized */
return mState;
}
else if (mState == InUninit)
{
/* Another thread has already started uninitialization, wait for its
* completion. This is necessary to make sure that when this method
* returns, the object state is well-defined (NotReady). */
/* lazy semaphore creation */
if (mInitUninitSem == NIL_RTSEMEVENTMULTI)
{
RTSemEventMultiCreate(&mInitUninitSem);
Assert(mInitUninitWaiters == 0);
}
++mInitUninitWaiters;
LogFlowFunc(("{%p}: Waiting for AutoUninitSpan to finish...\n", mObj));
stateLock.release();
RTSemEventMultiWait(mInitUninitSem, RT_INDEFINITE_WAIT);
stateLock.acquire();
if (--mInitUninitWaiters == 0)
{
/* destroy the semaphore since no more necessary */
RTSemEventMultiDestroy(mInitUninitSem);
mInitUninitSem = NIL_RTSEMEVENTMULTI;
}
/* the other thread set it to NotReady */
return mState;
}
/* go to InUninit to prevent from adding new callers */
setState(InUninit);
/* wait for already existing callers to drop to zero */
if (mCallers > 0)
{
/* lazy creation */
Assert(mZeroCallersSem == NIL_RTSEMEVENT);
RTSemEventCreate(&mZeroCallersSem);
/* wait until remaining callers release the object */
LogFlowFunc(("{%p}: Waiting for callers (%d) to drop to zero...\n",
mObj, mCallers));
stateLock.release();
RTSemEventWait(mZeroCallersSem, RT_INDEFINITE_WAIT);
}
return mState;
}
void ObjectState::autoUninitSpanDestructor()
{
AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
Assert(mState == InUninit);
setState(NotReady);
}
void ObjectState::setState(ObjectState::State aState)
{
Assert(mState != aState);
mState = aState;
mStateChangeThread = RTThreadSelf();
}
////////////////////////////////////////////////////////////////////////////////
//
// AutoInitSpan methods
//
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a smart initialization span object that places the object to
* InInit state.
*
* Please see the AutoInitSpan class description for more info.
*
* @param aObj |this| pointer of the managed VirtualBoxBase object whose
* init() method is being called.
* @param aResult Default initialization result.
*/
AutoInitSpan::AutoInitSpan(VirtualBoxBase *aObj,
Result aResult /* = Failed */)
: mObj(aObj),
mResult(aResult),
mOk(false)
{
Assert(mObj);
mOk = mObj->getObjectState().autoInitSpanConstructor(ObjectState::NotReady);
AssertReturnVoid(mOk);
}
/**
* Places the managed VirtualBoxBase object to Ready/Limited state if the
* initialization succeeded or partly succeeded, or places it to InitFailed
* state and calls the object's uninit() method.
*
* Please see the AutoInitSpan class description for more info.
*/
AutoInitSpan::~AutoInitSpan()
{
/* if the state was other than NotReady, do nothing */
if (!mOk)
return;
ObjectState::State newState;
if (mResult == Succeeded)
newState = ObjectState::Ready;
else if (mResult == Limited)
newState = ObjectState::Limited;
else
newState = ObjectState::InitFailed;
mObj->getObjectState().autoInitSpanDestructor(newState);
if (newState == ObjectState::InitFailed)
{
/* call uninit() to let the object uninit itself after failed init() */
mObj->uninit();
/* Note: the object may no longer exist here (for example, it can call
* the destructor in uninit()) */
}
}
// AutoReinitSpan methods
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a smart re-initialization span object and places the object to
* InInit state.
*
* Please see the AutoInitSpan class description for more info.
*
* @param aObj |this| pointer of the managed VirtualBoxBase object whose
* re-initialization method is being called.
*/
AutoReinitSpan::AutoReinitSpan(VirtualBoxBase *aObj)
: mObj(aObj),
mSucceeded(false),
mOk(false)
{
Assert(mObj);
mOk = mObj->getObjectState().autoInitSpanConstructor(ObjectState::Limited);
AssertReturnVoid(mOk);
}
/**
* Places the managed VirtualBoxBase object to Ready state if the
* re-initialization succeeded (i.e. #setSucceeded() has been called) or back to
* Limited state otherwise.
*
* Please see the AutoInitSpan class description for more info.
*/
AutoReinitSpan::~AutoReinitSpan()
{
/* if the state was other than Limited, do nothing */
if (!mOk)
return;
ObjectState::State newState;
if (mSucceeded)
newState = ObjectState::Ready;
else
newState = ObjectState::Limited;
mObj->getObjectState().autoInitSpanDestructor(newState);
/** @todo r=klaus: this is like the initial init() failure, but in this
* place uninit() is NOT called. Makes only limited sense. */
}
// AutoUninitSpan methods
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a smart uninitialization span object and places this object to
* InUninit state.
*
* Please see the AutoInitSpan class description for more info.
*
* @note This method blocks the current thread execution until the number of
* callers of the managed VirtualBoxBase object drops to zero!
*
* @param aObj |this| pointer of the VirtualBoxBase object whose uninit()
* method is being called.
*/
AutoUninitSpan::AutoUninitSpan(VirtualBoxBase *aObj)
: mObj(aObj),
mInitFailed(false),
mUninitDone(false)
{
Assert(mObj);
ObjectState::State state;
state = mObj->getObjectState().autoUninitSpanConstructor();
if (state == ObjectState::InitFailed)
mInitFailed = true;
else if (state == ObjectState::NotReady)
mUninitDone = true;
}
/**
* Places the managed VirtualBoxBase object to the NotReady state.
*/
AutoUninitSpan::~AutoUninitSpan()
{
/* do nothing if already uninitialized */
if (mUninitDone)
return;
mObj->getObjectState().autoUninitSpanDestructor();
}
/**
* Marks the uninitializion as succeeded.
*
* Same as the destructor, and makes the destructor do nothing.
*/
void AutoUninitSpan::setSucceeded()
{
/* do nothing if already uninitialized */
if (mUninitDone)
return;
mObj->getObjectState().autoUninitSpanDestructor();
mUninitDone = true;
}
| 30.559223
| 88
| 0.627208
|
egraba
|
88337aa39dc78f9e6d0ab600afd2499272c41cf2
| 1,265
|
cpp
|
C++
|
benchmarks/Matmul/matmul_cpp.cpp
|
Cwc-Lib/Cello
|
139e04c3b2cc2c6a68f96637e0c53286ca5792c0
|
[
"BSD-2-Clause-FreeBSD"
] | 4,067
|
2015-05-16T22:57:52.000Z
|
2022-03-30T05:40:04.000Z
|
benchmarks/Matmul/matmul_cpp.cpp
|
Cwc-Lib/Cello
|
139e04c3b2cc2c6a68f96637e0c53286ca5792c0
|
[
"BSD-2-Clause-FreeBSD"
] | 59
|
2015-06-17T09:51:27.000Z
|
2021-09-24T20:15:21.000Z
|
benchmarks/Matmul/matmul_cpp.cpp
|
Cwc-Lib/Cello
|
139e04c3b2cc2c6a68f96637e0c53286ca5792c0
|
[
"BSD-2-Clause-FreeBSD"
] | 308
|
2015-05-16T11:33:08.000Z
|
2022-03-18T00:26:28.000Z
|
#include <stdlib.h>
class Matrix {
public:
size_t n;
double** d;
Matrix(int n);
~Matrix();
};
Matrix::Matrix(int n) {
n = n;
d = (double**)malloc(n * sizeof(double*));
for (int i = 0; i < n; ++i) {
d[i] = (double*)calloc(n, sizeof(double));
}
}
Matrix::~Matrix() {
for (int i = 0; i < n; ++i) free(d[i]);
free(d);
}
static Matrix* Matrix_Gen(int n) {
Matrix* m = new Matrix(n);
double tmp = 1.0 / n / n;
for (int i = 0; i < m->n; ++i) {
for (int j = 0; j < m->n; ++j) {
m->d[i][j] = tmp * (i - j) * (i + j);
}
}
return m;
}
static Matrix* Matrix_Mul(Matrix* m0, Matrix* m1) {
Matrix* a = m0;
Matrix* b = m1;
Matrix* m = new Matrix(a->n);
Matrix* c = new Matrix(a->n);
for (int i = 0; i < m->n; ++i) {
for (int j = 0; j < m->n; ++j) {
c->d[i][j] = b->d[j][i];
}
}
for (int i = 0; i < m->n; ++i) {
double *p = a->d[i], *q = m->d[i];
for (int j = 0; j < m->n; ++j) {
double t = 0.0, *r = c->d[j];
for (int k = 0; k < m->n; ++k) {
t += p[k] * r[k];
}
q[j] = t;
}
}
delete c;
return m;
}
int main(int argc, char *argv[]) {
int n = 300;
n = (n/2) * 2;
Matrix* a = Matrix_Gen(n);
Matrix* b = Matrix_Gen(n);
Matrix* m = Matrix_Mul(a, b);
delete a; delete b; delete m;
return 0;
}
| 17.569444
| 51
| 0.474308
|
Cwc-Lib
|
883627ecb1bb0fd9fb37228628fa884e89e94580
| 1,207
|
cpp
|
C++
|
Easy/804_uniqueMorseRepresentations/804_uniqueMorseRepresentations/main.cpp
|
yangbingjie/Leetcode
|
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
|
[
"MIT"
] | 1
|
2020-10-08T06:15:37.000Z
|
2020-10-08T06:15:37.000Z
|
Easy/804_uniqueMorseRepresentations/804_uniqueMorseRepresentations/main.cpp
|
yangbingjie/Leetcode
|
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
|
[
"MIT"
] | null | null | null |
Easy/804_uniqueMorseRepresentations/804_uniqueMorseRepresentations/main.cpp
|
yangbingjie/Leetcode
|
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// 804_uniqueMorseRepresentations
//
// Created by bella on 2020/7/13.
// Copyright © 2020 bella. All rights reserved.
//
#include <iostream>
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
const string morse[26] = {".-","-...","-.-.","-..",".","..-.",
"--.","....","..",".---","-.-",".-..",
"--","-.","---",".--.","--.-",".-.","...",
"-","..-","...-",".--","-..-","-.--","--.."};
set<string>::iterator iter;
set<string>s;
string str;
for (int i = 0; i < words.size(); ++i) {
str = "";
for (int j = 0; j < words[i].size(); ++j) {
str += morse[words[i][j] - 'a'];
}
iter = s.find(str);
if (iter == s.end()) {
s.insert(str);
}
}
return s.size();
}
};
int main(int argc, const char * argv[]) {
const int LEN = 4;
string arr[LEN] = {"gin", "zen", "gig", "msg"};
vector<string>words(arr, arr + LEN);
Solution s;
cout << s.uniqueMorseRepresentations(words) << endl;
return 0;
}
| 27.431818
| 70
| 0.429992
|
yangbingjie
|
883691f670992a0c290e8a73acb137feb1a5f71c
| 8,416
|
cc
|
C++
|
packager/media/formats/ttml/ttml_generator.cc
|
s3bubble/shaka-packager
|
77721fce857742744df7d118b651c6937dc90608
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1,288
|
2016-05-25T01:20:31.000Z
|
2022-03-02T23:56:56.000Z
|
packager/media/formats/ttml/ttml_generator.cc
|
s3bubble/shaka-packager
|
77721fce857742744df7d118b651c6937dc90608
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 894
|
2016-05-17T00:39:30.000Z
|
2022-03-02T18:46:21.000Z
|
packager/media/formats/ttml/ttml_generator.cc
|
s3bubble/shaka-packager
|
77721fce857742744df7d118b651c6937dc90608
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 400
|
2016-05-25T01:20:35.000Z
|
2022-03-03T02:12:00.000Z
|
// Copyright 2020 Google LLC. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include "packager/media/formats/ttml/ttml_generator.h"
#include "packager/base/base64.h"
#include "packager/base/strings/stringprintf.h"
#include "packager/media/base/rcheck.h"
namespace shaka {
namespace media {
namespace ttml {
namespace {
constexpr const char* kRegionIdPrefix = "_shaka_region_";
std::string ToTtmlTime(int64_t time, int32_t timescale) {
int64_t remaining = time * 1000 / timescale;
const int ms = remaining % 1000;
remaining /= 1000;
const int sec = remaining % 60;
remaining /= 60;
const int min = remaining % 60;
remaining /= 60;
const int hr = remaining;
return base::StringPrintf("%02d:%02d:%02d.%02d", hr, min, sec, ms);
}
std::string ToTtmlSize(const TextNumber& x, const TextNumber& y) {
const char* kSuffixMap[] = {"px", "em", "%"};
return base::StringPrintf("%.0f%s %.0f%s", x.value,
kSuffixMap[static_cast<int>(x.type)], y.value,
kSuffixMap[static_cast<int>(y.type)]);
}
} // namespace
const char* TtmlGenerator::kTtNamespace = "http://www.w3.org/ns/ttml";
TtmlGenerator::TtmlGenerator() {}
TtmlGenerator::~TtmlGenerator() {}
void TtmlGenerator::Initialize(const std::map<std::string, TextRegion>& regions,
const std::string& language,
int32_t time_scale) {
regions_ = regions;
language_ = language;
time_scale_ = time_scale;
}
void TtmlGenerator::AddSample(const TextSample& sample) {
samples_.emplace_back(sample);
}
void TtmlGenerator::Reset() {
samples_.clear();
}
bool TtmlGenerator::Dump(std::string* result) const {
xml::XmlNode root("tt");
RCHECK(root.SetStringAttribute("xmlns", kTtNamespace));
RCHECK(root.SetStringAttribute("xmlns:tts",
"http://www.w3.org/ns/ttml#styling"));
bool did_log = false;
xml::XmlNode head("head");
RCHECK(root.SetStringAttribute("xml:lang", language_));
for (const auto& pair : regions_) {
if (!did_log && (pair.second.region_anchor_x.value != 0 &&
pair.second.region_anchor_y.value != 0)) {
LOG(WARNING) << "TTML doesn't support non-0 region anchor";
did_log = true;
}
xml::XmlNode region("region");
const auto origin =
ToTtmlSize(pair.second.window_anchor_x, pair.second.window_anchor_y);
const auto extent = ToTtmlSize(pair.second.width, pair.second.height);
RCHECK(region.SetStringAttribute("xml:id", pair.first));
RCHECK(region.SetStringAttribute("tts:origin", origin));
RCHECK(region.SetStringAttribute("tts:extent", extent));
RCHECK(head.AddChild(std::move(region)));
}
RCHECK(root.AddChild(std::move(head)));
size_t image_count = 0;
xml::XmlNode metadata("metadata");
xml::XmlNode body("body");
xml::XmlNode div("div");
for (const auto& sample : samples_) {
RCHECK(AddSampleToXml(sample, &div, &metadata, &image_count));
}
RCHECK(body.AddChild(std::move(div)));
if (image_count > 0) {
RCHECK(root.SetStringAttribute(
"xmlns:smpte", "http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt"));
RCHECK(root.AddChild(std::move(metadata)));
}
RCHECK(root.AddChild(std::move(body)));
*result = root.ToString(/* comment= */ "");
return true;
}
bool TtmlGenerator::AddSampleToXml(const TextSample& sample,
xml::XmlNode* body,
xml::XmlNode* metadata,
size_t* image_count) const {
xml::XmlNode p("p");
RCHECK(p.SetStringAttribute("xml:space", "preserve"));
RCHECK(p.SetStringAttribute("begin",
ToTtmlTime(sample.start_time(), time_scale_)));
RCHECK(
p.SetStringAttribute("end", ToTtmlTime(sample.EndTime(), time_scale_)));
RCHECK(ConvertFragmentToXml(sample.body(), &p, metadata, image_count));
if (!sample.id().empty())
RCHECK(p.SetStringAttribute("xml:id", sample.id()));
const auto& settings = sample.settings();
if (settings.line || settings.position || settings.width || settings.height) {
// TTML positioning needs to be from a region.
if (!settings.region.empty()) {
LOG(WARNING)
<< "Using both text regions and positioning isn't supported in TTML";
}
const auto origin = ToTtmlSize(
settings.position.value_or(TextNumber(0, TextUnitType::kPixels)),
settings.line.value_or(TextNumber(0, TextUnitType::kPixels)));
const auto extent = ToTtmlSize(
settings.width.value_or(TextNumber(100, TextUnitType::kPercent)),
settings.height.value_or(TextNumber(100, TextUnitType::kPercent)));
const std::string id = kRegionIdPrefix + std::to_string(region_id_++);
xml::XmlNode region("region");
RCHECK(region.SetStringAttribute("xml:id", id));
RCHECK(region.SetStringAttribute("tts:origin", origin));
RCHECK(region.SetStringAttribute("tts:extent", extent));
RCHECK(p.SetStringAttribute("region", id));
RCHECK(body->AddChild(std::move(region)));
} else if (!settings.region.empty()) {
RCHECK(p.SetStringAttribute("region", settings.region));
}
if (settings.writing_direction != WritingDirection::kHorizontal) {
const char* dir =
settings.writing_direction == WritingDirection::kVerticalGrowingLeft
? "tbrl"
: "tblr";
RCHECK(p.SetStringAttribute("tts:writingMode", dir));
}
if (settings.text_alignment != TextAlignment::kStart) {
switch (settings.text_alignment) {
case TextAlignment::kStart: // To avoid compiler warning.
case TextAlignment::kCenter:
RCHECK(p.SetStringAttribute("tts:textAlign", "center"));
break;
case TextAlignment::kEnd:
RCHECK(p.SetStringAttribute("tts:textAlign", "end"));
break;
case TextAlignment::kLeft:
RCHECK(p.SetStringAttribute("tts:textAlign", "left"));
break;
case TextAlignment::kRight:
RCHECK(p.SetStringAttribute("tts:textAlign", "right"));
break;
}
}
RCHECK(body->AddChild(std::move(p)));
return true;
}
bool TtmlGenerator::ConvertFragmentToXml(const TextFragment& body,
xml::XmlNode* parent,
xml::XmlNode* metadata,
size_t* image_count) const {
if (body.newline) {
xml::XmlNode br("br");
return parent->AddChild(std::move(br));
}
// If we have new styles, add a new <span>.
xml::XmlNode span("span");
xml::XmlNode* node = parent;
if (body.style.bold || body.style.italic || body.style.underline) {
node = &span;
if (body.style.bold) {
RCHECK(span.SetStringAttribute("tts:fontWeight",
*body.style.bold ? "bold" : "normal"));
}
if (body.style.italic) {
RCHECK(span.SetStringAttribute("tts:fontStyle",
*body.style.italic ? "italic" : "normal"));
}
if (body.style.underline) {
RCHECK(span.SetStringAttribute(
"tts:textDecoration",
*body.style.underline ? "underline" : "noUnderline"));
}
}
if (!body.body.empty()) {
node->AddContent(body.body);
} else if (!body.image.empty()) {
std::string image_data(body.image.begin(), body.image.end());
std::string base64_data;
base::Base64Encode(image_data, &base64_data);
std::string id = "img_" + std::to_string(++*image_count);
xml::XmlNode image_xml("smpte:image");
RCHECK(image_xml.SetStringAttribute("imageType", "PNG"));
RCHECK(image_xml.SetStringAttribute("encoding", "Base64"));
RCHECK(image_xml.SetStringAttribute("xml:id", id));
image_xml.SetContent(base64_data);
RCHECK(metadata->AddChild(std::move(image_xml)));
RCHECK(node->SetStringAttribute("smpte:backgroundImage", "#" + id));
} else {
for (const auto& frag : body.sub_fragments) {
if (!ConvertFragmentToXml(frag, node, metadata, image_count))
return false;
}
}
if (body.style.bold || body.style.italic || body.style.underline)
RCHECK(parent->AddChild(std::move(span)));
return true;
}
} // namespace ttml
} // namespace media
} // namespace shaka
| 34.921162
| 80
| 0.638308
|
s3bubble
|
88372d6cb574e2c1ea34aab80c4b97027579a58a
| 10,942
|
cpp
|
C++
|
libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.cpp
|
RiddleAndCode/Arduino_Core_STM32
|
cf54e13565a50c0c61740d7f10e9f8f3ec4ede77
|
[
"Apache-2.0"
] | null | null | null |
libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.cpp
|
RiddleAndCode/Arduino_Core_STM32
|
cf54e13565a50c0c61740d7f10e9f8f3ec4ede77
|
[
"Apache-2.0"
] | null | null | null |
libraries/GSM/src/GSM3ShieldV1DataNetworkProvider.cpp
|
RiddleAndCode/Arduino_Core_STM32
|
cf54e13565a50c0c61740d7f10e9f8f3ec4ede77
|
[
"Apache-2.0"
] | 1
|
2021-02-20T07:43:44.000Z
|
2021-02-20T07:43:44.000Z
|
/*
This file is part of the GSM3 communications library for Arduino
-- Multi-transport communications platform
-- Fully asynchronous
-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
-- Voice calls
-- SMS
-- TCP/IP connections
-- HTTP basic clients
This library has been developed by Telefónica Digital - PDI -
- Physical Internet Lab, as part as its collaboration with
Arduino and the Open Hardware Community.
September-December 2012
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
The latest version of this library can always be found at
https://github.com/BlueVia/Official-Arduino
*/
#include <GSM3ShieldV1DataNetworkProvider.h>
#include <Arduino.h>
const char _command_CGATT[] PROGMEM = "AT+CGATT=";
const char _command_SEPARATOR[] PROGMEM = "\",\"";
//Attach GPRS main function.
GSM3_NetworkStatus_t GSM3ShieldV1DataNetworkProvider::attachGPRS(char* apn, char* user_name, char* password, bool synchronous)
{
user = user_name;
passwd = password;
// A sad use of byte reuse
theGSM3ShieldV1ModemCore.setPhoneNumber(apn);
theGSM3ShieldV1ModemCore.openCommand(this,ATTACHGPRS);
theGSM3ShieldV1ModemCore.setStatus(CONNECTING);
attachGPRSContinue();
// If synchronous, wait till attach is over, or not.
if(synchronous)
{
// if we shorten this delay, the command fails
while(ready()==0)
delay(100);
}
return theGSM3ShieldV1ModemCore.getStatus();
}
//Atthach GPRS continue function.
void GSM3ShieldV1DataNetworkProvider::attachGPRSContinue()
{
bool resp;
// 1: Attach to GPRS service "AT+CGATT=1"
// 2: Wait attach OK and Set the context 0 as FGCNT "AT+QIFGCNT=0"
// 3: Wait context OK and Set bearer type as GPRS, APN, user name and pasword "AT+QICSGP=1..."
// 4: Wait bearer OK and Enable the function of MUXIP "AT+QIMUX=1"
// 5: Wait for disable MUXIP OK and Set the session mode as non transparent "AT+QIMODE=0"
// 6: Wait for session mode OK and Enable notification when data received "AT+QINDI=1"
// 8: Wait domain name OK and Register the TCP/IP stack "AT+QIREGAPP"
// 9: Wait for Register OK and Activate FGCNT "AT+QIACT"
// 10: Wait for activate OK
int ct=theGSM3ShieldV1ModemCore.getCommandCounter();
if(ct==1)
{
//AT+CGATT
theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGATT,false);
theGSM3ShieldV1ModemCore.print(1);
theGSM3ShieldV1ModemCore.print('\r');
theGSM3ShieldV1ModemCore.setCommandCounter(2);
}
else if(ct==2)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
//AT+QIFGCNT
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIFGCNT=0"));
theGSM3ShieldV1ModemCore.setCommandCounter(3);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==3)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
// Great. Go for the next step
//DEBUG
//Serial.println("AT+QICSGP.");
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QICSGP=1,\""),false);
theGSM3ShieldV1ModemCore.print(theGSM3ShieldV1ModemCore.getPhoneNumber());
theGSM3ShieldV1ModemCore.genericCommand_rq(_command_SEPARATOR,false);
theGSM3ShieldV1ModemCore.print(user);
theGSM3ShieldV1ModemCore.genericCommand_rq(_command_SEPARATOR,false);
theGSM3ShieldV1ModemCore.print(passwd);
theGSM3ShieldV1ModemCore.print("\"\r");
theGSM3ShieldV1ModemCore.setCommandCounter(4);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==4)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
// AT+QIMUX=1 for multisocket
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIMUX=0"));
theGSM3ShieldV1ModemCore.setCommandCounter(5);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==5)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
//AT+QIMODE=0 for multisocket
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIMODE=1"));
theGSM3ShieldV1ModemCore.setCommandCounter(6);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==6)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
// AT+QINDI=1
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QINDI=1"));
theGSM3ShieldV1ModemCore.setCommandCounter(8);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==8)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
// AT+QIREGAPP
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIREGAPP"));
theGSM3ShieldV1ModemCore.setCommandCounter(9);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==9)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if(resp)
{
// AT+QIACT
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QIACT"));
theGSM3ShieldV1ModemCore.setCommandCounter(10);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
else if(ct==10)
{
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
if (resp)
{
theGSM3ShieldV1ModemCore.setStatus(GPRS_READY);
theGSM3ShieldV1ModemCore.closeCommand(1);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
}
}
//Detach GPRS main function.
GSM3_NetworkStatus_t GSM3ShieldV1DataNetworkProvider::detachGPRS(bool synchronous)
{
theGSM3ShieldV1ModemCore.openCommand(this,DETACHGPRS);
theGSM3ShieldV1ModemCore.setStatus(CONNECTING);
detachGPRSContinue();
if(synchronous)
{
while(ready()==0)
delay(1);
}
return theGSM3ShieldV1ModemCore.getStatus();
}
void GSM3ShieldV1DataNetworkProvider::detachGPRSContinue()
{
bool resp;
// 1: Detach to GPRS service "AT+CGATT=0"
// 2: Wait dettach +PDP DEACT
// 3: Wait for OK
switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
case 1:
//AT+CGATT=0
theGSM3ShieldV1ModemCore.genericCommand_rq(_command_CGATT,false);
theGSM3ShieldV1ModemCore.print(0);
theGSM3ShieldV1ModemCore.print('\r');
theGSM3ShieldV1ModemCore.setCommandCounter(2);
break;
case 2:
char auxLocate[12];
prepareAuxLocate(PSTR("+PDP DEACT"), auxLocate);
if(theGSM3ShieldV1ModemCore.theBuffer().locate(auxLocate))
{
if(resp)
{
// Received +PDP DEACT;
theGSM3ShieldV1ModemCore.setCommandCounter(3);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
break;
case 3:
if(theGSM3ShieldV1ModemCore.genericParse_rsp(resp))
{
// OK received
if (resp)
{
theGSM3ShieldV1ModemCore.setStatus(GSM_READY);
theGSM3ShieldV1ModemCore.closeCommand(1);
}
else theGSM3ShieldV1ModemCore.closeCommand(3);
}
theGSM3ShieldV1ModemCore.theBuffer().flush();
theGSM3ShieldV1ModemCore.gss.spaceAvailable();
break;
}
}
//QILOCIP parse.
bool GSM3ShieldV1DataNetworkProvider::parseQILOCIP_rsp(char* LocalIP, int LocalIPlength, bool& rsp)
{
if (!(theGSM3ShieldV1ModemCore.theBuffer().extractSubstring("\r\n","\r\n", LocalIP, LocalIPlength)))
rsp = false;
else
rsp = true;
return true;
}
//Get IP main function.
int GSM3ShieldV1DataNetworkProvider::getIP(char* LocalIP, int LocalIPlength)
{
theGSM3ShieldV1ModemCore.setPhoneNumber(LocalIP);
theGSM3ShieldV1ModemCore.setPort(LocalIPlength);
theGSM3ShieldV1ModemCore.openCommand(this,GETIP);
getIPContinue();
return theGSM3ShieldV1ModemCore.getCommandError();
}
void GSM3ShieldV1DataNetworkProvider::getIPContinue()
{
bool resp;
// 1: Read Local IP "AT+QILOCIP"
// 2: Waiting for IP.
switch (theGSM3ShieldV1ModemCore.getCommandCounter()) {
case 1:
//AT+QILOCIP
theGSM3ShieldV1ModemCore.genericCommand_rq(PSTR("AT+QILOCIP"));
theGSM3ShieldV1ModemCore.setCommandCounter(2);
break;
case 2:
if(parseQILOCIP_rsp(theGSM3ShieldV1ModemCore.getPhoneNumber(), theGSM3ShieldV1ModemCore.getPort(), resp))
{
if (resp)
theGSM3ShieldV1ModemCore.closeCommand(1);
else
theGSM3ShieldV1ModemCore.closeCommand(3);
}
theGSM3ShieldV1ModemCore.theBuffer().flush();
theGSM3ShieldV1ModemCore.gss.spaceAvailable();
break;
}
}
//Get IP with IPAddress object
IPAddress GSM3ShieldV1DataNetworkProvider::getIPAddress() {
char ip_temp[15]="";
getIP(ip_temp, 15);
unsigned long m=millis();
while((millis()-m)<10*1000 && (!ready())){
// wait for a response from the modem:
delay(100);
}
IPAddress ip;
inet_aton(ip_temp, ip);
return ip;
}
int GSM3ShieldV1DataNetworkProvider::inet_aton(const char* aIPAddrString, IPAddress& aResult)
{
// See if we've been given a valid IP address
const char* p =aIPAddrString;
while (*p &&
( (*p == '.') || (*p >= '0') || (*p <= '9') ))
{
p++;
}
if (*p == '\0')
{
// It's looking promising, we haven't found any invalid characters
p = aIPAddrString;
int segment =0;
int segmentValue =0;
while (*p && (segment < 4))
{
if (*p == '.')
{
// We've reached the end of a segment
if (segmentValue > 255)
{
// You can't have IP address segments that don't fit in a byte
return 0;
}
else
{
aResult[segment] = (byte)segmentValue;
segment++;
segmentValue = 0;
}
}
else
{
// Next digit
segmentValue = (segmentValue*10)+(*p - '0');
}
p++;
}
// We've reached the end of address, but there'll still be the last
// segment to deal with
if ((segmentValue > 255) || (segment > 3))
{
// You can't have IP address segments that don't fit in a byte,
// or more than four segments
return 0;
}
else
{
aResult[segment] = (byte)segmentValue;
return 1;
}
}
else
{
return 0;
}
}
//Response management.
void GSM3ShieldV1DataNetworkProvider::manageResponse(byte from, byte to)
{
switch(theGSM3ShieldV1ModemCore.getOngoingCommand())
{
case ATTACHGPRS:
attachGPRSContinue();
break;
case DETACHGPRS:
detachGPRSContinue();
break;
case GETIP:
getIPContinue();
break;
default:
break;
}
}
| 27.218905
| 126
| 0.690733
|
RiddleAndCode
|
883a01ad6d74daecde45b1d28a806ac57b5e9048
| 8,363
|
hpp
|
C++
|
src/lapack_like/factor/LDL/dense/Pivoted/BunchKaufmanD.hpp
|
jeffhammond/Elemental
|
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
|
[
"Apache-2.0"
] | null | null | null |
src/lapack_like/factor/LDL/dense/Pivoted/BunchKaufmanD.hpp
|
jeffhammond/Elemental
|
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
|
[
"Apache-2.0"
] | null | null | null |
src/lapack_like/factor/LDL/dense/Pivoted/BunchKaufmanD.hpp
|
jeffhammond/Elemental
|
a9e6236ce9d92dd56c7d3cd5ffd52f796a35cd0c
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright (c) 2009-2016, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef EL_LDL_PIVOTED_BUNCHKAUFMAND_HPP
#define EL_LDL_PIVOTED_BUNCHKAUFMAND_HPP
namespace El {
namespace ldl {
namespace pivot {
template<typename F>
LDLPivot
BunchKaufmanD( const Matrix<F>& A, Base<F> gamma )
{
DEBUG_CSE
typedef Base<F> Real;
const Int n = A.Height();
if( gamma == Real(0) )
gamma = LDLPivotConstant<Real>( BUNCH_KAUFMAN_D );
const Real alpha11Abs = Abs(A(0,0));
const Range<Int> ind1( 0, 1 ),
ind2( 1, n );
const auto a21Max = VectorMaxAbsLoc( A(ind2,ind1) );
if( a21Max.value == Real(0) && alpha11Abs == Real(0) )
throw SingularMatrixException();
LDLPivot pivot;
if( alpha11Abs >= gamma*a21Max.value )
{
pivot.nb = 1;
pivot.from[0] = 0;
return pivot;
}
// Find maximum value in row r (exploit symmetry)
const Int r = a21Max.index + 1;
const Range<Int> indr0( 0, r ),
indr1( r, r+1 ),
indrB( r, n );
const auto leftMax = VectorMaxAbsLoc( A(indr1,indr0) );
const auto bottomMax = VectorMaxAbsLoc( A(indrB,indr1) );
const Real rowMaxVal = Max(leftMax.value,bottomMax.value);
if( alpha11Abs >= gamma*a21Max.value*(a21Max.value/rowMaxVal) )
{
pivot.nb = 1;
pivot.from[0] = 0;
return pivot;
}
// Default to a 2x2 pivot with 0 and r
pivot.nb = 2;
pivot.from[0] = 0;
pivot.from[1] = r;
return pivot;
}
template<typename F>
LDLPivot
BunchKaufmanD( const DistMatrix<F>& A, Base<F> gamma )
{
DEBUG_CSE
typedef Base<F> Real;
const Int n = A.Height();
if( gamma == Real(0) )
gamma = LDLPivotConstant<Real>( BUNCH_KAUFMAN_D );
const Real alpha11Abs = Abs(A.Get(0,0));
const Range<Int> ind1( 0, 1 ),
ind2( 1, n );
const auto a21Max = VectorMaxAbsLoc( A(ind2,ind1) );
if( a21Max.value == Real(0) && alpha11Abs == Real(0) )
throw SingularMatrixException();
LDLPivot pivot;
if( alpha11Abs >= gamma*a21Max.value )
{
pivot.nb = 1;
pivot.from[0] = 0;
return pivot;
}
// Find maximum value in row r (exploit symmetry)
const Int r = a21Max.index + 1;
const Range<Int> indr0( 0, r ),
indr1( r, r+1 ),
indrB( r, n );
const auto leftMax = VectorMaxAbsLoc( A(indr1,indr0) );
const auto bottomMax = VectorMaxAbsLoc( A(indrB,indr1) );
const Real rowMaxVal = Max(leftMax.value,bottomMax.value);
if( alpha11Abs >= gamma*a21Max.value*(a21Max.value/rowMaxVal) )
{
pivot.nb = 1;
pivot.from[0] = 0;
return pivot;
}
// Default to a 2x2 pivot with 0 and r
pivot.nb = 2;
pivot.from[0] = 0;
pivot.from[1] = r;
return pivot;
}
// TODO: Switch to the simpler panel update scheme used for Cholesky
template<typename F>
LDLPivot
PanelBunchKaufmanD
( const Matrix<F>& A, const Matrix<F>& X, const Matrix<F>& Y, Base<F> gamma )
{
DEBUG_CSE
typedef Base<F> Real;
const Int n = A.Height();
const Int k = X.Width();
if( gamma == Real(0) )
gamma = LDLPivotConstant<Real>( BUNCH_KAUFMAN_D );
const Range<Int> ind0( 0, k ),
ind1( k, k+1 ), ind1Off( 0, 1 ),
ind2Off( 1, n-k ),
indB( k, n );
auto aB1 = A( indB, ind1 );
auto zB1( aB1 );
// A(k:n-1,k) -= X(k:n-1,0:k-1) Y(k,0:k-1)^T
{
auto XB0 = X( indB, ind0 );
auto y10 = Y( ind1, ind0 );
Gemv( NORMAL, F(-1), XB0, y10, F(1), zB1 );
}
const Real alpha11Abs = Abs(zB1(0));
const auto a21Max = VectorMaxAbsLoc( zB1(ind2Off,ind1Off) );
if( a21Max.value == Real(0) && alpha11Abs == Real(0) )
throw SingularMatrixException();
LDLPivot pivot;
if( alpha11Abs >= gamma*a21Max.value )
{
pivot.nb = 1;
pivot.from[0] = k;
return pivot;
}
// Find maximum value in row r (exploit symmetry)
const Int r = a21Max.index + (k+1);
const Range<Int> indrM( k, r ),
indr1( r, r+1 ),
indrB( r, n );
auto aLeft = A( indr1, indrM );
auto aBottom = A( indrB, indr1 );
auto zLeft( aLeft );
auto zBottom( aBottom );
// Update necessary components out-of-place
// ----------------------------------------
// A(r,k:r-1) -= X(r,0:k-1) Y(k:r-1,0:k-1)^T
{
auto xr10 = X( indr1, ind0 );
auto YrM0 = Y( indrM, ind0 );
Gemv( NORMAL, F(-1), YrM0, xr10, F(1), zLeft );
}
// A(r:n-1,r) -= X(r:n-1,0:k-1) Y(r,0:k-1)^T
{
auto XrB0 = X( indrB, ind0 );
auto yr10 = Y( indr1, ind0 );
Gemv( NORMAL, F(-1), XrB0, yr10, F(1), zBottom );
}
const auto leftMax = VectorMaxAbsLoc( zLeft );
const auto bottomMax = VectorMaxAbsLoc( zBottom );
const Real rowMaxVal = Max(leftMax.value,bottomMax.value);
if( alpha11Abs >= gamma*a21Max.value*(a21Max.value/rowMaxVal) )
{
pivot.nb = 1;
pivot.from[0] = k;
return pivot;
}
// Default to a 2x2 pivot with k and r
pivot.nb = 2;
pivot.from[0] = k;
pivot.from[1] = r;
return pivot;
}
template<typename F>
LDLPivot
PanelBunchKaufmanD
( const DistMatrix<F>& A,
const DistMatrix<F,MC,STAR>& X,
const DistMatrix<F,MR,STAR>& Y,
Base<F> gamma )
{
DEBUG_CSE
typedef Base<F> Real;
const Int n = A.Height();
const Int k = X.Width();
if( A.ColAlign() != X.ColAlign() || A.RowAlign() != Y.ColAlign() )
LogicError("X and Y were not properly aligned with A");
if( gamma == Real(0) )
gamma = LDLPivotConstant<Real>( BUNCH_KAUFMAN_D );
const Range<Int> ind0( 0, k ),
ind1( k, k+1 ), ind1Off( 0, 1 ),
ind2Off( 1, n-k ),
indB( k, n );
auto aB1 = A( indB, ind1 );
auto zB1( aB1 );
// A(k:n-1,k) -= X(k:n-1,0:k-1) Y(k,0:k-1)^T
if( aB1.RowAlign() == aB1.RowRank() )
{
auto XB0 = X( indB, ind0 );
auto y10 = Y( ind1, ind0 );
LocalGemv( NORMAL, F(-1), XB0, y10, F(1), zB1 );
}
const Real alpha11Abs = Abs(zB1.Get(0,0));
const auto a21Max = VectorMaxAbsLoc( zB1(ind2Off,ind1Off) );
if( a21Max.value == Real(0) && alpha11Abs == Real(0) )
throw SingularMatrixException();
LDLPivot pivot;
if( alpha11Abs >= gamma*a21Max.value )
{
pivot.nb = 1;
pivot.from[0] = k;
return pivot;
}
// Find maximum off-diag value in row r (exploit symmetry)
const Int r = a21Max.index + (k+1);
const Range<Int> indrM( k, r ),
indr1( r, r+1 ),
indrB( r, n );
auto aLeft = A( indr1, indrM );
auto aBottom = A( indrB, indr1 );
auto zLeft( aLeft );
auto zBottom( aBottom );
// Update necessary components out-of-place
// ----------------------------------------
// A(r,k:r-1) -= X(r,0:k-1) Y(k:r-1,0:k-1)^T
if( aLeft.ColAlign() == aLeft.ColRank() )
{
auto xr10 = X( indr1, ind0 );
auto YrM0 = Y( indrM, ind0 );
LocalGemv( NORMAL, F(-1), YrM0, xr10, F(1), zLeft );
}
// A(r:n-1,r) -= X(r:n-1,0:k-1) Y(r,0:k-1)^T
if( aBottom.RowAlign() == aBottom.RowRank() )
{
auto XrB0 = X( indrB, ind0 );
auto yr10 = Y( indr1, ind0 );
LocalGemv( NORMAL, F(-1), XrB0, yr10, F(1), zBottom );
}
const auto leftMax = VectorMaxAbsLoc( zLeft );
const auto bottomMax = VectorMaxAbsLoc( zBottom );
const Real rowMaxVal = Max(leftMax.value,bottomMax.value);
if( alpha11Abs >= gamma*a21Max.value*(a21Max.value/rowMaxVal) )
{
pivot.nb = 1;
pivot.from[0] = k;
return pivot;
}
// Default to a 2x2 pivot with k and r
pivot.nb = 2;
pivot.from[0] = k;
pivot.from[1] = r;
return pivot;
}
} // namespace pivot
} // namespace ldl
} // namespace El
#endif // ifndef EL_LDL_PIVOTED_BUNCHKAUFMAND_HPP
| 28.158249
| 77
| 0.541672
|
jeffhammond
|
883aee3faf69fbf315c3a1f6ccb983bc8a2e682a
| 1,070
|
cpp
|
C++
|
Leetcode/2001-3000/2065. Maximum Path Quality of a Graph/2065.cpp
|
Next-Gen-UI/Code-Dynamics
|
a9b9d5e3f27e870b3e030c75a1060d88292de01c
|
[
"MIT"
] | null | null | null |
Leetcode/2001-3000/2065. Maximum Path Quality of a Graph/2065.cpp
|
Next-Gen-UI/Code-Dynamics
|
a9b9d5e3f27e870b3e030c75a1060d88292de01c
|
[
"MIT"
] | null | null | null |
Leetcode/2001-3000/2065. Maximum Path Quality of a Graph/2065.cpp
|
Next-Gen-UI/Code-Dynamics
|
a9b9d5e3f27e870b3e030c75a1060d88292de01c
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int maximalPathQuality(vector<int>& values, vector<vector<int>>& edges,
int maxTime) {
const int n = values.size();
int ans = 0;
vector<vector<pair<int, int>>> graph(n);
vector<int> seen(n);
seen[0] = 1;
for (const auto& e : edges) {
const int u = e[0];
const int v = e[1];
const int time = e[2];
graph[u].emplace_back(v, time);
graph[v].emplace_back(u, time);
}
dfs(graph, values, 0, values[0], maxTime, seen, ans);
return ans;
}
private:
void dfs(const vector<vector<pair<int, int>>>& graph,
const vector<int>& values, int u, int quality, int remainingTime,
vector<int>& seen, int& ans) {
if (u == 0)
ans = max(ans, quality);
for (const auto& [v, time] : graph[u]) {
if (time > remainingTime)
continue;
const int newQuality = quality + values[v] * (seen[v] == 0);
++seen[v];
dfs(graph, values, v, newQuality, remainingTime - time, seen, ans);
--seen[v];
}
}
};
| 27.435897
| 76
| 0.547664
|
Next-Gen-UI
|
883bbec44358e50add87f47786eea94f72a5f192
| 4,353
|
hh
|
C++
|
hackt_docker/hackt/src/sim/prsim/Cause.hh
|
broken-wheel/hacktist
|
36e832ae7dd38b27bca9be7d0889d06054dc2806
|
[
"MIT"
] | null | null | null |
hackt_docker/hackt/src/sim/prsim/Cause.hh
|
broken-wheel/hacktist
|
36e832ae7dd38b27bca9be7d0889d06054dc2806
|
[
"MIT"
] | null | null | null |
hackt_docker/hackt/src/sim/prsim/Cause.hh
|
broken-wheel/hacktist
|
36e832ae7dd38b27bca9be7d0889d06054dc2806
|
[
"MIT"
] | null | null | null |
/**
\file "sim/prsim/Cause.hh"
Structure of basic node event.
$Id: Cause.hh,v 1.5 2009/02/01 07:21:35 fang Exp $
*/
#ifndef __HAC_SIM_PRSIM_CAUSE_H__
#define __HAC_SIM_PRSIM_CAUSE_H__
#include <iosfwd>
#include "sim/common.hh"
#include "sim/prsim/enums.hh"
#include "util/utypes.h"
#include "sim/prsim/devel_switches.hh" // for PRSIM_TRACK_CAUSE_TIME
#if PRSIM_TRACK_CAUSE_TIME || PRSIM_TRACK_LAST_EDGE_TIME
#include "sim/time.hh"
#endif
namespace HAC {
namespace SIM {
namespace PRSIM {
using std::ostream;
using std::istream;
#if PRSIM_TRACK_CAUSE_TIME || PRSIM_TRACK_LAST_EDGE_TIME
typedef real_time event_time_type;
#endif
//=============================================================================
/**
(node, value) pair representing a past event.
With a time stamp, does this struct become large enough to
warrant using pointers to Cause objects?
Said Cause objects would need to expire over time,
perhaps via reference count...
*/
struct EventCause {
node_index_type node;
value_enum val;
#if PRSIM_TRACK_CAUSE_TIME
event_time_type time;
#endif
EventCause() : node(INVALID_NODE_INDEX), val(LOGIC_LOW)
#if PRSIM_TRACK_CAUSE_TIME
, time(-1.0)
#endif
{ }
// initial value doesn't matter, could be LOGIC_OTHER
#if PRSIM_TRACK_CAUSE_TIME
EventCause(const node_index_type n, const value_enum v,
const event_time_type& t) :
node(n), val(v), time(t) { }
#else
EventCause(const node_index_type n, const value_enum v) :
node(n), val(v) { }
#endif
/**
For set-ordering relation.
*/
bool
operator < (const EventCause& e) const {
// really, shouldn't be inserting events with same id,val...
return (node < e.node) ||
((node == e.node) && (
(val < e.val)
#if 0 && PRSIM_TRACK_CAUSE_TIME
|| ((val == e.val) && (time < e.time))
#endif
));
}
ostream&
dump_raw(ostream&) const;
void
save_state(ostream&) const;
void
load_state(istream&);
}; // end struct EventCause
//-----------------------------------------------------------------------------
/**
Structure for tracking event causality in greater detail.
Members kept in separate arrays for better alignment.
Note: don't want to trace critical trace index here, costs memory.
*/
struct LastCause {
typedef EventCause event_cause_type;
/**
The causing node.
Indexed by node's current value.
*/
node_index_type caused_by_node[3];
/**
The value of the causing node.
3 of 4 slots used for better padding.
Indexed by node's current value.
*/
value_enum caused_by_value[4];
#if PRSIM_TRACK_CAUSE_TIME
event_time_type cause_time[3];
#endif
void
initialize(void) {
// caused_by_node({0}),
// caused_by_value({0})
// caused_by_node = {0};
// caused_by_value = {0};
// *this = {{0,0,0}, {0,0,0}};
caused_by_node[0] = INVALID_NODE_INDEX;
caused_by_node[1] = INVALID_NODE_INDEX;
caused_by_node[2] = INVALID_NODE_INDEX;
caused_by_value[0] = LOGIC_LOW; // don't care
caused_by_value[1] = LOGIC_LOW; // don't care
caused_by_value[2] = LOGIC_LOW; // don't care
caused_by_value[3] = LOGIC_LOW; // really don't care
// but needs to be initialized else binary will be
// non-deterministic
#if PRSIM_TRACK_CAUSE_TIME
cause_time[0] = cause_time[1] = cause_time[2] = -1.0;
#endif
}
/**
How the f-- do you initialize aggregate members?
*/
LastCause() {
initialize();
}
/**
\param the value with which to lookup the last cause.
\return the index of the last node to cause this change.
*/
node_index_type
get_cause_node(const value_enum v) const {
return caused_by_node[size_t(v)];
}
event_cause_type
get_cause(const value_enum v) const {
const size_t i(v);
return event_cause_type(caused_by_node[i], caused_by_value[i]
#if PRSIM_TRACK_CAUSE_TIME
, cause_time[i]
#endif
);
}
void
set_cause(const value_enum v, const event_cause_type& e) {
const size_t i(v);
caused_by_node[i] = e.node;
caused_by_value[i] = e.val;
#if PRSIM_TRACK_CAUSE_TIME
cause_time[i] = e.time;
#endif
}
void
save_state(ostream&) const;
void
load_state(istream&);
ostream&
dump_checkpoint_state(ostream&) const;
}; // end struct LastCause
//=============================================================================
} // end namespace PRSIM
} // end namespace SIM
} // end namespace HAC
#endif // __HAC_SIM_PRSIM_CAUSE_H__
| 23.657609
| 79
| 0.666667
|
broken-wheel
|
883e5f28b3e8dd39ce48699669e91cddc117a46a
| 1,547
|
hpp
|
C++
|
include/gogh/disassembler.hpp
|
braedinski/gogh
|
28f5be6b075fc549dd9d8d6fb1708176b1892c03
|
[
"MIT"
] | null | null | null |
include/gogh/disassembler.hpp
|
braedinski/gogh
|
28f5be6b075fc549dd9d8d6fb1708176b1892c03
|
[
"MIT"
] | null | null | null |
include/gogh/disassembler.hpp
|
braedinski/gogh
|
28f5be6b075fc549dd9d8d6fb1708176b1892c03
|
[
"MIT"
] | null | null | null |
/*
* gogh::disassembler
*
* The class is just a wrapper for capstone disassembler.
* `gogh` will use its own instruction decoder/disassembler.
*
*/
#include <capstone/capstone.h>
namespace gogh {
class disassembler {
public:
disassembler() {
if (cs_open(
CS_ARCH_MIPS,
(cs_mode)(CS_MODE_MIPS32 + CS_MODE_BIG_ENDIAN),
&_handle) != CS_ERR_OK) {
}
}
~disassembler() {
if (_handle) {
cs_close(&_handle);
}
}
bool disassemble(const uint8_t *code, const size_t length) {
std::size_t count = cs_disasm(
_handle,
code,
length,
0x1000,
0,
&_instruction
);
if (count > 0) {
for (std::size_t j = 0; j < count; j++) {
/*
std::cout
<< "0x" << std::hex << _instruction[j].address << ' '
<< _instruction[j].mnemonic << ' '
<< _instruction[j].op_str << '\n';
*/
}
cs_free(_instruction, count);
}
return true;
}
protected:
cs_insn *_instruction;
csh _handle;
};
}
| 26.672414
| 81
| 0.372334
|
braedinski
|
883f7d3ccf35c53eb89b1db830f34c5e76883615
| 5,220
|
cpp
|
C++
|
tests/CoreTests/RandomOuts.cpp
|
JacopoDT/numerare-core
|
a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f
|
[
"MIT-0"
] | null | null | null |
tests/CoreTests/RandomOuts.cpp
|
JacopoDT/numerare-core
|
a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f
|
[
"MIT-0"
] | null | null | null |
tests/CoreTests/RandomOuts.cpp
|
JacopoDT/numerare-core
|
a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f
|
[
"MIT-0"
] | null | null | null |
/***
MIT License
Copyright (c) 2018 NUMERARE
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.
Parts of this file are originally Copyright (c) 2012-2017 The CryptoNote developers, The Bytecoin developers
***/
#include "RandomOuts.h"
#include "TestGenerator.h"
#include "Rpc/CoreRpcServerCommandsDefinitions.h"
GetRandomOutputs::GetRandomOutputs() {
REGISTER_CALLBACK_METHOD(GetRandomOutputs, checkHalfUnlocked);
REGISTER_CALLBACK_METHOD(GetRandomOutputs, checkFullyUnlocked);
}
bool GetRandomOutputs::generate(std::vector<test_event_entry>& events) const {
TestGenerator generator(*m_currency, events);
generator.generateBlocks();
uint64_t sendAmount = MK_COINS(1);
for (int i = 0; i < 10; ++i) {
auto builder =
generator.createTxBuilder(generator.minerAccount, generator.minerAccount, sendAmount, m_currency->minimumFee());
auto tx = builder.build();
generator.addEvent(tx);
generator.makeNextBlock(tx);
}
// unlock half of the money
generator.generateBlocks(m_currency->minedMoneyUnlockWindow() / 2 + 1);
generator.addCallback("checkHalfUnlocked");
// unlock the remaining part
generator.generateBlocks(m_currency->minedMoneyUnlockWindow() / 2);
generator.addCallback("checkFullyUnlocked");
return true;
}
bool GetRandomOutputs::request(CryptoNote::Core& c, uint64_t ramount, size_t mixin,
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response& resp) {
resp.outs.clear();
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request req;
req.amounts.push_back(ramount);
req.outs_count = static_cast<uint16_t>(mixin);
for (auto amount : req.amounts) {
std::vector<uint32_t> globalIndexes;
std::vector<Crypto::PublicKey> publicKeys;
if (!c.getRandomOutputs(amount, static_cast<uint16_t>(req.outs_count), globalIndexes, publicKeys)) {
return false;
}
assert(globalIndexes.size() == publicKeys.size());
resp.outs.emplace_back(CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_outs_for_amount{amount, {}});
for (size_t i = 0; i < globalIndexes.size(); ++i) {
resp.outs.back().outs.push_back({globalIndexes[i], publicKeys[i]});
}
}
return true;
}
#define CHECK(cond) \
if ((cond) == false) { \
LOG_ERROR("Condition " #cond " failed"); \
return false; \
}
bool GetRandomOutputs::checkHalfUnlocked(CryptoNote::Core& c, size_t ev_index,
const std::vector<test_event_entry>& events) {
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response resp;
auto amount = MK_COINS(1);
auto unlocked = m_currency->minedMoneyUnlockWindow() / 2 + 1;
CHECK(request(c, amount, 0, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == 0);
CHECK(request(c, amount, unlocked, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
CHECK(request(c, amount, unlocked * 2, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
return true;
}
bool GetRandomOutputs::checkFullyUnlocked(CryptoNote::Core& c, size_t ev_index,
const std::vector<test_event_entry>& events) {
CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response resp;
auto amount = MK_COINS(1);
auto unlocked = m_currency->minedMoneyUnlockWindow() + 1;
CHECK(request(c, amount, unlocked, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
CHECK(request(c, amount, unlocked * 2, resp));
CHECK(resp.outs.size() == 1);
CHECK(resp.outs[0].amount == amount);
CHECK(resp.outs[0].outs.size() == unlocked);
return true;
}
| 37.826087
| 120
| 0.66705
|
JacopoDT
|
88420f5b2b55df91aaef763f93e00a825683c381
| 4,976
|
cpp
|
C++
|
libs/hmtslam/src/CHMHMapArc.cpp
|
swt2c/mrpt
|
9b4fd246530ff94bb93f5703e61844c6f67aa0b9
|
[
"BSD-3-Clause"
] | null | null | null |
libs/hmtslam/src/CHMHMapArc.cpp
|
swt2c/mrpt
|
9b4fd246530ff94bb93f5703e61844c6f67aa0b9
|
[
"BSD-3-Clause"
] | null | null | null |
libs/hmtslam/src/CHMHMapArc.cpp
|
swt2c/mrpt
|
9b4fd246530ff94bb93f5703e61844c6f67aa0b9
|
[
"BSD-3-Clause"
] | 1
|
2020-12-30T14:06:37.000Z
|
2020-12-30T14:06:37.000Z
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2020, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "hmtslam-precomp.h" // Precomp header
using namespace mrpt;
using namespace mrpt::slam;
using namespace mrpt::hmtslam;
IMPLEMENTS_SERIALIZABLE(CHMHMapArc, CSerializable, mrpt::hmtslam)
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
CHMHMapArc::CHMHMapArc(
const CHMHMapNode::TNodeID& from, const CHMHMapNode::TNodeID& to,
const THypothesisIDSet& hyps, CHierarchicalMHMap* parent)
: m_hypotheses(hyps),
m_nodeFrom(from),
m_nodeTo(to),
m_parent(parent),
m_arcType(ARC_TYPES, DEFAULT_ARC_TYPE),
m_annotations()
{
// parent will be nullptr only inside a ">>" operation, as a temporal
// initialization of an empty object with the default constructor:
// To the graph:
}
/*---------------------------------------------------------------
Other constructor
---------------------------------------------------------------*/
CHMHMapArc::CHMHMapArc(
CHMHMapNode::Ptr& from, CHMHMapNode::Ptr& to, const THypothesisIDSet& hyps,
CHierarchicalMHMap* parent)
: m_hypotheses(hyps),
m_nodeFrom(),
m_nodeTo(),
m_parent(parent),
m_arcType(ARC_TYPES, DEFAULT_ARC_TYPE),
m_annotations()
{
if (from) m_nodeFrom = from->getID();
if (to) m_nodeTo = to->getID();
// parent will be nullptr only inside a ">>" operation, as a temporal
// initialization of an empty object with the default constructor:
}
/*---------------------------------------------------------------
Destructor
---------------------------------------------------------------*/
CHMHMapArc::~CHMHMapArc()
{
CHMHMapNode::Ptr node;
// To the nodes:
if ((node = m_parent->getNodeByID(m_nodeFrom)))
node->onArcDestruction(this);
if ((node = m_parent->getNodeByID(m_nodeTo))) node->onArcDestruction(this);
// To the graph:
if (m_parent.get()) m_parent->onArcDestruction(this);
}
/*---------------------------------------------------------------
onNodeDestruction
---------------------------------------------------------------*/
void CHMHMapArc::onNodeDestruction(CHMHMapNode* node)
{
MRPT_START
// Check if arc is from/to this node:
if (node->getID() == m_nodeFrom) m_nodeFrom = AREAID_INVALID;
if (node->getID() == m_nodeTo) m_nodeTo = AREAID_INVALID;
MRPT_END
}
uint8_t CHMHMapArc::serializeGetVersion() const { return 0; }
void CHMHMapArc::serializeTo(mrpt::serialization::CArchive& out) const
{
out << m_nodeFrom << m_nodeTo << m_arcType << m_annotations << m_hypotheses;
}
void CHMHMapArc::serializeFrom(
mrpt::serialization::CArchive& in, uint8_t version)
{
switch (version)
{
case 0:
{
in >> m_nodeFrom >> m_nodeTo >> m_arcType >> m_annotations >>
m_hypotheses;
// Find my smart pointer in the HMT map: we MUST have only 1 smrt.
// pointer pointing to the same object!!
CHMHMapArc::Ptr myPtr;
for (auto it = m_parent->m_arcs.begin();
it != m_parent->m_arcs.end(); ++it)
{
if (it->get() == this)
{
myPtr = *it;
break;
}
}
ASSERTMSG_(myPtr, "I cannot be found in my parent HMT map!");
CHMHMapNode::Ptr node;
// It's not necessary since at ::Create this is already done
// (but...check!)
// m_parent->onArcAddition(this);
// To the nodes:
if ((node = m_parent->getNodeByID(m_nodeFrom)))
node->onArcAddition(myPtr);
if ((node = m_parent->getNodeByID(m_nodeTo)))
node->onArcAddition(myPtr);
}
break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);
};
}
/*---------------------------------------------------------------
TArcList::debugDump
---------------------------------------------------------------*/
void TArcList::debugDump()
{
printf("Dumping arcs list: %u elements\n", (unsigned int)size());
for (auto& i : *this)
{
printf(
"\t'%s'\t-> '%s'\n",
i->m_parent->getNodeByID(i->getNodeFrom())->m_label.c_str(),
i->m_parent->getNodeByID(i->getNodeTo())->m_label.c_str());
}
}
void TArcList::read(mrpt::serialization::CArchive& in)
{
uint32_t i, n;
in >> n;
BASE::clear();
for (i = 0; i < n; i++)
{
CHMHMapArc::Ptr theObj = std::make_shared<CHMHMapArc>();
in >> *theObj;
this->push_back(theObj);
}
}
void TArcList::write(mrpt::serialization::CArchive& out) const
{
out.WriteAs<uint32_t>(this->size());
for (const auto& i : *this) out << *i;
}
| 30.341463
| 80
| 0.542605
|
swt2c
|
8842930a3f2c988927dcdc7a2bca9a2f05163bc8
| 11,159
|
cpp
|
C++
|
src/gpu/ocl/gemm/gen12lp_gemm.cpp
|
IvanNovoselov/oneDNN
|
aa47fcd2a03ee5caac119b6417bc66abe3154aab
|
[
"Apache-2.0"
] | null | null | null |
src/gpu/ocl/gemm/gen12lp_gemm.cpp
|
IvanNovoselov/oneDNN
|
aa47fcd2a03ee5caac119b6417bc66abe3154aab
|
[
"Apache-2.0"
] | 1
|
2020-04-17T22:23:01.000Z
|
2020-04-23T21:11:41.000Z
|
src/gpu/ocl/gemm/gen12lp_gemm.cpp
|
IvanNovoselov/oneDNN
|
aa47fcd2a03ee5caac119b6417bc66abe3154aab
|
[
"Apache-2.0"
] | 3
|
2021-07-20T07:40:15.000Z
|
2021-08-03T08:39:17.000Z
|
/*******************************************************************************
* Copyright 2019-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "gpu/ocl/gemm/gen12lp_gemm.hpp"
#include "common/c_types_map.hpp"
#include "common/dnnl_traits.hpp"
#include "common/type_helpers.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
namespace ocl {
struct gen12lp_gemm_driver_params_t {
static constexpr auto block_m = 2048;
static constexpr auto block_n = 2048;
static constexpr auto block_k = 1024;
};
status_t gen12lp_gemm_t::launch_x8x8s32(gemm_exec_ctx_t ctx,
compute::compute_stream_t *compute_stream, const memory_storage_t &a,
const memory_storage_t &b, const memory_storage_t &c, int offset_a,
int offset_b, int offset_c, int lda, int ldb, int ldc, int m, int n,
int k, int beta, int ao, int bo, const memory_storage_t &co,
int offset_co, bool apply_co, bool apply_eltwise, float eltwise_alpha,
float eltwise_beta, float eltwise_scale, bool aligned) const {
auto &kernel = compute_x8x8s32_kernel_[aligned];
assert(kernel);
int unroll_m, unroll_n, block_m, block_n;
gen12lp_gemm_x8x8s32_kernel_t::get_unrolls(unroll_m, unroll_n);
block_m = gen12lp_gemm_driver_params_t::block_m;
block_n = gen12lp_gemm_driver_params_t::block_n;
int kk = ((k + 3) & ~3);
int sizea = block_m * (kk + sizeof(int));
int sizeb = block_n * (kk + sizeof(int));
compute::kernel_arg_list_t arg_list;
arg_list.set(0, a);
arg_list.set(1, b);
arg_list.set(2, c);
arg_list.set(3, (int)offset_a);
arg_list.set(4, (int)offset_b);
arg_list.set(5, (int)offset_c);
arg_list.set(6, (int)lda);
arg_list.set(7, (int)ldb);
arg_list.set(8, (int)ldc);
arg_list.set(9, (int)m);
arg_list.set(10, (int)n);
arg_list.set(11, (int)k);
arg_list.set(12, (int)beta);
arg_list.set(13, (int)ao);
arg_list.set(14, (int)bo);
arg_list.set(15, co);
arg_list.set(16, (int)offset_co);
arg_list.set(17, (int)apply_co);
arg_list.set(18, sizea, nullptr);
arg_list.set(19, sizeb, nullptr);
arg_list.set(20, (int)apply_eltwise);
arg_list.set(21, eltwise_alpha);
arg_list.set(22, eltwise_beta);
arg_list.set(23, eltwise_scale);
size_t nthreads_x = (m + unroll_m - 1) / unroll_m;
size_t nthreads_y = (n + unroll_n - 1) / unroll_n;
size_t lthreads_x = 2;
size_t lthreads_y = 8;
#ifndef CL_VERSION_2_0
while (nthreads_x % lthreads_x)
lthreads_x--;
while (nthreads_y % lthreads_y)
lthreads_y--;
#endif
static constexpr size_t subgroup_size = 16;
size_t gws[3] = {nthreads_x * subgroup_size, nthreads_y, 1};
size_t lws[3] = {lthreads_x * subgroup_size, lthreads_y, 1};
auto nd_range = compute::nd_range_t(gws, lws);
return parallel_for(ctx, nd_range, kernel, arg_list);
}
status_t gen12lp_gemm_t::launch_scale_x8x8s32(gemm_exec_ctx_t ctx,
compute::compute_stream_t *compute_stream,
const memory_storage_t &c_temp, const memory_storage_t &c, char offsetc,
int offset_c, int m, int n, int ldc, float alpha, float beta,
const memory_storage_t &co, int offset_co, bool alpha_is_zero,
bool apply_eltwise, float eltwise_alpha, float eltwise_beta,
float eltwise_scale) const {
auto &kernel = scale_x8x8s32_kernel_;
assert(kernel);
compute::kernel_arg_list_t arg_list;
arg_list.set(0, c_temp);
arg_list.set(1, c);
arg_list.set(2, (int)offsetc);
arg_list.set(3, (int)offset_c);
arg_list.set(4, (int)m);
arg_list.set(5, (int)n);
arg_list.set(6, (int)ldc);
arg_list.set(7, alpha);
arg_list.set(8, beta);
arg_list.set(9, co);
arg_list.set(10, (int)offset_co);
arg_list.set(11, (int)alpha_is_zero);
arg_list.set(12, (int)apply_eltwise);
arg_list.set(13, eltwise_alpha);
arg_list.set(14, eltwise_beta);
arg_list.set(15, eltwise_scale);
int unroll_m, unroll_n;
gen12lp_gemm_scale_x8x8s32_kernel_t::get_unrolls(unroll_m, unroll_n);
size_t nthreads_x = (m + unroll_m - 1) / unroll_m;
size_t nthreads_y = (n + unroll_n - 1) / unroll_n;
size_t lthreads_x = 16;
size_t lthreads_y = 1;
size_t gws[3] = {nthreads_x * lthreads_x, nthreads_y, 1};
size_t lws[3] = {lthreads_x, lthreads_y, 1};
auto nd_range = compute::nd_range_t(gws, lws);
return parallel_for(ctx, nd_range, kernel, arg_list);
}
status_t gen12lp_gemm_t::execute(const gemm_exec_ctx_t &ctx) const {
return execute_standard(ctx);
}
status_t gen12lp_gemm_t::execute_standard(const gemm_exec_ctx_t &ctx) const {
auto a_type = pd()->desc()->a_type;
auto b_type = pd()->desc()->b_type;
auto c_type = pd()->desc()->c_type;
auto *compute_stream
= utils::downcast<compute::compute_stream_t *>(ctx.stream());
auto m = pd()->desc()->m;
auto n = pd()->desc()->n;
auto k = pd()->desc()->k;
bool transa = (pd()->desc()->transa == dnnl_trans);
bool transb = (pd()->desc()->transb == dnnl_trans);
int cmask = 0;
pd()->attr()->zero_points_.get(DNNL_ARG_DST, nullptr, &cmask, nullptr);
char offsetc_char;
if (1 << 1 == cmask)
offsetc_char = 'C';
else if (1 << 0 == cmask)
offsetc_char = 'R';
else
offsetc_char = 'F';
auto lda = pd()->desc()->lda;
auto ldb = pd()->desc()->ldb;
auto ldc = pd()->desc()->ldc;
const int *ao_i32 = nullptr;
const int *bo_i32 = nullptr;
pd()->attr()->zero_points_.get(DNNL_ARG_SRC, nullptr, nullptr, &ao_i32);
pd()->attr()->zero_points_.get(DNNL_ARG_WEIGHTS, nullptr, nullptr, &bo_i32);
auto ao = *ao_i32;
auto bo = *bo_i32;
auto alpha = pd()->alpha();
auto beta = pd()->beta();
auto eltwise_alpha = pd()->eltwise_alpha();
auto eltwise_beta = pd()->eltwise_beta();
auto eltwise_scale = pd()->eltwise_scale();
auto &a = GEMM_CTX_ARG_STORAGE(a);
auto &b = GEMM_CTX_ARG_STORAGE(b);
auto &co = GEMM_CTX_ARG_STORAGE(c_zero_point);
auto &c = GEMM_CTX_ARG_STORAGE(c);
auto temp_buf = ctx.get_scratchpad_grantor().get_memory_storage(
memory_tracking::names::key_gemm_tmp_buffer);
int64_t off_a0
= a.offset() / types::data_type_size(a_type) + pd()->dyn_offset_a;
int64_t off_b0
= b.offset() / types::data_type_size(b_type) + pd()->dyn_offset_b;
int64_t off_c0
= c.offset() / types::data_type_size(c_type) + pd()->dyn_offset_c;
int64_t offset_co
= co.offset() / types::data_type_size(c_type) + pd()->dyn_offset_co;
bool do_compute = pd()->do_compute();
bool do_scale = pd()->do_scale();
status_t status;
int unroll_m, unroll_n;
int block_m, block_n, block_k;
gen12lp_gemm_x8x8s32_kernel_t::get_unrolls(unroll_m, unroll_n);
block_m = gen12lp_gemm_driver_params_t::block_m;
block_n = gen12lp_gemm_driver_params_t::block_n;
block_k = gen12lp_gemm_driver_params_t::block_k;
bool apply_co = true;
bool aligned = false;
int64_t size_k, size_m, size_n;
if (do_compute) {
for (int64_t Bk = 0; Bk < k; Bk += size_k) {
size_k = k - Bk;
bool apply_eltwise = (size_k <= block_k);
if (size_k > block_k) size_k = block_k;
for (int64_t Bm = 0; Bm < m; Bm += size_m) {
size_m = m - Bm;
if (size_m > block_m) size_m = block_m;
auto off_a_src = off_a0
+ (!transa ? (Bm + Bk * lda) : (Bk + Bm * lda));
for (int64_t Bn = 0; Bn < n; Bn += size_n) {
size_n = n - Bn;
if (size_n > block_n) size_n = block_n;
auto off_b_src = off_b0
+ (!transb ? (Bk + Bn * ldb) : (Bn + Bk * ldb));
apply_co = !co.is_null() && !(do_scale || (Bk > 0));
auto offset_co_src = offset_co
+ ((offsetc_char == 'C') ? Bm : 0)
+ ((offsetc_char == 'R') ? Bn : 0);
int eff_beta = ((Bk > 0) || (!do_scale && (beta == 1.0f)))
? 1
: 0;
if (!do_scale) {
auto off_c = off_c0 + Bm + Bn * ldc;
if ((lda & 3) || (ldb & 3) || (ldc & 3)
|| (off_a_src & 3) || (off_b_src & 3)
|| (off_c & 3))
aligned = false;
else
aligned = true;
status = launch_x8x8s32(ctx, compute_stream, a, b, c,
off_a_src, off_b_src, off_c, lda, ldb, ldc,
size_m, size_n, size_k, eff_beta, ao, bo, co,
offset_co_src, apply_co, apply_eltwise,
eltwise_alpha, eltwise_beta, eltwise_scale,
aligned);
if (status) return status;
} else if (do_scale) {
auto off_c = 0 + Bm + Bn * m;
if ((lda & 3) || (ldb & 3) || (ldc & 3)
|| (off_a_src & 3) || (off_b_src & 3)
|| (off_c & 3))
aligned = false;
else
aligned = true;
status = launch_x8x8s32(ctx, compute_stream, a, b,
*temp_buf, off_a_src, off_b_src, off_c, lda,
ldb, m, size_m, size_n, size_k, eff_beta, ao,
bo, co, offset_co_src, apply_co, false,
eltwise_alpha, eltwise_beta, eltwise_scale,
aligned);
if (status) return status;
}
}
}
}
}
bool alpha_is_zero = false;
if (do_scale) {
status = launch_scale_x8x8s32(ctx, compute_stream, *temp_buf, c,
offsetc_char, off_c0, m, n, ldc, alpha, beta, co, offset_co,
(int)alpha_is_zero, true, eltwise_alpha, eltwise_beta,
eltwise_scale);
if (status) return status;
}
return status::success;
}
} // namespace ocl
} // namespace gpu
} // namespace impl
} // namespace dnnl
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
| 36.113269
| 80
| 0.570123
|
IvanNovoselov
|
8845300b68091228befc75b4c2bbc969a7a8389e
| 4,770
|
cc
|
C++
|
tensorflow/lite/kernels/irfft2d_test.cc
|
Stevanus-Christian/tensorflow
|
d44afcf5ca16c5d704c66f891b99eac804e7cd14
|
[
"Apache-2.0"
] | 3
|
2022-03-09T01:39:56.000Z
|
2022-03-30T23:17:58.000Z
|
tensorflow/lite/kernels/irfft2d_test.cc
|
Stevanus-Christian/tensorflow
|
d44afcf5ca16c5d704c66f891b99eac804e7cd14
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/lite/kernels/irfft2d_test.cc
|
Stevanus-Christian/tensorflow
|
d44afcf5ca16c5d704c66f891b99eac804e7cd14
|
[
"Apache-2.0"
] | 1
|
2022-03-22T00:45:15.000Z
|
2022-03-22T00:45:15.000Z
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <stdint.h>
#include <complex>
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/custom_ops_register.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/testing/util.h"
namespace tflite {
namespace ops {
namespace custom {
namespace {
using ::testing::ElementsAreArray;
class Irfft2dOpModel : public SingleOpModel {
public:
Irfft2dOpModel(const TensorData& input, const TensorData& fft_lengths) {
input_ = AddInput(input);
fft_lengths_ = AddInput(fft_lengths);
TensorType output_type = TensorType_FLOAT32;
output_ = AddOutput({output_type, {}});
const std::vector<uint8_t> custom_option;
SetCustomOp("Irfft2d", custom_option, Register_IRFFT2D);
BuildInterpreter({GetShape(input_)});
}
int input() { return input_; }
int fft_lengths() { return fft_lengths_; }
std::vector<float> GetOutput() { return ExtractVector<float>(output_); }
std::vector<int> GetOutputShape() { return GetTensorShape(output_); }
private:
int input_;
int fft_lengths_;
int output_;
};
TEST(Irfft2dOpTest, FftLengthMatchesInputSize) {
Irfft2dOpModel model({TensorType_COMPLEX64, {4, 3}}, {TensorType_INT32, {2}});
// clang-format off
model.PopulateTensor<std::complex<float>>(model.input(), {
{75, 0}, {-6, -1}, {9, 0}, {-10, 5}, {-3, 2}, {-6, 11},
{-15, 0}, {-2, 13}, {-5, 0}, {-10, -5}, {3, -6}, {-6, -11}
});
// clang-format on
model.PopulateTensor<int32_t>(model.fft_lengths(), {4, 4});
ASSERT_EQ(model.Invoke(), kTfLiteOk);
float expected_result[16] = {1, 2, 3, 4, 3, 8, 6, 3, 5, 2, 7, 6, 9, 5, 8, 3};
EXPECT_THAT(model.GetOutput(), ElementsAreArray(expected_result));
}
TEST(Irfft2dOpTest, FftLengthSmallerThanInputSize) {
Irfft2dOpModel model({TensorType_COMPLEX64, {4, 3}}, {TensorType_INT32, {2}});
// clang-format off
model.PopulateTensor<std::complex<float>>(model.input(), {
{75, 0}, {-6, -1}, {9, 0}, {-10, 5}, {-3, 2}, {-6, 11},
{-15, 0}, {-2, 13}, {-5, 0}, {-10, -5}, {3, -6}, {-6, -11}
});
// clang-format on
model.PopulateTensor<int32_t>(model.fft_lengths(), {2, 2});
ASSERT_EQ(model.Invoke(), kTfLiteOk);
float expected_result[4] = {14, 18.5, 20.5, 22};
EXPECT_THAT(model.GetOutput(), ElementsAreArray(expected_result));
}
TEST(Irfft2dOpTest, FftLengthGreaterThanInputSize) {
Irfft2dOpModel model({TensorType_COMPLEX64, {4, 3}}, {TensorType_INT32, {2}});
// clang-format off
model.PopulateTensor<std::complex<float>>(model.input(), {
{75, 0}, {-6, -1}, {9, 0}, {-10, 5}, {-3, 2}, {-6, 11},
{-15, 0}, {-2, 13}, {-5, 0}, {-10, -5}, {3, -6}, {-6, -11}
});
// clang-format on
model.PopulateTensor<int32_t>(model.fft_lengths(), {4, 8});
ASSERT_EQ(model.Invoke(), kTfLiteOk);
// clang-format off
float expected_result[32] = {
0.25, 0.54289322, 1.25, 1.25, 1.25, 1.95710678, 2.25, 1.25,
1.25, 2.85355339, 4.25, 3.91421356, 2.75, 2.14644661, 1.75, 1.08578644,
3., 1.43933983, 0.5, 2.14644661, 4., 3.56066017, 2.5, 2.85355339,
5.625, 3.65533009, 1.375, 3.3017767, 5.125, 2.59466991, 0.375, 2.9482233
};
// clang-format on
EXPECT_THAT(model.GetOutput(), ElementsAreArray(expected_result));
}
TEST(Irfft2dOpTest, InputDimsGreaterThan2) {
Irfft2dOpModel model({TensorType_COMPLEX64, {2, 2, 3}},
{TensorType_INT32, {2}});
// clang-format off
model.PopulateTensor<std::complex<float>>(model.input(), {
{30., 0.}, {-5, -3.}, { -4., 0.},
{-10., 0.}, {1., 7.}, { 0., 0.},
{58., 0.}, {-18., 6.}, { 26., 0.},
{-18., 0.}, { 14., 2.}, {-18., 0.}
});
// clang-format on
model.PopulateTensor<int32_t>(model.fft_lengths(), {2, 4});
ASSERT_EQ(model.Invoke(), kTfLiteOk);
float expected_result[16] = {1., 2., 3., 4., 3., 8., 6., 3.,
5., 2., 7., 6., 7., 3., 23., 5.};
EXPECT_THAT(model.GetOutput(), ElementsAreArray(expected_result));
}
} // namespace
} // namespace custom
} // namespace ops
} // namespace tflite
| 35.073529
| 80
| 0.638365
|
Stevanus-Christian
|