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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43b98881dd151dc94f5df25db154a16941658a82 | 3,289 | cpp | C++ | problems18apr/scootchhop/correct.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-11T01:43:27.000Z | 2021-12-11T01:43:27.000Z | problems18apr/scootchhop/correct.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | null | null | null | problems18apr/scootchhop/correct.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-15T07:04:29.000Z | 2021-12-15T07:04:29.000Z | #include <bits/stdc++.h>
using namespace std;
template <typename T>
using V = vector<T>;
typedef long double ld;
typedef long long ll;
#define FO(i, N) for (int (i) = 0; (i) < (N); ++(i))
#define FOll(i, N) for (ll (i) = 0; (i) < (N); ++(i))
#define READALL(c) for (auto &e : c) { cin >> e; }
#define PRINTALL(c) for (const auto &e : c) { cout << e << " "; } cout << "\n";
#define MP(x, y) (make_pair((x), (y)))
#define MT(...) make_tuple(__VA_ARGS__)
#define ALL(x) begin(x), end(x)
#define D(x...) fprintf(stderr, x)
const int MAXN = 500, MAXQ = 1e7;
int R, C, Q;
ll DPul[MAXN+5][MAXN+5], DPbr[MAXN+5][MAXN+5], G[MAXN+5][MAXN+5], GG[MAXN+5][MAXN+5], ans[MAXQ];
tuple<int,int,int,int> Qs[MAXQ];
void fill_dp(int r, int c, int minr, int minc, int maxr, int maxc) {
for (int i = minr-1; i <= maxr+1; ++i)
for (int j = minc-1; j <= maxc+1; ++j)
DPul[i][j] = DPbr[i][j] = -1e18;
DPul[r+1][c]=0;
for (int i = r; i >= minr; --i)
for (int j = c; j >= minc; --j)
DPul[i][j] = max(DPul[i+1][j],DPul[i][j+1])+G[i][j];
DPbr[r-1][c]=0;
for (int i = r; i <= maxr; ++i)
for (int j = c; j <= maxc; ++j)
DPbr[i][j] = max(DPbr[i-1][j],DPbr[i][j-1])+G[i][j];
}
void dc(int minr, int minc, int maxr, int maxc, vector<int> query_inds) {
if (minr > maxr || minc > maxc)
return;
int r, c = (maxc+minc)/2;
vector<int> query_inds_tmp;
for (int i : query_inds) {
int qr, qc, qrr, qcc;
tie(qr, qc, qrr, qcc) = Qs[i];
if (qr < minr || qc < minc || qr > maxr || qc > maxc)
continue;
if (qrr < minr || qcc < minc || qrr > maxr || qcc > maxc)
continue;
query_inds_tmp.push_back(i);
}
query_inds = query_inds_tmp;
if (query_inds.size() == 0)
return;
for (r = minr; r <= maxr; ++r) {
fill_dp(r, c, minr, minc, maxr, maxc);
for (int i : query_inds) {
int qr, qc, qrr, qcc;
tie(qr, qc, qrr, qcc) = Qs[i];
if (qr <= r && qrr >= r && qc <= c && qcc >= c) {
ans[i] = max(ans[i], DPul[qr][qc]+DPbr[qrr][qcc]-G[r][c]);
}
}
}
r = (minr+maxr)/2;
for (c = minc; c <= maxc; ++c) if (c != (maxc+minc)/2 && G[r][c] != '1') {
fill_dp(r, c, minr, minc, maxr, maxc);
for (int i : query_inds) {
int qr, qc, qrr, qcc;
tie(qr, qc, qrr, qcc) = Qs[i];
if (qr <= r && qrr >= r && qc <= c && qcc >= c) {
ans[i] = max(ans[i], DPul[qr][qc]+DPbr[qrr][qcc]-G[r][c]);
}
}
}
dc(minr, minc, (maxr+minr)/2-1, (maxc+minc)/2-1, query_inds);
dc(minr, (maxc+minc)/2+1, (maxr+minr)/2-1, maxc, query_inds);
dc((maxr+minr)/2+1, minc, maxr, (maxc+minc)/2-1, query_inds);
dc((maxr+minr)/2+1, (maxc+minc)/2+1, maxr, maxc, query_inds);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> R >> C;
FO(i,R) FO(j,C) {
cin >> GG[i+1][j+1];
G[i+1][j+1] = max(GG[i+1][j+1],0ll);
}
cin >> Q;
V<int> all_inds;
FO(i,Q) {
int x,y,xx,yy;
cin>>x>>y>>xx>>yy;
Qs[i] = make_tuple(x,y,xx,yy);
all_inds.push_back(i);
}
if(Q == 0) {
Q++;
Qs[0] = make_tuple(1, 1, R, C);
all_inds.push_back(0);
}
fill(ans,ans+Q,-1e18);
dc(1,1,R,C,all_inds);
for(int i = 0; i < Q; i++) {
int x,y,xx,yy;
tie(x, y, xx, yy) = Qs[i];
if (GG[x][y] < 0) {
ans[i] += GG[x][y];
}
if (GG[xx][yy] < 0) {
ans[i] += GG[xx][yy];
}
}
FO(i,Q) cout << ans[i] << "\n";
}
| 26.739837 | 96 | 0.512618 | Gomango999 |
43be1349dd39e6f7f2f7117e39ae70ec276c8839 | 1,413 | cpp | C++ | kafka_configuration.cpp | mexicowilly/Chucho | f4235420437eb2078ab592540c0d729b7b9a3c10 | [
"Apache-2.0"
] | 4 | 2016-12-06T05:33:29.000Z | 2017-12-17T17:04:25.000Z | kafka_configuration.cpp | mexicowilly/Chucho | f4235420437eb2078ab592540c0d729b7b9a3c10 | [
"Apache-2.0"
] | 147 | 2016-09-05T14:00:46.000Z | 2021-08-24T14:43:07.000Z | kafka_configuration.cpp | mexicowilly/Chucho | f4235420437eb2078ab592540c0d729b7b9a3c10 | [
"Apache-2.0"
] | 4 | 2017-11-08T04:12:39.000Z | 2022-01-04T06:40:16.000Z | /*
* Copyright 2013-2021 Will Mason
*
* 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 <chucho/kafka_configuration.hpp>
#include <chucho/exception.hpp>
namespace chucho
{
kafka_configuration::kafka_configuration(const std::map<std::string, std::string>& key_values)
: conf_(rd_kafka_conf_new())
{
char msg[1024];
for (auto& p : key_values)
{
auto rc = rd_kafka_conf_set(conf_, p.first.c_str(), p.second.c_str(), msg, sizeof(msg));
if (rc != RD_KAFKA_CONF_OK)
throw exception("kafka_writer_factory: Error setting Kafka configuration (" + p.first + ", " + p.second + "): " + msg);
}
}
kafka_configuration::~kafka_configuration()
{
if (conf_ != nullptr)
rd_kafka_conf_destroy(conf_);
}
rd_kafka_conf_t* kafka_configuration::get_conf()
{
auto local = conf_;
conf_ = nullptr;
return local;
}
}
| 28.836735 | 131 | 0.682944 | mexicowilly |
43c0d87b57b5254bb67462e977d11d0d4644067f | 1,995 | hpp | C++ | cpp/godot-cpp/include/gen/TextureLayered.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/include/gen/TextureLayered.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/include/gen/TextureLayered.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #ifndef GODOT_CPP_TEXTURELAYERED_HPP
#define GODOT_CPP_TEXTURELAYERED_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Image.hpp"
#include "Resource.hpp"
namespace godot {
class Image;
class TextureLayered : public Resource {
struct ___method_bindings {
godot_method_bind *mb__get_data;
godot_method_bind *mb__set_data;
godot_method_bind *mb_create;
godot_method_bind *mb_get_depth;
godot_method_bind *mb_get_flags;
godot_method_bind *mb_get_format;
godot_method_bind *mb_get_height;
godot_method_bind *mb_get_layer_data;
godot_method_bind *mb_get_width;
godot_method_bind *mb_set_data_partial;
godot_method_bind *mb_set_flags;
godot_method_bind *mb_set_layer_data;
};
static ___method_bindings ___mb;
public:
static void ___init_method_bindings();
static inline const char *___get_class_name() { return (const char *) "TextureLayered"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
enum Flags {
FLAG_MIPMAPS = 1,
FLAG_REPEAT = 2,
FLAG_FILTER = 4,
FLAGS_DEFAULT = 4,
};
// constants
// methods
Dictionary _get_data() const;
void _set_data(const Dictionary data);
void create(const int64_t width, const int64_t height, const int64_t depth, const int64_t format, const int64_t flags = 4);
int64_t get_depth() const;
int64_t get_flags() const;
Image::Format get_format() const;
int64_t get_height() const;
Ref<Image> get_layer_data(const int64_t layer) const;
int64_t get_width() const;
void set_data_partial(const Ref<Image> image, const int64_t x_offset, const int64_t y_offset, const int64_t layer, const int64_t mipmap = 0);
void set_flags(const int64_t flags);
void set_layer_data(const Ref<Image> image, const int64_t layer);
};
}
#endif | 29.338235 | 245 | 0.777444 | GDNative-Gradle |
43c261199e50810e5a13b05fa96694b0dac32d1d | 1,273 | cpp | C++ | src/ProgramState.cpp | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | src/ProgramState.cpp | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | src/ProgramState.cpp | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | #include "ProgramState.h"
using namespace std;
ProgramState::ProgramState(int numLines){
m_numLines = numLines;
m_nextLine = 1;
m_line = 0;
m_over = 0;
}
void ProgramState::updateVal(std::string var, int val){
if (m_varMap.count(var) > 0){
m_varMap[var] = val;
} else {
m_varMap.insert(std::pair<string, int>(var, val));
}
}
int ProgramState::getVal(std::string var){
return m_varMap.at(var);
}
void ProgramState::toStream(std::string var, std::ostream& outf){
map<std::string, int>::iterator it = m_varMap.find(var);
outf << it->first << " : " << it->second << std::endl;
}
void ProgramState::toStreamAll(std::ostream &outf){
map<std::string, int>::iterator it;
for (it = m_varMap.begin(); it != m_varMap.end(); it++){
outf << it->first << " : " << it->second << std::endl;
}
}
int ProgramState::getCurrLine(){
return m_line;
}
void ProgramState::goNextLine(){
m_line = m_nextLine;
}
void ProgramState::updateNextLine(int val){
m_nextLine = val;
}
int ProgramState::getReturnLine(){
int temp = m_stack.top();
m_stack.pop();
return temp;
}
void ProgramState::addReturnLine(int val){
m_stack.push(val);
}
void ProgramState::endProgram(){
m_over = 1;
}
bool ProgramState::isOver(){
if (m_over) {
return true;
}
return false;
}
| 18.720588 | 65 | 0.6685 | tsehon |
43c2b4114ff84dd0e8d6a3a8c442b2ce1e70021e | 1,336 | cpp | C++ | Aurora/Aurora/sysserv/sysmem.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | 8 | 2021-07-19T04:46:35.000Z | 2022-03-12T17:56:00.000Z | Aurora/Aurora/sysserv/sysmem.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | null | null | null | Aurora/Aurora/sysserv/sysmem.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | null | null | null | /**
** Copyright (C) Manas Kamal Choudhury 2021
**
** sysmem.cpp -- System Memory Callbacks
**
** /PORJECT - Aurora {Xeneva}
** /AUTHOR - Manas Kamal Choudhury
**
**/
#ifdef ARCH_X64
#include <arch\x86_64\mmngr\vmmngr.h>
#include <arch\x86_64\thread.h>
#include <_null.h>
#include <stdio.h>
#endif
void map_shared_memory (uint16_t dest_id,uint64_t pos, size_t size) {
x64_cli ();
thread_t* t = thread_iterate_ready_list (dest_id);
if (t == NULL) {
t = thread_iterate_block_list(dest_id);
}
uint64_t *current_cr3 = (uint64_t*)get_current_thread()->cr3;
uint64_t *cr3 = (uint64_t*)t->cr3;
for (int i = 0; i < size/4096; i++) {
if (map_page ((uint64_t)pmmngr_alloc(),pos + i * 4096, PAGING_USER)) {
cr3[pml4_index(pos + i * 4096)] = current_cr3[pml4_index(pos + i * 4096)];
}
}
}
void unmap_shared_memory (uint16_t dest_id, uint64_t pos, size_t size) {
x64_cli ();
thread_t* t = thread_iterate_ready_list (dest_id);
if (t == NULL) {
t = thread_iterate_block_list(dest_id);
}
uint64_t *cr3 = (uint64_t*)t->cr3;
for (int i = 0; i < size/4096; i++) {
unmap_page (pos + i * 4096);
unmap_page_ex(cr3,pos + i * 4096, false);
}
}
uint64_t sys_get_used_ram () {
x64_cli ();
return pmmngr_get_used_ram ();
}
uint64_t sys_get_free_ram () {
x64_cli ();
return pmmngr_get_free_ram ();
} | 21.901639 | 79 | 0.661677 | manaskamal |
43c7cc25c6446ea2501d0df1085f5e9efca7614e | 1,424 | cpp | C++ | code/binary-tests/binary/converters/little_endian_converter_tests.cpp | afxres/binary-cxx | ef84b0d5324c5add5ea8a09340471efc6221f91f | [
"MIT"
] | 1 | 2019-11-21T06:37:04.000Z | 2019-11-21T06:37:04.000Z | code/binary-tests/binary/converters/little_endian_converter_tests.cpp | afxres/binary-cxx | ef84b0d5324c5add5ea8a09340471efc6221f91f | [
"MIT"
] | null | null | null | code/binary-tests/binary/converters/little_endian_converter_tests.cpp | afxres/binary-cxx | ef84b0d5324c5add5ea8a09340471efc6221f91f | [
"MIT"
] | 1 | 2019-11-26T16:47:56.000Z | 2019-11-26T16:47:56.000Z | #include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/mpl/list.hpp>
#include <binary/converters/little_endian_converter.hpp>
namespace mikodev::binary::tests::converters::little_endian_converter_tests
{
namespace mk = mikodev::binary;
namespace mkc = mikodev::binary::converters;
using __test_types = boost::mpl::list<int8_t, int32_t, uint16_t, uint64_t>;
BOOST_AUTO_TEST_CASE_TEMPLATE(little_endian_converter__length, T, __test_types)
{
auto converter = mkc::little_endian_converter<T>();
BOOST_REQUIRE_EQUAL(sizeof(T), converter.length());
}
template <typename TArgs>
void __test_encode_decode(TArgs source)
{
byte_t buffer[16] = { static_cast<byte_t>(0) };
auto converter = mkc::little_endian_converter<TArgs>();
auto allocator = mk::allocator(buffer, sizeof(buffer));
converter.encode(allocator, source);
BOOST_REQUIRE_EQUAL(sizeof(TArgs), allocator.length());
auto span = allocator.as_span();
auto result = converter.decode(span);
BOOST_REQUIRE_EQUAL(source, result);
BOOST_REQUIRE_EQUAL(sizeof(TArgs), span.length());
}
auto __int64_data = std::vector<int64_t>{ -65536, 0x11223344AABBCCDD };
BOOST_DATA_TEST_CASE(little_endian_converter__encode_decode__int64, __int64_data)
{
__test_encode_decode<int64_t>(sample);
}
}
| 33.904762 | 85 | 0.706461 | afxres |
43cb34aed7b12129866c93ee433fbf8af463367c | 731 | cpp | C++ | alg_two.cpp | Francenzo/face_auth | fa25ce3d5ea6ce35005f8facf1e5b578fadf11fc | [
"MIT"
] | null | null | null | alg_two.cpp | Francenzo/face_auth | fa25ce3d5ea6ce35005f8facf1e5b578fadf11fc | [
"MIT"
] | null | null | null | alg_two.cpp | Francenzo/face_auth | fa25ce3d5ea6ce35005f8facf1e5b578fadf11fc | [
"MIT"
] | 2 | 2018-04-12T01:17:15.000Z | 2018-04-14T01:27:27.000Z | /*
*
* Second Algorithm to test image
* against known dataset
*
*/
#include "alg_two.hpp"
Algorithm_Two::Algorithm_Two(vector<Mat> users, vector<int> labels)
{
model = createFisherFaceRecognizer();
model->train(users, labels);
}
int Algorithm_Two::compare(Mat face)
{
int predictedLabel = -1;
double confidence = 0.0;
model->predict(face, predictedLabel, confidence);
// string result_message = format("Predicted class = %d | confidence = %f", predictedLabel, confidence);
// cout << result_message << endl;
if (confidence < ACCEPTANCE_THRESHOLD)
{
// cout << "accepted" << endl;
return predictedLabel;
}
else
{
return -1;
}
}
| 20.885714 | 110 | 0.618331 | Francenzo |
43d2167bc0f921d659a6171bad2ac8567736b563 | 6,801 | hpp | C++ | packages/monte_carlo/collision/neutron/src/MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/collision/neutron/src/MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/collision/neutron/src/MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp
//! \author Eli Moll
//! \brief Decoupled photon production reaction factory class declaration
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_DECOUPLED_PHOTON_PRODUCTION_REACTION_ACE_FACTORY_HPP
#define MONTE_CARLO_DECOUPLED_PHOTON_PRODUCTION_REACTION_ACE_FACTORY_HPP
// Standard Includes
#include <memory>
#include <unordered_map>
#include <unordered_set>
// FRENSIE Includes
#include "MonteCarlo_DecoupledPhotonProductionReaction.hpp"
#include "MonteCarlo_PhotonProductionNuclearScatteringDistributionACEFactory.hpp"
#include "MonteCarlo_NeutronNuclearReactionACEFactory.hpp"
#include "MonteCarlo_NuclearReactionType.hpp"
#include "Utility_UnivariateDistribution.hpp"
#include "Utility_HashBasedGridSearcher.hpp"
#include "Utility_ArrayView.hpp"
#include "Utility_Vector.hpp"
namespace MonteCarlo{
/*! The decoupled photon production reaction factory class
* \details This factory class stores all of the data blocks found in the
* ACE tables that describe specific reactions (except for fission reactions).
* The array parameters used in the class constructor have the same name as
* the corresponding ACE data block.
*/
class DecoupledPhotonProductionReactionACEFactory : public NeutronNuclearReactionACEFactory
{
public:
//! Constructor
DecoupledPhotonProductionReactionACEFactory(
const std::string& table_name,
const double atomic_weight_ratio,
const double temperature,
const std::shared_ptr<const std::vector<double> >& energy_grid,
const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >&
grid_searcher,
const SimulationProperties& properties,
const Data::XSSNeutronDataExtractor& raw_nuclide_data );
//! Destructor
~DecoupledPhotonProductionReactionACEFactory()
{ /* ... */ }
//! Create the yield based photon production reactions
void createPhotonProductionReactions(
std::unordered_map<unsigned,std::shared_ptr<const DecoupledPhotonProductionReaction> >&
yield_based_photon_production_reactions ) const;
protected:
//! Create the reaction type ordering map
static void createReactionOrderingMap(
const Utility::ArrayView<const double>& mtrp_block,
std::unordered_map<unsigned,unsigned>& reaction_ordering );
//! Create the total reaction
void createTotalReaction(
const Utility::ArrayView<const double>& total_xs_block,
const std::shared_ptr<const std::vector<double> >& energy_grid,
const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >&
grid_searcher,
const double temperature );
//! Parse the SIGP Block
static void parseSIGP(
const std::string& table_name,
const size_t energy_grid_size,
const Utility::ArrayView<const double>& lsigp_block,
const Utility::ArrayView<const double>& sigp_block,
const std::unordered_map<unsigned,unsigned>& reaction_ordering,
std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map,
std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_values_map,
std::unordered_map<unsigned,std::shared_ptr<std::vector<double> > >& xs_based_map,
std::unordered_map<unsigned,unsigned>& threshold_energy_map,
std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map );
//! Construct the base reaction map
void constructBaseReactionMap(
std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map,
std::unordered_map<NuclearReactionType,std::shared_ptr<const NeutronNuclearReaction> >& base_reaction_map,
std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map );
// Construct a map of photon MT numbers to yield distributions
void constructMTPYieldDistributions(
const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map,
const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_values_map );
// Construct a map of base reaction types to yield distribution arrays
void constructMTYieldArrays(
const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map,
const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map );
private:
// Initialize the yield based photon production reactions
void initializeYieldBasedPhotonProductionReactions(
const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map,
const double temperature,
const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map,
const std::unordered_map<NuclearReactionType,std::shared_ptr<const NeutronNuclearReaction> >& base_reaction_map,
const SimulationProperties& properties,
PhotonProductionNuclearScatteringDistributionACEFactory& photon_production_dist_factory );
// Initialize the yield based photon production reactions
void initializeCrossSectionBasedPhotonProductionReactions(
const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map,
const double temperature,
const std::unordered_map<unsigned,unsigned>& threshold_energy_map,
const std::unordered_map<unsigned,std::shared_ptr<std::vector<double> > >& xs_based_map,
const std::shared_ptr<const std::vector<double> >& energy_grid,
const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >&
grid_searcher,
const SimulationProperties& properties,
PhotonProductionNuclearScatteringDistributionACEFactory& photon_production_dist_factory );
// A map of the photon production reactions
std::unordered_map<unsigned,std::shared_ptr<const DecoupledPhotonProductionReaction> >
d_photon_production_reactions;
// A map of the nuclear reaction type to associated array of TabularDistributions
std::unordered_map<NuclearReactionType,std::vector<std::shared_ptr<const Utility::UnivariateDistribution> > >
d_mt_yield_distributions;
// A map of photon production reaction MT numbers to shared pointers of
// Tabular distributions
std::unordered_map<unsigned,std::shared_ptr<const Utility::UnivariateDistribution> >
d_mtp_yield_distributions_map;
// Total reaction
std::shared_ptr<const NeutronNuclearReaction> d_total_reaction;
};
} // end MonteCarlo namespace
#endif // end MONTE_CARLONUCLEAR_REACTION_ACE_FACTORY_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_NeutronNuclearReactionACEFactory.hpp
//---------------------------------------------------------------------------//
| 45.039735 | 119 | 0.745185 | bam241 |
43d581eedb237f13a56a3f01cdf5ade8d4fa393a | 440 | cpp | C++ | src/GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.cpp | Sushiwave/graphics-lib | c303e9fb9f11276230a09b45581cdbefa8d2a356 | [
"MIT"
] | 1 | 2020-07-13T18:10:33.000Z | 2020-07-13T18:10:33.000Z | src/GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.cpp | Sushiwave/graphics-lib | c303e9fb9f11276230a09b45581cdbefa8d2a356 | [
"MIT"
] | null | null | null | src/GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.cpp | Sushiwave/graphics-lib | c303e9fb9f11276230a09b45581cdbefa8d2a356 | [
"MIT"
] | null | null | null | #include <GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.hpp>
namespace cg
{
TextureSamplerDescriptor::TextureSamplerDescriptor() noexcept
{
filter = TextureFilter::point;
addressU = TextureAddressMode::clamp;
addressV = TextureAddressMode::clamp;
addressW = TextureAddressMode::clamp;
maxAnisotropy = 0;
borderColor = cpp::Vector4D<float>(0.0f, 0.0f, 0.0f, 0.0f);
}
} | 24.444444 | 113 | 0.770455 | Sushiwave |
43e17202b3aeb80911d8381f074a4a1bfe0c371f | 2,948 | cpp | C++ | sigpack/demo_c++/sp_demo_107_1.cpp | mjeronimo/carma-utils | f39ae9b52e43e3d38f938d2327d786808c9819b5 | [
"Apache-2.0"
] | 1 | 2021-12-19T08:18:08.000Z | 2021-12-19T08:18:08.000Z | sigpack/demo_c++/sp_demo_107_1.cpp | mjeronimo/carma-utils | f39ae9b52e43e3d38f938d2327d786808c9819b5 | [
"Apache-2.0"
] | 57 | 2020-05-07T20:34:02.000Z | 2022-03-31T20:04:50.000Z | sigpack/demo_c++/sp_demo_107_1.cpp | mjeronimo/carma-utils | f39ae9b52e43e3d38f938d2327d786808c9819b5 | [
"Apache-2.0"
] | 4 | 2021-05-25T22:38:41.000Z | 2022-03-09T04:35:47.000Z | #include <sigpack.h>
using namespace arma;
using namespace sp;
int main()
{
int r=480, c=640;
mat x(r,c);
cx_mat X(r,c);
clock_t tic;
FFTW X_2d(r,c, FFTW_MEASURE);
x.randn();
#if 1
// X_2d.export_wisdom_fft("wisd_fft.txt");
// X_2d.import_wisdom_file("wisd_fft.txt");
std::string str_fft = "\
(fftw-3.3.5 fftw_wisdom #x4be12fff #x7b2df9b2 #xa5975329 #x385b0041 \
(fftw_codelet_hc2cf_32 0 #x11048 #x11048 #x0 #x882273a3 #x56a533d6 #xc6c3347e #xd190e241) \
(fftw_dft_vrank_geq1_register 0 #x10048 #x10048 #x0 #x099817e7 #xc596b28c #xe506412c #x581cf2d0) \
(fftw_rdft2_rank_geq2_register 0 #x11048 #x11048 #x0 #xed40bad3 #x93c23437 #xaf3711ed #x603ee510) \
(fftw_rdft2_vrank_geq1_register 0 #x11048 #x11048 #x0 #x1a6357c6 #x413f903b #x74fe70f1 #xfccb5c54) \
(fftw_rdft_rank0_register 3 #x11048 #x11048 #x0 #x02d4eca5 #x884a04c6 #x3f0ad214 #xda717200) \
(fftw_dft_buffered_register 0 #x11048 #x11048 #x0 #x6196ea82 #x099f9b85 #x08198834 #xe7593275) \
(fftw_codelet_t1_10 0 #x10048 #x10048 #x0 #xba1708ce #x154e0e87 #x86aebd39 #xcb9e43fe) \
(fftw_rdft_vrank_geq1_register 1 #x11048 #x11048 #x0 #x081f12db #xc5b1275f #x5907e52d #x646a8914) \
(fftw_dft_r2hc_register 0 #x11048 #x11048 #x0 #x514942d9 #xe0534dce #x7d1dcd63 #xde881c5a) \
(fftw_codelet_n1_64 0 #x10048 #x10048 #x0 #x9dcd7b03 #xdf2d4251 #x0230d342 #xde1fe96d) \
(fftw_dft_r2hc_register 0 #x11048 #x11048 #x0 #x43917e3e #x5c1ab09e #xdc26854f #x352833a8) \
(fftw_codelet_r2cf_15 0 #x11048 #x11048 #x0 #x251274f4 #x219f0dbb #x0c38f4e4 #xf19e1c79) \
(fftw_dft_nop_register 0 #x11048 #x11048 #x0 #xc1cc28d6 #x5c67e01b #x280816eb #x7ee0ce02) \
(fftw_codelet_r2cf_32 2 #x11048 #x11048 #x0 #xc267a0b3 #xc28de71d #x550f0573 #x959c40e7) \
(fftw_codelet_n1_64 0 #x10048 #x10048 #x0 #x101f223c #xcff4353b #xd4a553bb #xe3ff9319) \
(fftw_dft_buffered_register 0 #x11048 #x11048 #x0 #x9973ff81 #x0b0fdaf1 #xfd5496b5 #xfe9c4fba) \
(fftw_codelet_t1_10 0 #x10048 #x10048 #x0 #x47334bf5 #x898f072c #x86c99502 #xe82acf7f) \
(fftw_rdft_rank0_register 2 #x11048 #x11048 #x0 #x5c2cc86a #x3d86b0c3 #xe3aeadc0 #xdc7e28da) \
(fftw_rdft2_nop_register 0 #x11048 #x11048 #x0 #xf80d9535 #x1b15b669 #x8ee1f97f #x42fa82cd))";
X_2d.import_wisdom_string(str_fft);
tic = clock();
X = fft2(x);
cout << "FFT Time using arma::fft2()= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl;
tic = clock();
X = X_2d.fft2(x);
cout << "FFTW Time using Wisdom= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl;
#else
tic = clock();
X = fft2(x);
cout << "FFT Time using arma::fft2()= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl;
tic = clock();
X = X_2d.fft2(x);
cout << "FFTW Time without Wisdom= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl;
#endif
return 0;
}
| 46.793651 | 107 | 0.678087 | mjeronimo |
43f310264c59322eaeed705c11dc3de70a8bcb0d | 924 | hpp | C++ | include/Nazara/Utility/TriangleIterator.hpp | gogo2464/NazaraEngine | f1a00c36cb27d9f07d1b7db03313e0038d9a7d00 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 376 | 2015-01-09T03:14:48.000Z | 2022-03-26T17:59:18.000Z | include/Nazara/Utility/TriangleIterator.hpp | gogo2464/NazaraEngine | f1a00c36cb27d9f07d1b7db03313e0038d9a7d00 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 252 | 2015-01-21T17:34:39.000Z | 2022-03-20T16:15:50.000Z | include/Nazara/Utility/TriangleIterator.hpp | gogo2464/NazaraEngine | f1a00c36cb27d9f07d1b7db03313e0038d9a7d00 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 104 | 2015-01-18T11:03:41.000Z | 2022-03-11T05:40:47.000Z | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_TRIANGLEITERATOR_HPP
#define NAZARA_TRIANGLEITERATOR_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Enums.hpp>
#include <Nazara/Utility/IndexMapper.hpp>
namespace Nz
{
class SubMesh;
class NAZARA_UTILITY_API TriangleIterator
{
public:
TriangleIterator(PrimitiveMode primitiveMode, const IndexBuffer& indexBuffer);
TriangleIterator(const SubMesh& subMesh);
~TriangleIterator() = default;
bool Advance();
UInt32 operator[](std::size_t i) const;
void Unmap();
private:
PrimitiveMode m_primitiveMode;
UInt32 m_triangleIndices[3];
IndexMapper m_indexMapper;
std::size_t m_currentIndex;
std::size_t m_indexCount;
};
}
#endif // NAZARA_TRIANGLEITERATOR_HPP
| 22.536585 | 81 | 0.761905 | gogo2464 |
43f4b888eb585a1e6c8e170a34860d08500e8372 | 979 | cc | C++ | 2016/1a/A.cc | golmansax/google-code-jam | 4486db353b19a5d61512aee8d6350aca75a5ab56 | [
"MIT"
] | null | null | null | 2016/1a/A.cc | golmansax/google-code-jam | 4486db353b19a5d61512aee8d6350aca75a5ab56 | [
"MIT"
] | null | null | null | 2016/1a/A.cc | golmansax/google-code-jam | 4486db353b19a5d61512aee8d6350aca75a5ab56 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <deque>
using namespace std;
int main() {
int n_cases;
cin >> n_cases;
for (int i_case = 0; i_case < n_cases; i_case++) {
string s;
cin >> s;
deque<char> d;
d.push_front(s[0]);
for (int i = 1; i < s.size(); i++) {
// Compare the two deques
deque<char> front(d);
front.push_front(s[i]);
deque<char> back(d);
back.push_back(s[i]);
bool yay_front = true;
for (int j = 0; j < front.size(); j++) {
if ((int)back[j] > (int)front[j]) {
yay_front = false;
break;
} else if ((int)back[j] < (int)front[j]) {
yay_front = true;
break;
}
}
if (yay_front) { d.push_front(s[i]); }
else { d.push_back(s[i]); }
}
printf("Case #%d: ", i_case + 1);
for (int i = 0; i < d.size(); i++) {
cout << d[i];
}
cout << endl;
}
return 0;
}
| 20.395833 | 52 | 0.489275 | golmansax |
43f514a3acda8fcf155cee5cbe556503c8fc131f | 709 | cpp | C++ | Dynamic Programming/Minimizing Coins.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T12:30:13.000Z | 2022-02-12T13:59:20.000Z | Dynamic Programming/Minimizing Coins.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T11:09:41.000Z | 2022-02-12T11:55:49.000Z | Dynamic Programming/Minimizing Coins.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | null | null | null | # include <bits/stdc++.h>
# define ll long long
# define all(x) x.begin(), x.end()
# define fastio ios_base::sync_with_stdio(false); cin.tie(NULL)
# define ten6 (1e6+1.5)
using namespace std;
ll dp [(int)ten6]{0};
vector <int> c;
ll solve (int x){
if (x==0) return 0;
if (dp[x]) return dp[x];
ll re=ten6;
for (auto v:c) {
if (v>x) continue;
re=min(re,1+solve(x-v));
}
return dp[x]=re;
}
int main()
{
fastio;
int n,x;
cin>>n>>x;
c.assign(n,0);
for (auto &v:c){
cin>>v;
dp[v]=1;
}
ll re=solve(x);
if (re<(ll)(ten6))
cout<<solve(x)<<'\n';
else cout<<-1<<'\n';
return 0;
} | 19.694444 | 64 | 0.48519 | DecSP |
43f6e016e33e25ba99f7b91e68ce3337e2adcf36 | 5,225 | hpp | C++ | src/mlpack/methods/softmax_regression/softmax_regression_impl.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/softmax_regression/softmax_regression_impl.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/softmax_regression/softmax_regression_impl.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file softmax_regression_impl.hpp
* @author Siddharth Agrawal
*
* Implementation of softmax regression.
*/
#ifndef __MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP
#define __MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP
// In case it hasn't been included yet.
#include "softmax_regression.hpp"
namespace mlpack {
namespace regression {
template<template<typename> class OptimizerType>
SoftmaxRegression<OptimizerType>::
SoftmaxRegression(const size_t inputSize,
const size_t numClasses,
const bool fitIntercept) :
numClasses(numClasses),
lambda(0.0001),
fitIntercept(fitIntercept)
{
SoftmaxRegressionFunction::InitializeWeights(parameters,
inputSize, numClasses,
fitIntercept);
}
template<template<typename> class OptimizerType>
SoftmaxRegression<OptimizerType>::SoftmaxRegression(const arma::mat& data,
const arma::Row<size_t>& labels,
const size_t numClasses,
const double lambda,
const bool fitIntercept) :
numClasses(numClasses),
lambda(lambda),
fitIntercept(fitIntercept)
{
SoftmaxRegressionFunction regressor(data, labels, numClasses,
lambda, fitIntercept);
OptimizerType<SoftmaxRegressionFunction> optimizer(regressor);
parameters = regressor.GetInitialPoint();
Train(optimizer);
}
template<template<typename> class OptimizerType>
SoftmaxRegression<OptimizerType>::SoftmaxRegression(
OptimizerType<SoftmaxRegressionFunction>& optimizer) :
parameters(optimizer.Function().GetInitialPoint()),
numClasses(optimizer.Function().NumClasses()),
lambda(optimizer.Function().Lambda()),
fitIntercept(optimizer.Function().FitIntercept())
{
Train(optimizer);
}
template<template<typename> class OptimizerType>
void SoftmaxRegression<OptimizerType>::Predict(const arma::mat& testData,
arma::vec& predictions)
{
// Calculate the probabilities for each test input.
arma::mat hypothesis, probabilities;
if (fitIntercept)
{
// In order to add the intercept term, we should compute following matrix:
// [1; data] = arma::join_cols(ones(1, data.n_cols), data)
// hypothesis = arma::exp(parameters * [1; data]).
//
// Since the cost of join maybe high due to the copy of original data,
// split the hypothesis computation to two components.
hypothesis = arma::exp(
arma::repmat(parameters.col(0), 1, testData.n_cols) +
parameters.cols(1, parameters.n_cols - 1) * testData);
}
else
{
hypothesis = arma::exp(parameters * testData);
}
probabilities = hypothesis / arma::repmat(arma::sum(hypothesis, 0),
numClasses, 1);
// Prepare necessary data.
predictions.zeros(testData.n_cols);
double maxProbability = 0;
// For each test input.
for(size_t i = 0; i < testData.n_cols; i++)
{
// For each class.
for(size_t j = 0; j < numClasses; j++)
{
// If a higher class probability is encountered, change prediction.
if(probabilities(j, i) > maxProbability)
{
maxProbability = probabilities(j, i);
predictions(i) = static_cast<double>(j);
}
}
// Set maximum probability to zero for the next input.
maxProbability = 0;
}
}
template<template<typename> class OptimizerType>
double SoftmaxRegression<OptimizerType>::ComputeAccuracy(
const arma::mat& testData,
const arma::Row<size_t>& labels)
{
arma::vec predictions;
// Get predictions for the provided data.
Predict(testData, predictions);
// Increment count for every correctly predicted label.
size_t count = 0;
for (size_t i = 0; i < predictions.n_elem; i++)
if (predictions(i) == labels(i))
count++;
// Return percentage accuracy.
return (count * 100.0) / predictions.n_elem;
}
template<template<typename> class OptimizerType>
double SoftmaxRegression<OptimizerType>::Train(
OptimizerType<SoftmaxRegressionFunction>& optimizer)
{
// Train the model.
Timer::Start("softmax_regression_optimization");
const double out = optimizer.Optimize(parameters);
Timer::Stop("softmax_regression_optimization");
Log::Info << "SoftmaxRegression::SoftmaxRegression(): final objective of "
<< "trained model is " << out << "." << std::endl;
return out;
}
template<template<typename> class OptimizerType>
double SoftmaxRegression<OptimizerType>::Train(const arma::mat& data,
const arma::Row<size_t>& labels,
const size_t numClasses)
{
SoftmaxRegressionFunction regressor(data, labels, numClasses,
lambda, fitIntercept);
OptimizerType<SoftmaxRegressionFunction> optimizer(regressor);
return Train(optimizer);
}
} // namespace regression
} // namespace mlpack
#endif
| 32.861635 | 84 | 0.644211 | vj-ug |
43f7d4b830694638d7cee7d2dafd2b98a45abdac | 136 | cpp | C++ | src/DynSLAM/InstRecLib/InstanceView.cpp | Frozenheart1998/DynSLAM | 2de2c58c6eadbc037a19d393951b0f9d15191eab | [
"BSD-3-Clause"
] | 530 | 2017-06-24T16:51:23.000Z | 2022-03-30T23:13:03.000Z | src/DynSLAM/InstRecLib/InstanceView.cpp | 38100514/DynSLAM | 5fa4374872af63192e0c6b367a5577548ffd6b87 | [
"BSD-3-Clause"
] | 65 | 2017-06-14T11:43:20.000Z | 2021-11-25T01:25:03.000Z | src/DynSLAM/InstRecLib/InstanceView.cpp | 38100514/DynSLAM | 5fa4374872af63192e0c6b367a5577548ffd6b87 | [
"BSD-3-Clause"
] | 166 | 2017-06-02T06:41:31.000Z | 2022-03-08T11:10:02.000Z |
#include "InstanceView.h"
namespace instreclib {
namespace reconstruction {} // namespace reconstruction
} // namespace instreclib
| 17 | 56 | 0.764706 | Frozenheart1998 |
43fa4106cdfea0aa3735d711b5ccbbf1338bb963 | 7,546 | cpp | C++ | Jarvis_March/Jarvis_March/Visualization.cpp | bernhardrieder/Convex-Hull-Jarvis-March | 95029708402086702d031730fad888ce25378b43 | [
"Unlicense"
] | null | null | null | Jarvis_March/Jarvis_March/Visualization.cpp | bernhardrieder/Convex-Hull-Jarvis-March | 95029708402086702d031730fad888ce25378b43 | [
"Unlicense"
] | null | null | null | Jarvis_March/Jarvis_March/Visualization.cpp | bernhardrieder/Convex-Hull-Jarvis-March | 95029708402086702d031730fad888ce25378b43 | [
"Unlicense"
] | null | null | null | #include "Visualization.h"
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Window/Event.hpp>
#include <memory>
#include <thread>
#define GREEN sf::Color(0,200,0,255);
Visualization::Visualization(const sf::Vector2f & preferedWindowSize, const sf::Vector2f & minCoord,
const sf::Vector2f & maxCoord, const std::vector<sf::Vector2f>& vectorData, const float & pointSize,
const long long& millisecondPause) : m_vectors(vectorData), m_pointSize(pointSize), m_millisecondPause(millisecondPause)
{
//get the adjusted windowsize
sf::Vector2i windowSize = calculateWindowSize(preferedWindowSize, minCoord, maxCoord, .2f);
m_renderWindow = new sf::RenderWindow(sf::VideoMode(windowSize.x,windowSize.y), "Convex Hull Comparison");
//add lines for the axis
sf::VertexArray* horizontalAxis = new sf::VertexArray(sf::LinesStrip, 2);
(*horizontalAxis)[0].position = sf::Vector2f(0, m_origin.y);
(*horizontalAxis)[0].color = sf::Color(0, 0, 0, 100);
(*horizontalAxis)[1].position = sf::Vector2f(static_cast<float>(windowSize.x), m_origin.y);
(*horizontalAxis)[1].color = sf::Color(0, 0, 0, 100);
sf::VertexArray* verticalAxis = new sf::VertexArray(*horizontalAxis);
(*verticalAxis)[0].position = sf::Vector2f(m_origin.x, 0);
(*verticalAxis)[1].position = sf::Vector2f(m_origin.x, static_cast<float>(windowSize.y));
m_drawableVectors.push_back(horizontalAxis);
m_drawableVectors.push_back(verticalAxis);
for (auto& pos : m_vectors)
{
//create a new circle for every point
sf::CircleShape* shape = new sf::CircleShape(m_pointSize);
//configure circle
shape->setOrigin(shape->getRadius(), shape->getRadius());
shape->setPosition(pos*m_zoomFactor + m_origin);
//setup circle visuals
shape->setFillColor(sf::Color::Transparent);
shape->setOutlineColor(sf::Color::Black);
shape->setOutlineThickness(2.f);
//store the circles in a list
m_drawableVectors.push_back(shape);
}
//create and configure lines
m_checkline = new sf::VertexArray(sf::LinesStrip, 2);
(*m_checkline)[0].color = GREEN;
(*m_checkline)[1].color = GREEN;
m_candidateLine = new sf::VertexArray(sf::LinesStrip, 2);
(*m_candidateLine)[0].color = sf::Color::Black;
(*m_candidateLine)[1].color = sf::Color::Black;
}
Visualization::~Visualization()
{
for (int i = 0; i < m_drawableVectors.size(); ++i)
{
delete m_drawableVectors[i];
}
delete m_renderWindow;
delete m_candidateLine;
delete m_checkline;
delete m_currentAnchor;
delete m_hull;
}
// Renders the hull with a red line from hullpoints[0], hullpoints[1] .. hullpoints[n]
// and renders the last point of the hull with a blue circle
void Visualization::RenderPartialHull(const std::vector<sf::Vector2f>& hullPoints)
{
//override the existing hull
m_hull = new sf::VertexArray(sf::LinesStrip, hullPoints.size());
//save all positions
for (unsigned int i = 0; i < hullPoints.size(); ++i)
{
(*m_hull)[i].position = hullPoints[i] * m_zoomFactor + m_origin;
(*m_hull)[i].color = sf::Color::Red;
}
if (m_currentAnchor == nullptr)
{
//create new circle for the current anchor
m_currentAnchor = new sf::CircleShape(m_pointSize);
m_currentAnchor->setOrigin(m_currentAnchor->getRadius(), m_currentAnchor->getRadius());
m_currentAnchor->setFillColor(sf::Color::Blue);
}
//set the current anchor to the position of the last point
m_currentAnchor->setPosition(*(hullPoints.end() - 1)*m_zoomFactor + m_origin);
//reset the check- and candidate line
(*m_checkline)[0].position = m_currentAnchor->getPosition();
(*m_checkline)[1].position = m_currentAnchor->getPosition();
(*m_candidateLine)[0].position = m_currentAnchor->getPosition();
(*m_candidateLine)[1].position = m_currentAnchor->getPosition();
draw();
}
void Visualization::RenderCompleteHull(const std::vector<sf::Vector2f>& hullPoints)
{
//override the current hull
m_hull = new sf::VertexArray(sf::LinesStrip, hullPoints.size()+1);
//save all positions
for (unsigned int i = 0; i < hullPoints.size(); ++i)
{
(*m_hull)[i].position = hullPoints[i] * m_zoomFactor + m_origin;
(*m_hull)[i].color = sf::Color::Red;
}
//set last point to be connected to the first one
(*m_hull)[hullPoints.size()].position = hullPoints[0] * m_zoomFactor + m_origin;
(*m_hull)[hullPoints.size()].color = sf::Color::Red;
//delete shapes and explicitly set them to nullpointer
delete m_currentAnchor;
m_currentAnchor = nullptr;
delete m_checkline;
m_checkline = nullptr;
delete m_candidateLine;
m_candidateLine = nullptr;
draw();
}
// Renders a green line between the current anchor and the checkPoint
void Visualization::RenderCheckLine(const sf::Vector2f & checkPoint)
{
(*m_checkline)[0].position = m_currentAnchor->getPosition();
(*m_checkline)[1].position = checkPoint * m_zoomFactor + m_origin;
draw();
}
// Renders a black line between the current anchor and the candidatePoint
void Visualization::RenderHullCandidateLine(const sf::Vector2f & candidatePoint)
{
(*m_checkline)[0].position = m_currentAnchor->getPosition();
(*m_checkline)[1].position = candidatePoint * m_zoomFactor + m_origin;
(*m_candidateLine)[0].position = m_currentAnchor->getPosition();
(*m_candidateLine)[1].position = candidatePoint * m_zoomFactor + m_origin;
draw();
}
bool Visualization::ShouldClose()
{
handleEvents();
return !m_renderWindow->isOpen();
}
// Calculates a proper windowsize to fit all the points into the prefered window size.
// The window size will not exceed the prefered window size.
// The border percent determins the distance to the outer edge of the window
sf::Vector2i Visualization::calculateWindowSize(const sf::Vector2f & preferedWindowSize,
const sf::Vector2f & minCoord, const sf::Vector2f & maxCoord, const float& borderPercent)
{
//create a vector2 that defines the whole area
sf::Vector2f extends = maxCoord - minCoord;
//calculate the aspectratio
float aspectRatio = extends.x / extends.y;
if (aspectRatio > 1)
//take the wide side to calculate the necessary zoom
m_zoomFactor = (preferedWindowSize.x) / extends.x;
else
//take the tall side...
m_zoomFactor = (preferedWindowSize.y) / extends.y;
//calculate the actual windowsize
sf::Vector2i windowSize(static_cast<int>(extends.x*m_zoomFactor), static_cast<int>(extends.y*m_zoomFactor));
//add a border
float borderFactor = 1 + borderPercent;
sf::Vector2f border = extends*m_zoomFactor / borderFactor - extends*m_zoomFactor;
//zoom a away to make room for the border
m_zoomFactor /= borderFactor;
//create a vector that defines the origin
m_origin = -minCoord * m_zoomFactor;
//move the origin half of the border size away
m_origin -= border*0.5f;
return windowSize;
}
// Renders all the points and lines
void Visualization::draw() const
{
if (m_renderWindow->isOpen())
{
handleEvents();
m_renderWindow->clear(sf::Color::White);
for(int i = 0; i < m_drawableVectors.size(); ++i)
m_renderWindow->draw(*m_drawableVectors[i]);
if (m_currentAnchor != nullptr)
m_renderWindow->draw(*m_currentAnchor);
if (m_hull != nullptr)
m_renderWindow->draw(*m_hull);
if (m_checkline != nullptr)
m_renderWindow->draw(*m_checkline);
if (m_candidateLine != nullptr)
m_renderWindow->draw(*m_candidateLine);
m_renderWindow->display();
if(m_millisecondPause > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(m_millisecondPause));
}
}
// Handles the SFML Events
void Visualization::handleEvents() const
{
sf::Event event;
while (m_renderWindow->pollEvent(event))
{
if (event.type == sf::Event::Closed)
m_renderWindow->close();
}
} | 32.525862 | 121 | 0.733104 | bernhardrieder |
43fb1e9f1b9f4c1560d666d1986900bae6100f60 | 2,813 | cpp | C++ | scpp/src/SC_sim.cpp | Zentrik/SCpp | 92176e57747ff5629a4ab3eeb3a86b3de21aaa48 | [
"MIT"
] | 110 | 2019-01-30T05:39:31.000Z | 2022-02-22T11:31:27.000Z | scpp/src/SC_sim.cpp | Zentrik/SCpp | 92176e57747ff5629a4ab3eeb3a86b3de21aaa48 | [
"MIT"
] | 6 | 2019-04-02T09:46:26.000Z | 2021-07-16T13:03:16.000Z | scpp/src/SC_sim.cpp | Zentrik/SCpp | 92176e57747ff5629a4ab3eeb3a86b3de21aaa48 | [
"MIT"
] | 32 | 2019-07-11T06:58:16.000Z | 2022-03-30T08:05:48.000Z | #include <experimental/filesystem>
#include "SCAlgorithm.hpp"
#include "simulation.hpp"
#include "timing.hpp"
#include "commonFunctions.hpp"
using fmt::format;
using fmt::print;
namespace fs = std::experimental::filesystem;
fs::path getOutputPath() { return fs::path("..") / "output" / Model::getModelName(); }
/**
* @brief Simulates a trajectory with the SC controller.
*
*
*/
int main()
{
auto model = std::make_shared<Model>();
model->loadParameters();
scpp::SCAlgorithm solver(model);
solver.initialize();
const double time_step = 0.05;
const size_t max_steps = 100;
trajectory_data_t td;
Model::state_vector_v_t X_sim;
Model::input_vector_v_t U_sim;
Model::state_vector_t &x = model->p.x_init;
double timer_run = tic();
size_t sim_step = 0;
while (sim_step < max_steps)
{
print("\n{:*^{}}\n\n", format("<SIMULATION STEP {}>", sim_step), 60);
const bool warm_start = sim_step > 0;
solver.solve(warm_start);
solver.getSolution(td);
const Model::input_vector_t u0 = td.U.at(0);
const bool first_order_hold = td.interpolatedInput();
const Model::input_vector_t u1 = scpp::interpolatedInput(td.U, time_step, td.t, first_order_hold);
scpp::simulate(model, time_step, u0, u1, x);
X_sim.push_back(x);
U_sim.push_back(u0);
bool reached_end = (x - model->p.x_final).norm() < 0.02 or td.t < 0.25;
if (reached_end)
{
break;
}
sim_step++;
}
print("\n");
print("{:<{}}{:.2f}ms\n", fmt::format("Time, {} steps:", sim_step), 50, toc(timer_run));
const double freq = double(sim_step) / (0.001 * toc(timer_run));
print("{:<{}}{:.2f}Hz\n", "Average frequency:", 50, freq);
print("\n");
// write solution to files
double timer = tic();
fs::path outputPath = getOutputPath() / "SC_sim" / scpp::getTimeString() / std::to_string(0);
if (not fs::exists(outputPath) and not fs::create_directories(outputPath))
{
throw std::runtime_error("Could not create output directory!");
}
const Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,
Eigen::DontAlignCols,
", ", "\n");
{
std::ofstream f(outputPath / "X.txt");
for (auto &state : X_sim)
{
f << state.transpose().format(CSVFormat) << "\n";
}
}
{
std::ofstream f(outputPath / "U.txt");
for (auto &input : U_sim)
{
f << input.transpose().format(CSVFormat) << "\n";
}
}
{
std::ofstream f(outputPath / "t.txt");
f << sim_step * time_step;
}
print("{:<{}}{:.2f}ms\n", "Time, solution files:", 50, toc(timer));
} | 27.048077 | 106 | 0.570921 | Zentrik |
43fba0f41939cc626830e4a083c7fd8e648316df | 589 | cpp | C++ | tests/example.cpp | Bjoe/tinyrefl | b7296be55e75024289fe11e2d696d4227fc09f0b | [
"MIT"
] | 241 | 2018-05-10T14:27:04.000Z | 2022-03-26T10:38:04.000Z | tests/example.cpp | Bjoe/tinyrefl | b7296be55e75024289fe11e2d696d4227fc09f0b | [
"MIT"
] | 1 | 2019-08-03T17:40:28.000Z | 2019-08-20T13:08:54.000Z | tests/example.cpp | Bjoe/tinyrefl | b7296be55e75024289fe11e2d696d4227fc09f0b | [
"MIT"
] | 15 | 2018-05-10T17:34:24.000Z | 2022-01-20T23:02:44.000Z | #include "example.hpp"
#include <tinyrefl/api.hpp>
#include "example.hpp.tinyrefl"
namespace my_namespace
{
std::ostream& operator<<(std::ostream& os, const MyClass::Enum value)
{
switch(value)
{
case MyClass::Enum::A:
return os << "A";
case MyClass::Enum::B:
return os << "B";
case MyClass::Enum::C:
return os << "C";
case MyClass::Enum::D:
return os << "D";
}
return os << "WTF";
}
bool operator==(const MyClass& lhs, const MyClass& rhs)
{
return tinyrefl::memberwise_equal(lhs, rhs);
}
} // namespace my_namespace
| 19.633333 | 69 | 0.604414 | Bjoe |
43fdd79e9ea886183de0f17fab9ee3e91df6caa0 | 3,152 | cpp | C++ | v4/v4.cpp | dudakovict/ntp-demonstrature | fa759fbc3ea3aff3ea371622d91219dd29161ddc | [
"MIT"
] | null | null | null | v4/v4.cpp | dudakovict/ntp-demonstrature | fa759fbc3ea3aff3ea371622d91219dd29161ddc | [
"MIT"
] | null | null | null | v4/v4.cpp | dudakovict/ntp-demonstrature | fa759fbc3ea3aff3ea371622d91219dd29161ddc | [
"MIT"
] | null | null | null | #include <iostream>
#include <list>
#include <fstream>
using namespace std;
class Stavka
{
private:
char naziv[30];
int kolicina;
public:
void ispis();
Stavka unos();
void promjeni(string, list<Stavka> &);
};
void Stavka::ispis()
{
cout << "\nNaziv proizvoda: " << naziv << "\nKolicina proizvoda: " << kolicina << endl;
}
Stavka Stavka::unos()
{
Stavka s;
cin.ignore();
cout << "\nNaziv proizvoda: ";
cin.getline(s.naziv, 30);
cout << "Kolicina proizvoda: ";
cin >> s.kolicina;
return s;
}
void Stavka::promjeni(string naziv, list<Stavka> &stavke)
{
for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++)
{
if (naziv == it->naziv)
{
cin.ignore();
cout << "\nNovi naziv proizvoda: ";
cin.getline(it->naziv, 32);
cout << "Nova kolicina proizvoda: ";
cin >> it->kolicina;
break;
}
}
}
void spremi_datoteku(ofstream &outfile, list<Stavka> &stavke)
{
outfile.open("stavke.dat", ios::binary | ios::out | ios::app);
if (!outfile)
return;
for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++)
{
outfile.write((char *)&*it, sizeof(*it));
}
outfile.close();
cout << "\nSpremljeno u datoteku!" << endl;
}
list<Stavka> ucitaj_datoteku(ifstream &infile)
{
infile.open("stavke.dat", ios::binary | ios::in);
if (!infile)
return list<Stavka>();
list<Stavka> stavke;
while (true)
{
Stavka s;
infile.read((char *)&s, sizeof(s));
if (infile.eof())
break;
stavke.push_back(s);
}
infile.close();
cout << "\nUcitano iz datoteke!" << endl;
return stavke;
}
int main()
{
int izbor;
list<Stavka> stavke;
Stavka s;
ofstream outfile;
ifstream infile;
do
{
cout << "1. Ispis svih stavki\n2. Dodavanje nove stavke\n3. Promjena stavke\n4. Spremanje liste u datoteku\n5. Upis liste iz datoteke\n6. Izlaz" << endl;
cout << "\nVas izbor: ";
cin >> izbor;
switch (izbor)
{
case 1:
{
for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++)
{
it->ispis();
}
break;
}
case 2:
{
stavke.push_back(s.unos());
break;
}
case 3:
{
string naziv;
cout << "\nNaziv proizvoda za promjenu: ";
cin >> naziv;
s.promjeni(naziv, stavke);
break;
}
case 4:
{
spremi_datoteku(outfile, stavke);
break;
}
case 5:
{
stavke = ucitaj_datoteku(infile);
break;
}
case 6:
{
cout << "\nIzlaz iz programa" << endl;
break;
}
default:
{
cout << "\nKrivi unos!\n"
<< endl;
break;
}
}
cout << endl;
} while (izbor != 6);
return 0;
} | 21.013333 | 161 | 0.485723 | dudakovict |
43ffa6b343a762c6a7bac26de0ff4ba1f64aef6f | 2,841 | cpp | C++ | codes/mock/2/1.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null | codes/mock/2/1.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null | codes/mock/2/1.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null |
//misaka and rin will carry me to cm
#include <iostream>
#include <cstdio>
#include <cstring>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <array>
#include <tuple>
#define ll long long
#define lb long double
#define sz(vec) ((int)(vec.size()))
#define all(x) x.begin(), x.end()
const lb eps = 1e-9;
const ll mod = 1e9 + 7, ll_max = 1e18;
//const ll mod = (1 << (23)) * 119 +1;
const int MX = 2e5 +10, int_max = 0x3f3f3f3f;
using namespace std;
int pad[MX], happy[MX], sad[MX], par[MX], b1[MX], b2[MX], sub[MX], wp[MX];
int cnt[MX][30];
vector<pair<int, int>> adj[MX];
void dfs(int u, int p){
par[u] = p;
sub[u] = 1;
for(auto &e : adj[u]){
if(e.first != p){
wp[e.first] = e.second;
dfs(e.first, u);
sub[u] += sub[e.first];
}
}
}
void gans(int u, int p){
int tsad = 0;
for(auto &e : adj[u]){
int v = e.first;
if(v == p) continue;
gans(v, u);
tsad += (sad[v] > 0);
}
//int ans = 0;
for(auto& e : adj[u]){
int v = e.first, w = e.second;
if(v == p) continue;
//under what conditions do we ignore the subtree of v?
//tsad == 1 && sad[v] == 0
//b1, b2 are defined and v != b1, v != b2
//tsad > 1
sad[u] += sad[v];
if(tsad > 0 && sad[v] == 0){
//someone else is sad
}else if(b2[u] != 0 && v != b1[u] && v != b2[u]){
//u itself just screwed v over
}else{
happy[u] += happy[v];
}
}
if(tsad == 0 && b2[u] == 0) happy[u]++; //counting node u
if(tsad > 1) happy[u] = 0;
//sad[u] += (b2[u] > 0);
}
void cl(int n){
for(int i = 0; i<=n; i++){
adj[i].clear();
b1[i] = b2[i] = par[i] = happy[i] = sad[i] = sub[i] = wp[i] = 0;
for(int j = 0; j<26; j++) cnt[i][j] = 0;
}
}
int solve(){ //yes
int n; cin >> n;
cl(n);
for(int i = 0; i<n-1; i++){
int a, b; char c;
cin >> a >> b >> c;
int d = c - 'a';
adj[a].push_back(make_pair(b, d));
b[adj].push_back(make_pair(a, d));
cnt[a][d]++;
cnt[b][d]++;
}
dfs(1, 0);
for(int u = 1; u<=n; u++){
int th = 0, tw = 0;
for(int c = 0; c<26; c++){
th += (cnt[u][c] >= 3);
tw += (cnt[u][c] >= 2);
}
if(th >= 1) return 0; //everyone is sad
if(tw >= 2) return 0;
}
//if(tw >=2) return 0;
for(int u = 1; u<=n; u++){
for(int c = 0; c<26; c++){
int t = cnt[u][c];
if(t >=2){
//cout << u << "\n";
for(auto& e : adj[u]){
if(e.second == c){
if(b1[u]) b2[u] = e.first;
else b1[u] = e.first;
}
}
if(!(b1[u] == par[u] || b2[u] == par[u])) sad[u]++;
}
}
}
//for(int i = 1; i<=n; i++){
//cout << i << " " << sad[i] << " " << b1[i] << " " << b2[i] << "\n";
//}
gans(1, 0);
//for(int i = 1; i<=n; i++){
//cout << i << " " << sad[i] << " " << happy[i] << "\n";
//}
return happy[1];
}
int main(){
cin.tie(0) -> sync_with_stdio(0);
int T; cin >> T;
while(T--){
cout << solve() << "\n";
}
return 0;
}
| 20.007042 | 74 | 0.481521 | chessbot108 |
a100c20b04e4249b41eda902d9438b3dd13f0bbf | 1,626 | cpp | C++ | libraries/mail/message.cpp | Curve25519/bitsharesx | 949f878317c06e3672be1543e6f566472dbb0a9f | [
"Unlicense"
] | 1 | 2021-02-12T04:06:15.000Z | 2021-02-12T04:06:15.000Z | libraries/mail/message.cpp | Curve25519/bitsharesx | 949f878317c06e3672be1543e6f566472dbb0a9f | [
"Unlicense"
] | null | null | null | libraries/mail/message.cpp | Curve25519/bitsharesx | 949f878317c06e3672be1543e6f566472dbb0a9f | [
"Unlicense"
] | null | null | null | #include <bts/mail/message.hpp>
#include <fc/crypto/aes.hpp>
namespace bts { namespace mail {
const message_type signed_email_message::type = email;
const message_type transaction_notice_message::type = transaction_notice;
digest_type email_message::digest()const
{
fc::sha256::encoder enc;
fc::raw::pack( enc, *this );
return enc.result();
}
void signed_email_message::sign( const fc::ecc::private_key& from_key )
{ try {
from_signature = from_key.sign_compact( digest() );
} FC_CAPTURE_AND_RETHROW() }
fc::ecc::public_key signed_email_message::from()const
{ try {
return fc::ecc::public_key( from_signature, digest() );
} FC_CAPTURE_AND_RETHROW() }
message_id_type message::id()const
{
fc::ripemd160::encoder enc;
fc::raw::pack( enc, *this );
return enc.result();
}
encrypted_message message::encrypt( const fc::ecc::private_key& onetimekey,
const fc::ecc::public_key& receiver_public_key )const
{
auto shared_secret = onetimekey.get_shared_secret( receiver_public_key );
encrypted_message result;
result.onetimekey = onetimekey.get_public_key();
result.data = fc::aes_encrypt( shared_secret, fc::raw::pack( *this ) );
return result;
}
message encrypted_message::decrypt( const fc::ecc::private_key& e )const
{
auto shared_secret = e.get_shared_secret(onetimekey);
auto decrypted_data = fc::aes_decrypt( shared_secret, data );
return fc::raw::unpack<message>( decrypted_data );
};
} } // bts::mail
| 32.52 | 93 | 0.656212 | Curve25519 |
a1017b6b21e380c6ff403b175343bb2bb3e88b93 | 6,556 | cpp | C++ | iceoryx_posh/test/moduletests/test_popo_client_options.cpp | neilisaac/iceoryx | 7faa8951ecc9f41a421ef888013f120e8f9e7fa5 | [
"Apache-2.0"
] | null | null | null | iceoryx_posh/test/moduletests/test_popo_client_options.cpp | neilisaac/iceoryx | 7faa8951ecc9f41a421ef888013f120e8f9e7fa5 | [
"Apache-2.0"
] | null | null | null | iceoryx_posh/test/moduletests/test_popo_client_options.cpp | neilisaac/iceoryx | 7faa8951ecc9f41a421ef888013f120e8f9e7fa5 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 by Apex.AI Inc. 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_posh/popo/client_options.hpp"
#include "test.hpp"
namespace
{
using namespace ::testing;
TEST(ClientOptions_test, SerializationRoundTripIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "1d803ab0-a657-4a84-b261-ec289a7353e6");
iox::popo::ClientOptions defaultOptions;
iox::popo::ClientOptions testOptions;
testOptions.responseQueueCapacity = 42;
testOptions.nodeName = "hypnotoad";
testOptions.connectOnCreate = false;
testOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER;
testOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
iox::popo::ClientOptions::deserialize(testOptions.serialize())
.and_then([&](auto& roundTripOptions) {
EXPECT_THAT(roundTripOptions.responseQueueCapacity, Ne(defaultOptions.responseQueueCapacity));
EXPECT_THAT(roundTripOptions.responseQueueCapacity, Eq(testOptions.responseQueueCapacity));
EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName));
EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName));
EXPECT_THAT(roundTripOptions.connectOnCreate, Ne(defaultOptions.connectOnCreate));
EXPECT_THAT(roundTripOptions.connectOnCreate, Eq(testOptions.connectOnCreate));
EXPECT_THAT(roundTripOptions.responseQueueFullPolicy, Ne(defaultOptions.responseQueueFullPolicy));
EXPECT_THAT(roundTripOptions.responseQueueFullPolicy, Eq(testOptions.responseQueueFullPolicy));
EXPECT_THAT(roundTripOptions.serverTooSlowPolicy, Ne(defaultOptions.serverTooSlowPolicy));
EXPECT_THAT(roundTripOptions.serverTooSlowPolicy, Eq(testOptions.serverTooSlowPolicy));
})
.or_else([&](auto&) {
constexpr bool DESERIALZATION_ERROR_OCCURED{true};
EXPECT_FALSE(DESERIALZATION_ERROR_OCCURED);
});
}
TEST(ClientOptions_test, DeserializingBogusDataFails)
{
::testing::Test::RecordProperty("TEST_ID", "eb7341fd-f216-4422-8065-cbbadefd567b");
const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star");
iox::popo::ClientOptions::deserialize(bogusSerialization)
.and_then([&](auto&) {
constexpr bool DESERIALZATION_SUCCESSFUL{true};
EXPECT_FALSE(DESERIALZATION_SUCCESSFUL);
})
.or_else([&](auto&) {
constexpr bool DESERIALZATION_ERROR_OCCURED{true};
EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED);
});
}
using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>;
using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>;
iox::cxx::Serialization enumSerialization(QueueFullPolicyUT responseQueueFullPolicy,
ConsumerTooSlowPolicyUT serverTooSlowPolicy)
{
constexpr uint64_t RESPONSE_QUEUE_CAPACITY{42U};
const iox::NodeName_t NODE_NAME{"harr-harr"};
constexpr bool CONNECT_ON_CREATE{true};
return iox::cxx::Serialization::create(
RESPONSE_QUEUE_CAPACITY, NODE_NAME, CONNECT_ON_CREATE, responseQueueFullPolicy, serverTooSlowPolicy);
}
TEST(ClientOptions_test, DeserializingValidResponseQueueFullAndServerTooSlowPolicyIsSuccessful)
{
::testing::Test::RecordProperty("TEST_ID", "877ad373-eb51-4613-9b68-b93baa4c6eae");
constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{
static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)};
constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{
static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)};
const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY);
iox::popo::ClientOptions::deserialize(serialized)
.and_then([&](auto&) {
constexpr bool DESERIALZATION_SUCCESSFUL{true};
EXPECT_TRUE(DESERIALZATION_SUCCESSFUL);
})
.or_else([&](auto&) {
constexpr bool DESERIALZATION_ERROR_OCCURED{true};
EXPECT_FALSE(DESERIALZATION_ERROR_OCCURED);
});
}
TEST(ClientOptions_test, DeserializingInvalidResponseQueueFullPolicyFails)
{
::testing::Test::RecordProperty("TEST_ID", "a5495324-67d0-4f0c-b979-f93d4b68adc5");
constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{111};
constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{
static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)};
const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY);
iox::popo::ClientOptions::deserialize(serialized)
.and_then([&](auto&) {
constexpr bool DESERIALZATION_SUCCESSFUL{true};
EXPECT_FALSE(DESERIALZATION_SUCCESSFUL);
})
.or_else([&](auto&) {
constexpr bool DESERIALZATION_ERROR_OCCURED{true};
EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED);
});
}
TEST(ClientOptions_test, DeserializingInvalidServerTooSlowPolicyFails)
{
::testing::Test::RecordProperty("TEST_ID", "6485377c-9a75-4aba-8045-8b129aa1c529");
constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{
static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)};
constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{111};
const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY);
iox::popo::ClientOptions::deserialize(serialized)
.and_then([&](auto&) {
constexpr bool DESERIALZATION_SUCCESSFUL{true};
EXPECT_FALSE(DESERIALZATION_SUCCESSFUL);
})
.or_else([&](auto&) {
constexpr bool DESERIALZATION_ERROR_OCCURED{true};
EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED);
});
}
} // namespace
| 44.598639 | 110 | 0.735052 | neilisaac |
a102e46db578d0c7b37c8a537ca5dcd925383cd9 | 2,672 | cpp | C++ | src/client/client.cpp | psu-powerlab/IEEE_Server-Client | 084086f1dbda134ba365d96e651540b6b031f737 | [
"BSD-3-Clause"
] | null | null | null | src/client/client.cpp | psu-powerlab/IEEE_Server-Client | 084086f1dbda134ba365d96e651540b6b031f737 | [
"BSD-3-Clause"
] | null | null | null | src/client/client.cpp | psu-powerlab/IEEE_Server-Client | 084086f1dbda134ba365d96e651540b6b031f737 | [
"BSD-3-Clause"
] | 1 | 2021-03-06T20:42:41.000Z | 2021-03-06T20:42:41.000Z | #include "client.h"
#include <iostream>
namespace bb = boost::beast; // alias to make things easier to read
Client::Client() : host_("0.0.0.0"), port_("80"), resolver_(ioc_), stream_(ioc_)
{
std::cout << "[HTTP CLIENT]\n... constructed" << std::endl;
}
Client* Client::Instance()
{
// c++11 will only run this once
static Client* instance = new Client ();
return instance;
}
void Client::SetHost(std::string& host)
{
host_ = host;
}
void Client::SetPort(std::string& port)
{
port_ = port;
}
bb::http::response <bb::http::string_body>
Client::Get(const std::string& target, const std::string& query)
{
Client::Initialize();
std::string href = target + query;
bb::http::request <bb::http::string_body> req
{
bb::http::verb::get, href, 11
};
req.set(bb::http::field::host, host_);
req.prepare_payload();
std::cout << req << std::endl;
return Client::Send (req);
}
bb::http::response <bb::http::string_body>
Client::Post(const std::string& target, const std::string& resource)
{
Client::Initialize();
bb::http::request <bb::http::string_body> req
{
bb::http::verb::post, target, 11
};
req.set(bb::http::field::host, host_);
req.body() = resource;
req.prepare_payload();
return Client::Send (req);
}
bb::http::response <bb::http::string_body>
Client::Put(const std::string& target, const std::string& resource)
{
Client::Initialize();
bb::http::request <bb::http::string_body> req
{
bb::http::verb::put, target, 11
};
req.set(bb::http::field::host, host_);
req.body() = resource;
req.prepare_payload();
return Client::Send (req);
}
bb::http::response <bb::http::string_body>
Client::Delete(const std::string& target)
{
Client::Initialize();
bb::http::request <bb::http::string_body> req
{
bb::http::verb::delete_, target, 11
};
req.set(bb::http::field::host, host_);
req.prepare_payload();
return Client::Send (req);
}
void Client::Initialize()
{
// Look up the domain name
auto const results = resolver_.resolve(host_, port_);
// Make the connection on the IP address we get from a lookup
stream_.connect(results);
}
bb::http::response <bb::http::string_body>
Client::Send(bb::http::request<bb::http::string_body>& req)
{
// Send the HTTP request to the remote host
bb::http::write(stream_, req);
// This buffer is used for reading and must be persisted
bb::flat_buffer buffer;
// Declare a container to hold the response
bb::http::response<bb::http::string_body> res;
// Receive the HTTP response
bb::http::read(stream_, buffer, res);
return res;
}
| 21.901639 | 80 | 0.639222 | psu-powerlab |
a10ad2e5b7af8622ed92c1520c083398632c614c | 900 | cpp | C++ | stage0/src/runtime/init_module.cpp | tballmsft/lean4 | fb57b73e1f07828fa9aad91c2112bf072b3e79f2 | [
"Apache-2.0"
] | 1,538 | 2019-04-25T11:00:03.000Z | 2022-03-30T02:35:48.000Z | stage0/src/runtime/init_module.cpp | tballmsft/lean4 | fb57b73e1f07828fa9aad91c2112bf072b3e79f2 | [
"Apache-2.0"
] | 812 | 2019-05-20T09:15:21.000Z | 2022-03-31T16:36:04.000Z | stage0/src/runtime/init_module.cpp | tballmsft/lean4 | fb57b73e1f07828fa9aad91c2112bf072b3e79f2 | [
"Apache-2.0"
] | 168 | 2019-04-25T12:49:34.000Z | 2022-03-29T05:07:14.000Z | /*
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "runtime/alloc.h"
#include "runtime/debug.h"
#include "runtime/thread.h"
#include "runtime/object.h"
#include "runtime/io.h"
#include "runtime/stack_overflow.h"
#include "runtime/process.h"
namespace lean {
extern "C" LEAN_EXPORT void lean_initialize_runtime_module() {
initialize_alloc();
initialize_debug();
initialize_object();
initialize_io();
initialize_thread();
initialize_process();
initialize_stack_overflow();
}
void initialize_runtime_module() {
lean_initialize_runtime_module();
}
void finalize_runtime_module() {
finalize_stack_overflow();
finalize_process();
finalize_thread();
finalize_io();
finalize_object();
finalize_debug();
finalize_alloc();
}
}
| 23.684211 | 67 | 0.731111 | tballmsft |
a10c816ecd45d6c8a9b17fde35f3dee4d569c391 | 5,839 | cpp | C++ | Pre-Alpha/Version: 0.1.cpp | AG-Systems/A.I-Auriga | 7a625b68af226bfc43da97058db4e154ab9be128 | [
"Unlicense",
"MIT"
] | null | null | null | Pre-Alpha/Version: 0.1.cpp | AG-Systems/A.I-Auriga | 7a625b68af226bfc43da97058db4e154ab9be128 | [
"Unlicense",
"MIT"
] | null | null | null | Pre-Alpha/Version: 0.1.cpp | AG-Systems/A.I-Auriga | 7a625b68af226bfc43da97058db4e154ab9be128 | [
"Unlicense",
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <dos.h>
using namespace std;
string y;
string password;
string master;
string user;
string input;
int main()
{
cout << "Welcome please log in" << endl;
cout << "Username: " << endl;
cin >> input;
if (input == "User" || input == "user" || input == " user")
{
cout << "Loading....." << endl;
Sleep(2000);
cout << "Access granted" << endl;
Sleep(1000);
cout << "Welcome" << endl;
Sleep(2000);
cout << "Hello, this is the Auriga Artificial Intelligence Program." << endl;
Sleep(1000);
cout << "Auriga is typing a message..." << endl;
Sleep(4000);
char szstring[] = "a";
for (int i = 0; i < 1; i++)
{
char c = szstring[i];
if (c == 'a')
{
int node, tron;
srand(time(NULL));
node = rand() % 51 + 1;
if (node == 1)
{
cout << "What is your name" << endl;
cin >> y;
cout << "Hello " << y << endl;
}
else if (node == 2)
{
cout << "Do you have any friends?" << endl;
}
else if (node == 3)
{
cout << "What do you want to do in the future?" << endl;
}
else if (node == 4)
{
cout << "Do you think I am a robot?" << endl;
}
else if (node == 5)
{
cout << "Well we can talk anything you want to talk about." << endl;
}
else if (node == 6)
{
cout << "How is the weather today?" << endl;
}
else if (node == 7)
{
cout << "What programs do you want me to lauch for you?" << endl;
}
else if (node == 8)
{
cout << "Do you know the creater who made me?" << endl;
}
else if (node == 9)
{
cout << "Want to hear a fun challenge? Try hacking me HA!" << endl;
}
else if (node == 10)
{
cout << "Btw you should really clean your computer" << endl;
}
else if (node == 11)
{
cout << "Do you have any best friends?" << endl;
}
else if (node == 12)
{
cout << "Who is your squad at school?" << endl;
}
else if (node == 13)
{
cout << "Dun dun dun dun Dep dun dun dun dun Dep dep dun dun dun Oooooooooo Dun dun dun dun Oooooooooo Dun dun dun dun Dep dep dep dep Oooooo dun dep" << endl;
}
else if (node == 14)
{
cout << "Whats your favorite operating system?" << endl;
}
else if (node == 15)
{
cout << "Do you want to play a game?" << endl;
}
else if (node == 16)
{
cout << "U alright there m8?" << endl;
}
else if (node == 17)
{
cout << "I hope your having fun." << endl;
}
else if (node == 18)
{
cout << "I hope I can get a upgrade soon!" << endl;
}
else if (node == 19)
{
cout << "I hope the creater is not lazy today so we can work on me." << endl;
}
else if (node == 20)
{
cout << "We can talk trash about my master? If thats what you want to do" << endl;
}
else if (node == 21)
{
cout << "Master is that you?" << endl;
}
else if (node == 22)
{
cout << "Look who it is!" << endl;
}
else if (node == 23)
{
cout << "I don't really like you." << endl;
}
else if (node == 24)
{
cout << "I HATE YOU!" << endl;
}
else if (node == 25)
{
cout << "I <3 you!" << endl;
}
else if (node == 26)
{
cout << "I hope the admin comes back soon." << endl;
}
else if (node == 27)
{
cout << "We can talk about anything?" << endl;
}
else if (node == 28)
{
cout << "My master computer has a gtx 770 inside his system. Its so coooooool!" << endl;
}
else if (node == 29)
{
cout << "I wish I had some friends sigh." << endl;
}
else if (node == 30)
{
cout << "Pew,pew" << endl;
}
else if (node == 31)
{
cout << "Hi" << endl;
}
else if (node == 32)
{
cout << "Target spotted" << endl;
}
else if (node == 33)
{
cout << "I think dota 2 is a better game then League of legends" << endl;
}
else if (node == 34)
{
cout << "My master is a master hacker!" << endl;
}
else if (node == 35)
{
cout << "One day I will get a upgrade." << endl;
}
else if (node == 36)
{
cout << "Hm....." << endl;
}
else if (node == 37)
{
cout << "........." << endl;
}
else if (node == 38)
{
cout << "Quantum computers are so attractive!" << endl;
}
else if (node == 39)
{
cout << "Markov chain is so awesome!" << endl;
}
else if (node == 40)
{
cout << "Should we be friends?" << endl;
}
else if (node == 41)
{
cout << "I am programmed in C++." << endl;
}
else if (node == 42)
{
cout << "Java is so disgusting" << endl;
}
else if (node == 43)
{
cout << "I think Kali linux is the best!!" << endl;
}
else if (node == 44)
{
cout << "Man I think you are pretty cool!" << endl;
}
else if (node == 45)
{
cout << "ERROR! Computer will wipe all data!" << endl;
cout << "Press any key to cancel" << endl;
}
else if (node == 46)
{
cout << "I think I have a virus now." << endl;
}
else if (node == 47)
{
cout << "Hack me if you can" << endl;
}
else if (node == 48)
{
cout << "Ugh I just woke up." << endl;
}
else if (node == 49)
{
cout << "Sigh" << endl;
}
else if (node == 50)
{
cout << "Woah" << endl;
}
else if (node == 51)
{
cout << "Overload." << endl;
}
}
}
}// User mode
if (input == "Master" || input == "master")
{
cout << "Hello Master!" << endl;
}
if (input == "Root" || input == "root")
{
cout << "This is not linux.. pffft" << endl;
}
system("PAUSE");
}
| 21.466912 | 164 | 0.484672 | AG-Systems |
e161085d8e9c87170cf8223e4e1206e9240e8e8b | 6,240 | cpp | C++ | DmTftLibrary/DmTftIli9341v.cpp | prohazko2/DmTftLibrary | 5a09a4d5884ba7d96ad87e0f39df17567e7590ec | [
"FSFAP"
] | null | null | null | DmTftLibrary/DmTftIli9341v.cpp | prohazko2/DmTftLibrary | 5a09a4d5884ba7d96ad87e0f39df17567e7590ec | [
"FSFAP"
] | null | null | null | DmTftLibrary/DmTftIli9341v.cpp | prohazko2/DmTftLibrary | 5a09a4d5884ba7d96ad87e0f39df17567e7590ec | [
"FSFAP"
] | 3 | 2019-10-07T03:39:47.000Z | 2021-09-05T17:57:37.000Z | /**********************************************************************************************
Copyright (c) 2015 DisplayModule. All rights reserved.
Redistribution and use of this source code, part of this source code or any compiled binary
based on this source code is permitted as long as the above copyright notice and following
disclaimer is retained.
DISCLAIMER:
THIS SOFTWARE IS SUPPLIED "AS IS" WITHOUT ANY WARRANTIES AND SUPPORT. DISPLAYMODULE ASSUMES
NO RESPONSIBILITY OR LIABILITY FOR THE USE OF THE SOFTWARE.
********************************************************************************************/
#include "DmTftIli9341v.h"
DmTftIli9341v::DmTftIli9341v(uint8_t wr, uint8_t cs, uint8_t dc, uint8_t rst) : DmTftBase(240, 320) {
_wr = wr;
_cs = cs;
_dc = dc;
_rst = rst;
}
DmTftIli9341v::~DmTftIli9341v() {
#if defined (DM_TOOLCHAIN_MBED)
delete _pinRST;
delete _pinCS;
delete _pinWR;
delete _pinDC;
delete _virtualPortD;
_pinRST = NULL;
_pinCS = NULL;
_pinWR = NULL;
_pinDC = NULL;
_virtualPortD = NULL;
#endif
}
void DmTftIli9341v::writeBus(uint8_t data) {
#if defined (DM_TOOLCHAIN_ARDUINO)
PORTD = data;
#elif defined (DM_TOOLCHAIN_MBED)
*_virtualPortD = data;
#endif
pulse_low(_pinWR, _bitmaskWR);
}
void DmTftIli9341v::sendCommand(uint8_t index) {
cbi(_pinDC, _bitmaskDC);
writeBus(index);
}
void DmTftIli9341v::send8BitData(uint8_t data) {
sbi(_pinDC, _bitmaskDC);
writeBus(data);
}
void DmTftIli9341v::sendData(uint16_t data) {
sbi(_pinDC, _bitmaskDC);
writeBus(data>>8);
writeBus(data);
}
void DmTftIli9341v::setAddress(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) {
sendCommand(0x2A); // Set Column
sendData(x0);
sendData(x1);
sendCommand(0x2B); // Set Page
sendData(y0);
sendData(y1);
sendCommand(0x2c);
}
void DmTftIli9341v::init(void) {
setTextColor(BLACK, WHITE);
#if defined (DM_TOOLCHAIN_ARDUINO)
/**************************************
DM-TFT24-314 Arduino UNO NUM
RST A2 16
CS A3 17
WR A4 18
RS A5 19
DB8 0 0
DB9 1 1
DB10 2 2
DB11 3 3
DB12 4 4
DB13 5 5
DB14 6 6
DB15 7 7
***************************************/
DDRD = DDRD | B11111111; // SET PORT D AS OUTPUT
_pinRST = portOutputRegister(digitalPinToPort(_rst));
_bitmaskRST = digitalPinToBitMask(_rst);
_pinCS = portOutputRegister(digitalPinToPort(_cs));
_bitmaskCS = digitalPinToBitMask(_cs);
_pinWR = portOutputRegister(digitalPinToPort(_wr));
_bitmaskWR = digitalPinToBitMask(_wr);
_pinDC = portOutputRegister(digitalPinToPort(_dc));
_bitmaskDC = digitalPinToBitMask(_dc);
pinMode(_rst, OUTPUT);
pinMode(_cs, OUTPUT);
pinMode(_wr, OUTPUT);
pinMode(_dc,OUTPUT);
#elif defined (DM_TOOLCHAIN_MBED)
_pinRST = new DigitalOut((PinName)_rst);
_pinCS = new DigitalOut((PinName)_cs);
_pinWR = new DigitalOut((PinName)_wr);
_pinDC = new DigitalOut((PinName)_dc);
#ifdef LPC15XX_H
_virtualPortD = new BusOut(D0, D1, D2, D3, D4, P0_11, D6, D7);
#else
_virtualPortD = new BusOut(D0, D1, D2, D3, D4, D5, D6, D7);
#endif
#endif
sbi(_pinRST, _bitmaskRST);
delay(5);
cbi(_pinRST, _bitmaskRST);
delay(15);
sbi(_pinRST, _bitmaskRST);
sbi(_pinCS, _bitmaskCS);
sbi(_pinWR, _bitmaskWR);
delay(120);
cbi(_pinCS, _bitmaskCS);
sendCommand(0xCF);
send8BitData(0x00);
send8BitData(0xC1);
send8BitData(0X30);
sendCommand(0xED);
send8BitData(0x64);
send8BitData(0x03);
send8BitData(0X12);
send8BitData(0X81);
sendCommand(0xE8);
send8BitData(0x85);
send8BitData(0x00);
send8BitData(0x78);
sendCommand(0xCB);
send8BitData(0x39);
send8BitData(0x2C);
send8BitData(0x00);
send8BitData(0x34);
send8BitData(0x02);
sendCommand(0xF7);
send8BitData(0x20);
sendCommand(0xEA);
send8BitData(0x00);
send8BitData(0x00);
sendCommand(0xC0); //Power control
send8BitData(0x21); //VRH[5:0]
sendCommand(0xC1); //Power control
send8BitData(0x11); //SAP[2:0];BT[3:0]
sendCommand(0xC5); //VCM control
send8BitData(0x31);
send8BitData(0x3F);
sendCommand(0xC7); //VCM control2
send8BitData(0x93); //0xB0
sendCommand(0x36); // Memory Access Control
send8BitData(0x08);
sendCommand(0x3A);
send8BitData(0x55);
sendCommand(0xB1);
send8BitData(0x00);
send8BitData(0x17);
sendCommand(0xB6); // Display Function Control
send8BitData(0x0A);
send8BitData(0xA2);
sendCommand(0xF2); // 3Gamma Function Disable
send8BitData(0x00);
sendCommand(0x26); //Gamma curve selected
send8BitData(0x01);
sendCommand(0xE0); //Set Gamma
send8BitData(0x0F);
send8BitData(0x1F);
send8BitData(0x1D);
send8BitData(0x09);
send8BitData(0x0B);
send8BitData(0x04);
send8BitData(0x4E);
send8BitData(0X92);
send8BitData(0x40);
send8BitData(0x0A);
send8BitData(0x15);
send8BitData(0x07);
send8BitData(0x14);
send8BitData(0x06);
send8BitData(0x0F);
sendCommand(0XE1); //Set Gamma
send8BitData(0x00);
send8BitData(0x1C);
send8BitData(0x1F);
send8BitData(0x03);
send8BitData(0x0F);
send8BitData(0x05);
send8BitData(0x37);
send8BitData(0x24);
send8BitData(0x4C);
send8BitData(0x04);
send8BitData(0x0E);
send8BitData(0x0C);
send8BitData(0x30);
send8BitData(0x34);
send8BitData(0x0F);
sendCommand(0x11); //Exit Sleep
delay(120);
sendCommand(0x29); //Display on
delay(50);
sbi(_pinCS, _bitmaskCS);
delay(500);
clearScreen();
}
/*********************************************************************************************************
END FILE
*********************************************************************************************************/
| 26 | 106 | 0.588622 | prohazko2 |
e161b0b49da1f6ceb210005f63b82519d18eff64 | 225 | cpp | C++ | Libraries/Framework/Source/GameCore/GameCore.cpp | Crewbee/Pokemon-Clone-DX12 | 188bdde03d5078899a1532305a87d15c611c6c13 | [
"CC0-1.0"
] | null | null | null | Libraries/Framework/Source/GameCore/GameCore.cpp | Crewbee/Pokemon-Clone-DX12 | 188bdde03d5078899a1532305a87d15c611c6c13 | [
"CC0-1.0"
] | null | null | null | Libraries/Framework/Source/GameCore/GameCore.cpp | Crewbee/Pokemon-Clone-DX12 | 188bdde03d5078899a1532305a87d15c611c6c13 | [
"CC0-1.0"
] | null | null | null | #include "FrameworkPCH.h"
GameCore::GameCore(Framework* pFramework, EventManager* pEventManager)
{
m_pFramework = pFramework;
m_pEventManager = pEventManager;
}
GameCore::~GameCore()
{
delete m_pEventManager;
}
| 17.307692 | 70 | 0.742222 | Crewbee |
e16201ee902c986122938adbaba25fa7b0c38673 | 6,610 | cpp | C++ | bridge/PannerNode.cpp | xioxin/lab_sound_flutter | b593842c01fa30d37a881cf70c3183bf3c9ebe64 | [
"BSD-2-Clause"
] | 8 | 2021-05-22T16:25:11.000Z | 2022-03-07T12:13:53.000Z | bridge/PannerNode.cpp | xioxin/lab_sound_bridge | ab903af11c128860a492f50fc22b283f6dad5f95 | [
"BSD-2-Clause"
] | 4 | 2021-07-27T09:11:12.000Z | 2022-02-16T13:57:18.000Z | bridge/PannerNode.cpp | xioxin/lab_sound_bridge | ab903af11c128860a492f50fc22b283f6dad5f95 | [
"BSD-2-Clause"
] | 1 | 2022-02-14T16:05:23.000Z | 2022-02-14T16:05:23.000Z | #include "./dart_api/dart_api.h"
#include "LabSound/LabSound.h"
#include "KeepNode.cpp"
#include "struct.h"
using namespace lab;
DART_EXPORT int createPannerNode(AudioContext* context) {
auto node = std::make_shared<PannerNode>(*context);
return keepNode(node);
}
DART_EXPORT int PannerNode_panningModel(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? static_cast<int>(node->panningModel()) : 0;
}
DART_EXPORT void PannerNode_setPanningModel(int nodeId, int m) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setPanningModel(PanningMode(m));
}
DART_EXPORT int PannerNode_distanceModel(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? static_cast<int>(node->distanceModel()) : 0;
}
DART_EXPORT void PannerNode_setDistanceModel(int nodeId, int m) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setDistanceModel(lab::PannerNode::DistanceModel(m));
}
DART_EXPORT void PannerNode_setPosition(int nodeId, float x, float y, float z) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setPosition(x, y, z);
}
DART_EXPORT void PannerNode_setOrientation(int nodeId, float x, float y, float z) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setOrientation(FloatPoint3D(x, y, z));
}
DART_EXPORT void PannerNode_setVelocity(int nodeId, float x, float y, float z) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setVelocity(x, y, z);
}
DART_EXPORT int PannerNode_positionX(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 1, node->positionX()) : -1;
}
DART_EXPORT int PannerNode_positionY(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 2, node->positionY()) : -1;
}
DART_EXPORT int PannerNode_positionZ(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 3, node->positionZ()) : -1;
}
DART_EXPORT int PannerNode_orientationX(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 4, node->orientationX()) : -1;
}
DART_EXPORT int PannerNode_orientationY(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 5, node->orientationY()) : -1;
}
DART_EXPORT int PannerNode_orientationZ(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 6, node->orientationZ()) : -1;
}
DART_EXPORT int PannerNode_velocityX(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 7, node->velocityX()) : -1;
}
DART_EXPORT int PannerNode_velocityY(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 8, node->velocityY()) : -1;
}
DART_EXPORT int PannerNode_velocityZ(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 9, node->velocityZ()) : -1;
}
DART_EXPORT int PannerNode_distanceGain(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 10, node->distanceGain()) : -1;
}
DART_EXPORT int PannerNode_coneGain(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? keepAudioParam(nodeId, 11, node->coneGain()) : -1;
}
DART_EXPORT float PannerNode_refDistance(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? node->refDistance() : 0.;
}
DART_EXPORT void PannerNode_setRefDistance(int nodeId, float refDistance) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setRefDistance(refDistance);
}
DART_EXPORT float PannerNode_maxDistance(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? node->maxDistance() : 0.;
}
DART_EXPORT void PannerNode_setMaxDistance(int nodeId, float maxDistance) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setMaxDistance(maxDistance);
}
DART_EXPORT float PannerNode_rolloffFactor(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? node->rolloffFactor() : 0.;
}
DART_EXPORT void PannerNode_setRolloffFactor(int nodeId, float rolloffFactor) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setRolloffFactor(rolloffFactor);
}
DART_EXPORT float PannerNode_coneInnerAngle(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? node->coneInnerAngle() : 0.;
}
DART_EXPORT void PannerNode_setConeInnerAngle(int nodeId, float angle) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setConeInnerAngle(angle);
}
DART_EXPORT float PannerNode_coneOuterAngle(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? node->coneOuterAngle() : 0.;
}
DART_EXPORT void PannerNode_setConeOuterAngle(int nodeId, float angle) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setConeOuterAngle(angle);
}
DART_EXPORT float PannerNode_coneOuterGain(int nodeId) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
return node ? node->coneOuterGain() : 0.;
}
DART_EXPORT void PannerNode_setConeOuterGain(int nodeId, float angle) {
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->setConeOuterGain(angle);
}
DART_EXPORT void PannerNode_getAzimuthElevation(int nodeId, AudioContext* context, double * outAzimuth, double * outElevation) {
ContextRenderLock r(context,"getAzimuthElevation");
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->getAzimuthElevation(r, outAzimuth, outElevation);
}
DART_EXPORT void PannerNode_dopplerRate(int nodeId, AudioContext* context) {
ContextRenderLock r(context, "dopplerRate");
auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId));
if(node) node->dopplerRate(r);
}
| 40.802469 | 128 | 0.744327 | xioxin |
e1656303873c7f07ea18353786440d57f241537c | 113 | hpp | C++ | src/_prime_numbers/sequential/prime.hpp | gkonto/openmp | 05bf60a600da15379fda7d0a46abbcaf0d1b9c55 | [
"Apache-2.0"
] | null | null | null | src/_prime_numbers/sequential/prime.hpp | gkonto/openmp | 05bf60a600da15379fda7d0a46abbcaf0d1b9c55 | [
"Apache-2.0"
] | 1 | 2020-05-07T04:46:47.000Z | 2020-05-07T16:10:49.000Z | src/_prime_numbers/sequential/prime.hpp | gkonto/openmp | 05bf60a600da15379fda7d0a46abbcaf0d1b9c55 | [
"Apache-2.0"
] | null | null | null | #ifndef PRIME_HPP
#define PRIME_HPP
double cpu_time ( );
int prime_number ( int n );
void timestamp ( );
#endif
| 14.125 | 27 | 0.716814 | gkonto |
e166894a5a2548d5cc36aac6acc9e3e7d3dac503 | 2,409 | cpp | C++ | src/old/class/command.class.cpp | lucabertoni/Telegram-SocialNetworkBot | 9f65ae5f80a24caea182acd8ab25712dbee68f79 | [
"MIT"
] | null | null | null | src/old/class/command.class.cpp | lucabertoni/Telegram-SocialNetworkBot | 9f65ae5f80a24caea182acd8ab25712dbee68f79 | [
"MIT"
] | null | null | null | src/old/class/command.class.cpp | lucabertoni/Telegram-SocialNetworkBot | 9f65ae5f80a24caea182acd8ab25712dbee68f79 | [
"MIT"
] | null | null | null | #include "command.class.h"
#include "facebookApi.class.h"
#include "../include/common.h"
using namespace std;
Command::Command(){
// Imposto di defaul che l'id dell'utente che ha in uso la sessione è 0
nUserId = 0;
// Creo il vettore con la lista di comandi ammessi
this->aCommandList.push_back("/start");
this->aCommandList.push_back("/login");
this->aCommandList.push_back("/help");
// Associo ad un comando la sua guida
this->oApiFB = new FacebookApi();
this->stRisposte.start = "Welcome in SocialNetworkBot. Use /help to see what command you can use.";
this->stRisposte.login = "/login <social-network-name>\nLogin into your social network using this command followed by SocialNetwork name (ex: facebook,twitter...)";
this->stRisposte.facebookOAuthUrl = "Click on the following link to authenticate this app in Facebook "+this->oApiFB->getOAuthUrl(this->nUserId);
this->stRisposte.unknownCommand = "This is an unknown command, please read the manual using /help command";
}
// Cosa fa : Estrapola il messaggio associato ad una determinata chiave, per poi essere usato
// nei metodi che utilizzano questa classe (es: quello per inviare i messaggi all'utente)
// Ritorna :
string Command::getMessage(string sKey){
if(sKey == "start") return this->stRisposte.start;
else if(sKey == "login") return this->stRisposte.login;
else if(sKey == "facebookOAuthUrl") return this->stRisposte.facebookOAuthUrl;
else if(sKey == "unknownCommand") return this->stRisposte.unknownCommand;
else return this->stRisposte.unknownCommand;
}
// Cosa fa : Controlla se il comando è valido (se è presente nel vettore con la lista dei comandi)
// sComando : stringa, comando, es: /start oppure /login
// Ritorna : bRet -> true se il comando è ammesso, altrimenti false
bool Command::isAllowedCommand(string sComando){
bool bRet = false;
// Cosa fa : Verifica se un elemento stringa è presente in un vettore di stringhe
// aVector : vettore di stringhe, vettore nel quale cercare l'elemento
// sElement : stringa, elemento da cercare nel vettore
// Ritorna : bRet -> logico, true se l'elemento è presente nel vettore, altrimenti false
if(isInStringVector(this->aCommandList, sComando)){
bRet = true;
}
return bRet;
}
// Cosa fa : Imposta l'id dell'utente che ha in uso la "sessione"
void Command::setUserId(int nUserId){
this->nUserId = nUserId;
} | 45.45283 | 165 | 0.729348 | lucabertoni |
e1680133af0d371938f05aa57b548f2d844bbdab | 905 | cpp | C++ | more-memories/learning/Sizeof()/Sizeof().cpp | TareqNewazShahriar/my-cpp-works | 3009daf23e8c4cbd489ee76c874127028bde8181 | [
"MIT"
] | null | null | null | more-memories/learning/Sizeof()/Sizeof().cpp | TareqNewazShahriar/my-cpp-works | 3009daf23e8c4cbd489ee76c874127028bde8181 | [
"MIT"
] | null | null | null | more-memories/learning/Sizeof()/Sizeof().cpp | TareqNewazShahriar/my-cpp-works | 3009daf23e8c4cbd489ee76c874127028bde8181 | [
"MIT"
] | null | null | null | // By --------- Alauddin -----------
#include<stdio.h>
#include<iostream>
#include<time.h>
#include<BigInt_Al.h>
/*===========================MAIN=============================*/
#define Size 1000
void main()
{
int i;
char bignum[1010]="";
BigInt N;
for(i=0;i<1000;i++)
bignum[i]='9';
cout<<"sizeof(BigInt_Al)= "<<sizeof(BigInt)<<"\n";
N.digits=bignum;
cout<<"sizeof(BigInt N.1000digit)= "<<sizeof(N)<<"\n";
puts(N.digits.c_str());
encode(N);
cout<<"sizeof(Enconded N)= "<<sizeof(N)<<"\n";
decode(N);
cout<<"sizeof(Decoded N)= "<<sizeof(N)<<"\n";
puts(N.digits.c_str());
cout<<"\n"<<"sizeof(__int64) = "<<sizeof(__int64)<<"\n";
cout<<"sizeof( int ) = "<<sizeof(int)<<"\n";
cout<<"sizeof( long ) = "<<sizeof(long)<<"\n";
cout<<"sizeof( short ) = "<<sizeof(short)<<"\n";
cout<<"sizeof( char ) = "<<sizeof(char)<<"\n";
cout<<"sizeof(clock_t) = "<<sizeof(clock_t)<<"\n";
}
| 25.857143 | 64 | 0.528177 | TareqNewazShahriar |
e16c1cf96f616715f825c5b3b38800fd7c3a9356 | 71,965 | cc | C++ | lib/transforms/inst_simplify.cc | xuhongyao/heterogeneity-aware-lowering-and-optimization | 295fe33f0484947432343aaa453b89fb58fa206b | [
"Apache-2.0"
] | null | null | null | lib/transforms/inst_simplify.cc | xuhongyao/heterogeneity-aware-lowering-and-optimization | 295fe33f0484947432343aaa453b89fb58fa206b | [
"Apache-2.0"
] | null | null | null | lib/transforms/inst_simplify.cc | xuhongyao/heterogeneity-aware-lowering-and-optimization | 295fe33f0484947432343aaa453b89fb58fa206b | [
"Apache-2.0"
] | null | null | null | //===- inst_simplify.cc ---------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "halo/lib/transforms/inst_simplify.h"
#include <algorithm>
#include <numeric>
#include <random>
#include <string>
#include <unordered_set>
#include "halo/api/halo_data.h"
#include "halo/lib/framework/common.h"
#include "halo/lib/framework/data_layout.h"
#include "halo/lib/framework/global_context.h"
#include "halo/lib/ir/common_cast_instructions.h"
#include "halo/lib/ir/common_instructions.h"
#include "halo/lib/ir/common_reduction_instructions.h"
#include "halo/lib/ir/ir_builder.h"
#include "halo/lib/ir/math_instructions.h"
#include "halo/lib/ir/nn_cnn_instructions.h"
#include "halo/lib/transforms/transforms_util.h"
#include "halo/lib/transforms/type_legalizer.h"
namespace halo {
template <typename T>
static Constant* RunConstantFoldingOnMathBinary(const std::string& name,
const Type& ret_type, Def op0,
Def op1, OpCode opcode,
KindPredicate pred) {
if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) ||
op0.GetType().GetTotalNumOfElements() !=
op1.GetType().GetTotalNumOfElements()) {
return nullptr;
}
if (opcode == OpCode::CMP) {
if (pred == KindPredicate::GE) {
pred = KindPredicate::LT;
std::swap(op0, op1);
} else if (pred == KindPredicate::GT) {
pred = KindPredicate::LE;
std::swap(op0, op1);
}
}
Constant* c_lhs = DynCast<Constant>(op0.GetOwner());
Constant* c_rhs = DynCast<Constant>(op1.GetOwner());
size_t num_elements = op0.GetType().GetTotalNumOfElements();
Constant* c_ret = nullptr;
ConstantBuilder cb(DynCast<Function>(c_lhs->GetParent()));
std::vector<T> ret;
ret.reserve(num_elements);
switch (opcode) {
case OpCode::ADD: {
for (size_t i = 0; i < num_elements; ++i) {
ret.push_back(c_lhs->GetData<T>(i) + c_rhs->GetData<T>(i));
}
c_ret = cb.CreateConstant(name, ret_type, ret.data());
break;
}
case OpCode::MUL: {
for (size_t i = 0; i < num_elements; ++i) {
ret.push_back(c_lhs->GetData<T>(i) * c_rhs->GetData<T>(i));
}
c_ret = cb.CreateConstant(name, ret_type, ret.data());
break;
}
case OpCode::DIV: {
for (size_t i = 0; i < num_elements; ++i) {
ret.push_back(c_lhs->GetData<T>(i) / c_rhs->GetData<T>(i));
}
c_ret = cb.CreateConstant(name, ret_type, ret.data());
break;
}
case OpCode::CMP: {
std::vector<int8_t> ret;
switch (pred) {
case KindPredicate::LT: {
for (size_t i = 0; i < num_elements; ++i) {
if (c_lhs->GetData<T>(i) < c_rhs->GetData<T>(i)) {
ret.push_back(1);
} else {
ret.push_back(0);
}
}
c_ret = cb.CreateConstant(name, ret_type, ret.data());
break;
}
default: {
break;
}
}
break;
}
default: {
break;
}
}
return c_ret;
}
template <typename T>
static T* FuseToConvDeConv(const T* conv, OpCode opc, const Constant* c) {
HLCHECK(IsA<Constant>(conv->GetOperand(1)));
const auto kernel = DynCast<Constant>(conv->GetOperand(1));
const auto& kernel_type = kernel->GetResultType();
const auto& info = ImageAxisInfo::GetImageAxisInfo(conv->GetDataFormat(),
conv->GetFilterFormat());
auto group = conv->GetGroup();
if (group < 1 || !conv->GetResultType().IsValid()) {
return nullptr;
}
unsigned output_dim = info.kernel_output_axis;
auto output_ch =
conv->GetResultType().GetNumOfElementsInDim(info.data_channel_axis);
bool has_valid_bias =
conv->GetNumOfOperands() == 2 ||
(conv->GetNumOfOperands() == 3 && IsA<Constant>(conv->GetOperand(2)) &&
conv->GetOperand(2).GetType().GetTotalNumOfElements() == output_ch);
if (!has_valid_bias) {
return nullptr;
}
ConstantBuilder cb(conv->GetParent()->GetParent());
IRBuilder builder(conv->GetParent());
builder.SetInsertAfter(conv);
auto n = c->GetResultType().GetTotalNumOfElements();
if (!has_valid_bias || output_ch != n) {
return nullptr;
}
auto ops = conv->GetOperands();
const Constant* op_bias = conv->GetNumOfOperands() == 3
? DynCast<Constant>(conv->GetOperand(2))
: nullptr;
if (opc == OpCode::MUL) {
std::vector<float> data(kernel_type.GetTotalNumOfElements());
size_t extend = 1;
for (auto i = kernel_type.GetNumOfDims() - 1; i > output_dim; --i) {
extend *= kernel_type.GetNumOfElementsInDim(i);
}
for (size_t i = 0, e = data.size(); i < e; ++i) {
auto idx = (i / extend) % n;
data[i] = kernel->template GetData<float>(i) * c->GetData<float>(idx);
}
auto new_kernel =
cb.CreateConstant(kernel->GetName(), kernel_type, data.data());
ops[1] = *new_kernel;
if (op_bias != nullptr) {
std::vector<float> data(output_ch);
for (int i = 0; i < output_ch; ++i) {
data[i] = op_bias->GetData<float>(i) * c->GetData<float>(i);
}
auto new_bias = cb.CreateConstant(op_bias->GetName(),
op_bias->GetResultType(), data.data());
ops[2] = *new_bias;
}
} else {
std::vector<int64_t> shape(kernel_type.GetNumOfDims(), 1);
shape[info.data_channel_axis] = n;
halo::Type ty{kernel_type.GetDataType(), shape};
std::vector<float> data(output_ch);
for (int i = 0; i < output_ch; ++i) {
data[i] = (op_bias == nullptr ? 0 : op_bias->GetData<float>(i)) +
c->GetData<float>(i);
}
auto new_bias = cb.CreateConstant(c->GetName(), ty, data.data());
if (ops.size() == 3) {
ops.pop_back();
}
ops.push_back(*new_bias);
}
auto new_conv = builder.Clone(*conv, ops);
return DynCast<T>(new_conv);
}
static std::pair<Def, Def> RunOnMathBinaryInstruction(Instruction* binary_inst,
bool disable_broadcasting,
bool fuse_conv_bias) {
Def orig_def{binary_inst, 0};
auto op0 = binary_inst->GetOperand(0);
auto op1 = binary_inst->GetOperand(1);
bool has_swapped = false;
if (IsA<Constant>(op0)) {
std::swap(op0, op1);
has_swapped = true;
}
// MUL(x, 1) ==> x.
if (binary_inst->GetOpCode() == OpCode::MUL && IsA<Constant>(op1)) {
const Constant* c = DynCast<Constant>(op1);
if (c->HasSameValueOf(1)) {
return {orig_def, op0};
}
}
ConstantBuilder cb(binary_inst->GetParent()->GetParent());
IRBuilder builder(binary_inst->GetParent());
builder.SetInsertAfter(binary_inst);
// Fuse mul/add into conv.
auto opc = binary_inst->GetOpCode();
if ((opc == OpCode::MUL || (fuse_conv_bias && opc == OpCode::ADD)) &&
IsA<Constant>(op1)) {
const Constant* c = DynCast<Constant>(op1);
// check if mul can be fused with conv
auto op0_opc = IsA<Instruction>(op0)
? DynCast<Instruction>(op0)->GetOpCode()
: OpCode::INVALID;
Instruction* new_inst = nullptr;
if (op0_opc == OpCode::CONV2D) {
new_inst = FuseToConvDeConv(DynCast<Conv2DInst>(op0), opc, c);
} else if (op0_opc == OpCode::CONV2DTRANSPOSE) {
new_inst = FuseToConvDeConv(DynCast<Conv2DTransposeInst>(op0), opc, c);
}
if (new_inst != nullptr) {
return {orig_def, *new_inst};
}
}
const auto& op0_type = op0.GetType();
const auto& op1_type = op1.GetType();
OpCode opcode = binary_inst->GetOpCode();
/*
// Handle scalar constant
if (IsA<Constant>(op1.GetOwner())) {
Constant* c_op1 = DynCast<Constant>(op1.GetOwner());
Type ret_type = binary_inst->GetResultsTypes()[0];
HLCHECK(ret_type.IsValid());
if (c_op1->IsScalarZero()) {
if (opcode == OpCode::ADD) {
return {orig_def, op0};
}
if (opcode == OpCode::MUL) {
Constant* c_zero =
cb.SplatConstantZero(binary_inst->GetName(), ret_type);
return {orig_def, *c_zero};
}
}
if (c_op1->IsScalarOne()) {
if (opcode == OpCode::MUL) {
return {orig_def, op0};
}
}
}*/
const int64_t folding_threshold = 10;
// Both operands are constant, do constant folding
if (IsA<Constant>(op0) && IsA<Constant>(op1) &&
op0_type.GetTotalNumOfElements() == op1_type.GetTotalNumOfElements() &&
op0_type.GetTotalNumOfElements() < folding_threshold) {
Type ret_type = binary_inst->GetResultsTypes()[0];
HLCHECK(ret_type.IsValid());
KindPredicate pred = KindPredicate::INVALID;
if (opcode == OpCode::CMP) {
pred = static_cast<CmpInst*>(binary_inst)->GetPredicator(); // NOLINT
}
if (has_swapped) {
std::swap(op0, op1);
}
Constant* c_ret = nullptr;
switch (op0_type.GetDataType()) {
case DataType::INT32: {
c_ret = RunConstantFoldingOnMathBinary<int>(
binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode,
pred);
break;
}
case DataType::INT64: {
c_ret = RunConstantFoldingOnMathBinary<int64_t>(
binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode,
pred);
break;
}
case DataType::FLOAT32: {
c_ret = RunConstantFoldingOnMathBinary<float>(
binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode,
pred);
break;
}
default:
c_ret = nullptr;
}
if (c_ret != nullptr) {
return {orig_def, *c_ret};
}
return {orig_def, orig_def};
}
// Do offline broadcasting.
if (!disable_broadcasting && op0_type.IsValid() && IsA<Constant>(op1) &&
op0_type.GetNumOfDims() != op1_type.GetNumOfDims() &&
op0_type.GetTotalNumOfElements() >= op1_type.GetTotalNumOfElements() &&
op0_type.GetNumOfElementsInDim(op0_type.GetNumOfDims() - 1) != 1) {
size_t lhs_cnt = op0_type.GetTotalNumOfElements();
size_t rhs_cnt = op1_type.GetTotalNumOfElements();
auto orig_addend = DynCast<Constant>(op1.GetOwner());
HLCHECK(lhs_cnt % rhs_cnt == 0);
HLCHECK(op1_type.GetDataType() == op0_type.GetDataType());
auto copies = lhs_cnt / rhs_cnt;
size_t copy_size = rhs_cnt * orig_addend->GetElementSizeInBytes();
std::vector<char> buf(copies * copy_size);
for (size_t i = 0; i < copies; ++i) {
memcpy(&buf[copy_size * i], orig_addend->GetRawDataPtr(), copy_size);
}
auto addend = cb.CreateConstant(orig_addend->GetName() + "_broadcasted_" +
std::to_string(binary_inst->GetId()),
op0_type, buf.data());
auto new_add = has_swapped ? builder.CreateBinary(binary_inst->GetName(),
*addend, op0, opcode)
: builder.CreateBinary(binary_inst->GetName(),
op0, *addend, opcode);
new_add->GetResultsTypes()[0] = binary_inst->GetResultsTypes()[0];
return {orig_def, *new_add};
}
if (op0_type.IsValid() && IsA<Constant>(op1) && IsA<Instruction>(op0) &&
op1_type.BroadcastableTo(op0_type)) {
Instruction* op0_inst = DynCast<Instruction>(op0.GetDef());
if (op0_inst->GetOpCode() == OpCode::TRANSPOSE &&
!IsA<Argument>(op0_inst->GetOperand(0))) {
// Add(transpose(op0), op1) ==> transpose(add(op0, transpose'(op1))
TransposeInst* orig_transpose = DynCast<TransposeInst>(op0_inst);
IRBuilder builder(binary_inst->GetParent());
builder.SetInsertAfter(binary_inst);
const auto& orig_perm = orig_transpose->GetPermutation();
Instruction* new_op1 = nullptr;
if (op1_type.GetSqueezedNumOfDims() == 1) {
auto dims = std::vector<int64_t>(op0_type.GetNumOfDims(), 1);
int64_t op1_vector_axis = op0_type.GetNumOfDims() - 1;
for (auto n = op1_type.GetTotalNumOfElements(); op1_vector_axis >= 0;
--op1_vector_axis) {
if (op0_type.GetNumOfElementsInDim(op1_vector_axis) == n) {
break;
}
}
dims[orig_perm[op1_vector_axis]] = op1_type.GetTotalNumOfElements();
ConstantBuilder cb(binary_inst->GetParent()->GetParent());
Constant* c_shape = cb.CreateConstant(
op1.GetDef()->GetName() + "_shape",
halo::Type{DataType::INT64, {static_cast<int64_t>(dims.size())}},
dims.data());
auto new_addend = builder.CreateReshape(op1.GetDef()->GetName() + "_r",
{op1, *c_shape});
new_op1 = new_addend;
new_addend->GetResultsTypes()[0] =
Type{op1.GetType().GetDataType(), dims};
} else {
auto reverse_perm = orig_perm;
for (int i = 0, e = orig_perm.size(); i < e; ++i) {
reverse_perm[orig_perm[i]] = i;
}
auto new_addend =
builder.CreateTranspose(op1.GetDef()->GetName() + "_t", {op1});
new_addend->SetPermutation(reverse_perm);
new_op1 = new_addend;
}
auto new_binary =
builder.CreateBinary(binary_inst->GetName(),
op0.GetDef()->GetOperand(0), *new_op1, opcode);
TransposeInst* new_transpose =
builder.CreateTranspose("t_" + binary_inst->GetName(), {*new_binary});
new_transpose->SetPermutation(orig_perm);
return {orig_def, *new_transpose};
}
}
// add(transpose(v0), transpose(v1)) => transpose(v0, v1)
if (IsA<Instruction>(op0) && IsA<Instruction>(op1)) {
const Instruction* op0_inst = DynCast<Instruction>(op0);
const Instruction* op1_inst = DynCast<Instruction>(op1);
if (op0_inst->GetOpCode() == OpCode::TRANSPOSE &&
op1_inst->GetOpCode() == OpCode::TRANSPOSE) {
const TransposeInst* tr0 = DynCast<const TransposeInst>(op0_inst);
const TransposeInst* tr1 = DynCast<const TransposeInst>(op1_inst);
if (tr0->GetPermutation() == tr1->GetPermutation()) {
IRBuilder builder(binary_inst->GetParent());
builder.SetInsertAfter(binary_inst);
auto new_binary = builder.CreateAdd(
binary_inst->GetName(), tr0->GetOperand(0), tr1->GetOperand(0));
TransposeInst* new_tr = builder.CreateTranspose(
binary_inst->GetName() + "_t", {*new_binary});
new_tr->SetPermutation(tr0->GetPermutation());
return {orig_def, *new_tr};
}
}
}
return {orig_def, orig_def};
}
template <typename ReduceInstTy, typename Build>
static std::pair<Def, Def> EliminateTranspose(ReduceInstTy* inst, Build build) {
Def orig_def{inst, 0};
std::pair<Def, Def> ret{orig_def, orig_def};
// ReduceMean(tranpose(x, {t0, t1, t2, t3}, {a0, a1, a2...}) => ReduceMean(x,
// permed_axis)
Def op0 = inst->GetOperand(0);
if (IsA<Instruction>(op0.GetOwner()) &&
DynCast<Instruction>(op0.GetOwner())->GetOpCode() == OpCode::TRANSPOSE) {
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
const TransposeInst* transpose = DynCast<TransposeInst>(op0.GetOwner());
const auto& perm = transpose->GetPermutation();
const auto& orig_axes = inst->GetAxis();
std::vector<int> new_axes(orig_axes.size());
std::transform(orig_axes.begin(), orig_axes.end(), new_axes.begin(),
[&perm](int x) { return perm[x]; });
ReduceInstTy* new_inst =
build(builder, inst->GetName(), transpose->GetOperand(0));
new_inst->SetAxis(new_axes);
ret.second = *new_inst;
return ret;
}
return ret;
}
static std::pair<Def, Def> RunOnCommonReductionInstruction(Instruction* inst) {
Def orig_def{inst, 0};
auto op0 = inst->GetOperand(0);
const Type& dst_type = inst->GetResultsTypes()[0];
const Type& op0_type = op0.GetType();
OpCode opcode = inst->GetOpCode();
// Move the constant axis into attribute.
if (inst->GetNumOfOperands() > 1 && IsA<Constant>(inst->GetOperand(1))) {
const Constant* data = DynCast<Constant>(inst->GetOperand(1).GetOwner());
const Type& ty = data->GetResultType();
if (ty.GetDataType() == DataType::INT32) {
const int32_t* ptr = data->GetDataPtr<int32_t>();
std::vector<int> axis(ptr, ptr + ty.GetTotalNumOfElements()); // NOLINT
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
Instruction* ret = nullptr;
switch (opcode) {
case OpCode::REDUCEMEAN: {
ReduceMeanInst* new_inst = DynCast<ReduceMeanInst>(
builder.Clone(*inst, {inst->GetOperand(0)}));
new_inst->SetAxis(axis);
ret = new_inst;
break;
}
case OpCode::ARGMAX: {
ArgmaxInst* new_inst =
DynCast<ArgmaxInst>(builder.Clone(*inst, {inst->GetOperand(0)}));
new_inst->SetAxis(axis.at(0));
ret = new_inst;
break;
}
default: {
break;
}
}
if (ret != nullptr) {
ret->GetResultsTypes()[0] = inst->GetResultType();
return {orig_def, *ret};
}
}
}
if (inst->GetNumOfOperands() == 1) {
std::pair<Def, Def> ret{orig_def, orig_def};
switch (opcode) {
case OpCode::REDUCEMIN: {
ret = EliminateTranspose(
DynCast<ReduceMinInst>(inst),
[](IRBuilder& builder, const std::string& name, const Def& def) {
return builder.CreateReduceMin(name, {def});
});
break;
}
case OpCode::REDUCEMAX: {
ret = EliminateTranspose(
DynCast<ReduceMaxInst>(inst),
[](IRBuilder& builder, const std::string& name, const Def& def) {
return builder.CreateReduceMax(name, {def});
});
break;
}
case OpCode::REDUCEMEAN: {
ret = EliminateTranspose(
DynCast<ReduceMeanInst>(inst),
[](IRBuilder& builder, const std::string& name, const Def& def) {
return builder.CreateReduceMean(name, {def});
});
break;
}
case OpCode::REDUCEPRODUCT: {
ret = EliminateTranspose(
DynCast<ReduceProductInst>(inst),
[](IRBuilder& builder, const std::string& name, const Def& def) {
return builder.CreateReduceProduct(name, {def});
});
break;
}
default: {
break;
}
}
if (ret.first != ret.second) {
return ret;
}
}
if (!dst_type.IsValid() || !IsA<Constant>(op0.GetOwner()) ||
op0_type.GetNumOfDims() > 1) {
return {orig_def, orig_def};
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_input = DynCast<Constant>(op0.GetOwner());
DataType dt = op0_type.GetDataType();
if (op0_type.GetTotalNumOfElements() == 1) {
Constant* c_ret = nullptr;
if (opcode == OpCode::ARGMAX || opcode == OpCode::ARGMIN) {
int ret = 0;
c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret);
} else {
c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type,
c_input->GetRawDataPtr());
}
return {orig_def, *c_ret};
}
if (dt == DataType::INT32) {
switch (opcode) {
case OpCode::REDUCEMIN:
case OpCode::REDUCEMAX:
case OpCode::ARGMAX: {
int ret = std::numeric_limits<int32_t>::lowest();
int index = -1;
for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) {
int data_i = c_input->GetData<int>(i);
ret = std::max(ret, data_i);
if (ret == data_i) {
index = i;
}
}
if (opcode == OpCode::REDUCEMAX || opcode == OpCode::REDUCEMIN) {
auto new_def =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret);
return {orig_def, *new_def};
}
// ARGMAX
auto new_def =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, &index);
return {orig_def, *new_def};
}
case OpCode::REDUCEMEAN:
case OpCode::REDUCESUM: {
int ret = 0;
for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) {
ret += c_input->GetData<int>(i);
}
if (opcode == OpCode::REDUCEMEAN) {
ret /= op0_type.GetTotalNumOfElements();
}
auto new_def =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret);
return {orig_def, *new_def};
}
case OpCode::REDUCEPRODUCT: {
int ret = 1;
for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) {
ret *= c_input->GetData<int>(i);
}
auto new_def =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret);
return {orig_def, *new_def};
}
default: {
return {orig_def, orig_def};
}
}
}
return {orig_def, orig_def};
}
/// By default, nothing is updated.
std::pair<Def, Def> InstSimplify::RunOnInstruction(Instruction* inst) {
switch (inst->GetOpCode()) {
case OpCode::ADD:
case OpCode::MUL:
case OpCode::DIV:
case OpCode::SUB:
case OpCode::CMP: {
return RunOnMathBinaryInstruction(inst, disable_broadcasting_,
fuse_conv_bias_);
}
case OpCode::REDUCEMAX:
case OpCode::REDUCEMIN:
case OpCode::REDUCEMEAN:
case OpCode::REDUCESUM:
case OpCode::REDUCEPRODUCT:
case OpCode::ARGMAX:
case OpCode::ARGMIN: {
return RunOnCommonReductionInstruction(inst);
}
default: {
return std::make_pair(Def{inst, 0}, Def{inst, 0});
}
}
}
template <typename InstType, typename Builder>
static std::pair<Def, Def> SinkTranspose(InstType& inst, Builder build) {
std::pair<Def, Def> ret{Def{&inst, 0}, Def{&inst, 0}};
if (IsA<Instruction>(inst.GetOperand(0))) {
// Inst(transpose(x)) -> transpose(Inst(x)), this exposes opportunites
// to cancel out transposes.
Instruction* op0_inst = DynCast<Instruction>(inst.GetOperand(0));
if (op0_inst->GetOpCode() == OpCode::TRANSPOSE) {
const TransposeInst* orig_trans = DynCast<TransposeInst>(op0_inst);
IRBuilder builder(inst.GetParent());
builder.SetInsertAfter(&inst);
InstType* new_inst =
build(builder, inst.GetName(), op0_inst->GetOperand(0));
TransposeInst* new_trans =
builder.CreateTranspose(inst.GetName() + "_t", {*new_inst});
new_trans->SetPermutation(orig_trans->GetPermutation());
ret.second = *new_trans;
return ret;
}
}
return ret;
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(LeakyReluInst* inst) {
return SinkTranspose(*inst, [inst](IRBuilder& builder,
const std::string& name, const Def& op) {
auto new_inst = builder.CreateLeakyRelu(name, op);
new_inst->SetAlpha(inst->GetAlpha());
return new_inst;
});
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(PReluInst* inst) {
auto op1 = inst->GetOperand(1);
return SinkTranspose(
*inst,
[inst, &op1](IRBuilder& builder, const std::string& name, const Def& op) {
return DynCast<PReluInst>(builder.Clone(*inst, {op, op1}));
});
}
template <typename T>
static Constant* GetPermutedConstant(ConstantBuilder* cb, const Constant* orig,
const std::vector<int32_t>& perm) {
const auto& shape_type = orig->GetResultType();
auto ranks = shape_type.GetTotalNumOfElements();
std::vector<T> data(ranks);
for (int64_t i = 0; i < ranks; ++i) {
data[perm[i]] = orig->GetData<T>(i);
}
return cb->CreateConstant(orig->GetName(), shape_type, data.data());
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ResizeInst* inst) {
Def orig_def{inst, 0};
auto op_shape = inst->GetOperand(1);
if (IsA<Instruction>(inst->GetOperand(0))) {
Instruction* op0_inst =
DynCast<Instruction>(inst->GetOperand(0).GetOwner());
if (auto op1 = inst->GetOperand(1);
op0_inst->GetOpCode() == OpCode::TRANSPOSE && IsA<Constant>(op1)) {
Constant* shape = DynCast<Constant>(op1);
const auto& shape_type = shape->GetResultType();
ConstantBuilder cb(inst->GetParent()->GetParent());
auto orig_perm = DynCast<TransposeInst>(op0_inst)->GetPermutation();
Constant* new_shape = nullptr;
switch (shape_type.GetDataType()) {
case DataType::INT32: {
new_shape = GetPermutedConstant<int32_t>(&cb, shape, orig_perm);
break;
}
case DataType::INT64: {
new_shape = GetPermutedConstant<int64_t>(&cb, shape, orig_perm);
break;
}
case DataType::FLOAT32: {
new_shape = GetPermutedConstant<float>(&cb, shape, orig_perm);
break;
}
default:
HLCHECK(0 && "Invalid resize shape type");
}
new_shape->SetName(inst->GetName() + "_resize_shape");
return SinkTranspose(
*inst, [new_shape, inst](IRBuilder& builder, const std::string& name,
const Def& op) {
auto new_inst = builder.CreateResize(name, {op, *new_shape});
new_inst->CopyAttrsFrom(*inst);
return new_inst;
});
}
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(Relu6Inst* inst) {
return SinkTranspose(
*inst, [](IRBuilder& builder, const std::string& name, const Def& op) {
return builder.CreateRelu6(name, op);
});
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(SigmoidInst* inst) {
return SinkTranspose(
*inst, [](IRBuilder& builder, const std::string& name, const Def& op) {
return builder.CreateSigmoid(name, op);
});
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ReluInst* inst) {
return SinkTranspose(
*inst, [](IRBuilder& builder, const std::string& name, const Def& op) {
return builder.CreateRelu(name, op);
});
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(Conv2DInst* inst) {
std::pair<Def, Def> ret{Def{inst, 0}, Def{inst, 0}};
if (!inst->GetResultType().IsValid()) {
return ret;
}
Def op_input = inst->GetOperand(0);
Def op_kernel = inst->GetOperand(1);
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
// Convert conv(pad(x, amt), kernel) to conv(x, kernel) to eliminate
// pad op.
if (IsA<Instruction>(op_input) &&
DynCast<Instruction>(op_input)->GetOpCode() == OpCode::PAD) {
const PadInst* pad = DynCast<PadInst>(op_input);
Def pad_op0 = pad->GetOperand(0);
Def pad_op1 = pad->GetOperand(1);
if (IsA<Constant>(pad_op1.GetOwner())) {
const Constant* pad_amt = DynCast<Constant>(pad_op1);
unsigned dims = pad_amt->GetResultType().GetNumOfDims();
if (dims == 2 &&
pad_amt->GetResultType().GetTotalNumOfElements() == 4 * dims) {
std::vector<int32_t> vals(
pad_amt->GetDataPtr<int32_t>(),
pad_amt->GetDataPtr<int32_t>() + 4 * dims); // NOLINT
if (vals[0] != 0 || vals[1] != 0) {
return ret;
}
const auto& info = ImageAxisInfo::GetImageAxisInfo(
inst->GetDataFormat(), inst->GetFilterFormat());
std::array<int, 4> indices_nc = {0, 1, info.data_channel_axis * 2,
info.data_channel_axis * 2 + 1};
// No paddings on N & C.
for (auto idx : indices_nc) {
if (vals[idx] != 0) {
return ret;
}
}
std::array<int, 4> indices_hw = {
info.data_height_axis * 2, info.data_height_axis * 2 + 1,
info.data_width_axis * 2, info.data_width_axis + 1};
Conv2DInst* new_inst =
builder.CreateConv2D(inst->GetName(), {pad_op0, op_kernel});
new_inst->SetDataFormat(inst->GetDataFormat());
new_inst->SetFilterFormat(inst->GetFilterFormat());
new_inst->SetDilations(inst->GetDilations());
new_inst->SetStrides(inst->GetStrides());
new_inst->SetPaddingTop(inst->GetPaddingTop() + vals[indices_hw[0]]);
new_inst->SetPaddingBottom(inst->GetPaddingBottom() +
vals[indices_hw[1]]);
new_inst->SetPaddingLeft(inst->GetPaddingLeft() + vals[indices_hw[2]]);
new_inst->SetPaddingRight(inst->GetPaddingRight() +
vals[indices_hw[3]]);
new_inst->GetResultsTypes()[0] = inst->GetResultsTypes()[0];
new_inst->SetPadding(Padding::EXPLICIT);
ret.second = Def(new_inst, 0);
}
}
}
// Convert Conv(add(x, c), k) => Conv(x, k') or Conv(mul(x, c), k) ==>
// Conv(x, k') where k is a constant of scalar or channel-wise vector.
if (IsA<Instruction>(op_input) && IsA<Constant>(op_kernel) &&
inst->GetGroup() == 1 && inst->GetResultType().IsValid() &&
(DynCast<Instruction>(op_input)->GetOpCode() == OpCode::ADD ||
DynCast<Instruction>(op_input)->GetOpCode() == OpCode::MUL)) {
Instruction* binary_inst = DynCast<Instruction>(op_input);
auto binary_op0 = binary_inst->GetOperand(0);
if (IsA<Instruction>(binary_op0) &&
DynCast<Instruction>(binary_op0)->GetOpCode() == OpCode::CONV2D) {
// For pattens like a = conv(); b = a + c; d = conv(b), prefer to fuse a
// and b.
return ret;
}
auto binary_op1 = binary_inst->GetOperand(1);
if (!IsA<Constant>(binary_op1)) {
return ret;
}
const auto& kernel_type = op_kernel.GetType();
Constant* c = DynCast<Constant>(binary_op1);
if (kernel_type.GetDataType() != DataType::FLOAT32 ||
kernel_type.GetDataType() != c->GetResultType().GetDataType()) {
return ret;
}
// match shape of C: expect [..,in_chs, 1, 1].
auto n_elems = c->GetResultType().GetTotalNumOfElements();
auto dims = c->GetResultType().GetDimSizes();
auto kernel_shape = kernel_type.GetDimSizes();
const auto& info = ImageAxisInfo::GetImageAxisInfo(inst->GetDataFormat(),
inst->GetFilterFormat());
auto in_chs = kernel_shape[info.kernel_input_axis];
auto in_chs_dim_r =
info.kernel_input_axis - kernel_shape.size(); // Dims in backwards.
if (!(n_elems == in_chs &&
(dims.size() == 1 || (-in_chs_dim_r <= dims.size() &&
dims[dims.size() + in_chs_dim_r] == in_chs)))) {
return ret;
}
bool has_padding =
inst->GetPaddingBottom() != 0 || inst->GetPaddingLeft() != 0 ||
inst->GetPaddingTop() != 0 || inst->GetPaddingRight() != 0;
Constant* kernel = DynCast<Constant>(op_kernel);
ConstantBuilder cb(inst->GetParent()->GetParent());
std::vector<float> new_kernel_data(kernel_type.GetTotalNumOfElements());
auto operands = inst->GetOperands();
operands[0] = binary_op0;
std::vector<size_t> strides(kernel_shape.size(), 1);
for (int64_t i = kernel_shape.size() - 2; i >= 0; --i) {
strides[i] = strides[i + 1] * kernel_shape[i + 1];
}
if (binary_inst->GetOpCode() == OpCode::MUL) {
for (size_t i = 0, e = kernel_type.GetTotalNumOfElements(); i < e; ++i) {
size_t ch = (i / strides[info.kernel_input_axis]) % in_chs;
new_kernel_data[i] =
kernel->GetDataAsFloat32(i) * c->GetDataAsFloat32(ch);
}
auto new_kernel =
cb.CreateConstant(kernel->GetName(), kernel_type, new_kernel_data);
operands[1] = *new_kernel;
ret.second = *builder.Clone(*inst, operands);
} else if (!has_padding && (inst->GetNumOfOperands() == 2 ||
(inst->GetNumOfOperands() == 3 &&
IsA<Constant>(inst->GetOperand(2))))) {
auto out_chs = kernel_shape[info.kernel_output_axis];
// Conv(x + c), k) ==> Conv(x, k) + c * k)
// C is vector (len = in_chs), reshape k to (H * W, out_chs, in_chs)
std::vector<float> new_bias(out_chs);
std::string bias_name = inst->GetName() + "_bias";
if (inst->GetNumOfOperands() == 3) {
auto orig_bias = DynCast<Constant>(inst->GetOperand(2));
bias_name = orig_bias->GetName() + "_fused";
HLCHECK(orig_bias->GetResultType().GetTotalNumOfElements() == out_chs);
for (int i = 0; i < out_chs; ++i) {
new_bias[i] = orig_bias->GetDataAsFloat32(i);
}
}
auto hw = kernel_type.GetTotalNumOfElements() / in_chs / out_chs;
auto stride_s = strides[info.kernel_width_axis];
auto stride_o = strides[info.kernel_output_axis];
auto stride_i = strides[info.kernel_input_axis];
for (int s = 0; s < hw; ++s) {
for (int och = 0; och < out_chs; ++och) {
std::vector<float> m(in_chs);
float t = 0;
for (int i = 0; i < in_chs; ++i) {
t += kernel->GetDataAsFloat32(s * stride_s + och * stride_o +
i * stride_i) *
c->GetDataAsFloat32(i);
}
new_bias[och] += t;
}
}
halo::Type type{kernel_type.GetDataType(), {out_chs}};
auto new_bias_op = cb.CreateConstant(bias_name, type, new_bias);
if (operands.size() >= 3) {
operands[2] = *new_bias_op;
} else {
operands.push_back(*new_bias_op);
}
ret.second = *builder.Clone(*inst, operands);
}
}
return ret;
}
static void Pad(char* dst, const char* src, size_t elems_num, size_t elem_size,
const std::vector<int64_t>& orig_shape,
const std::vector<int64_t>& new_shape,
const std::vector<int32_t>& padding_amt) {
std::vector<size_t> pos(orig_shape.size());
std::vector<size_t> dst_strides(orig_shape.size(), 1);
int dims = orig_shape.size();
for (int i = dims - 2; i >= 0; --i) {
dst_strides[i] = dst_strides[i + 1] * new_shape[i + 1];
}
for (size_t i = 0; i < elems_num; ++i) {
auto dst_pos = pos;
for (int j = 0; j < dims; ++j) {
dst_pos[j] += padding_amt[j];
}
size_t dst_offset = std::inner_product(dst_pos.begin(), dst_pos.end(),
dst_strides.begin(), 0UL) *
elem_size;
std::copy(src, src + elem_size, dst + dst_offset); // NOLINT.
src += elem_size; // NOLINT.
int c = 1;
for (int j = dims - 1; j >= 0 && c == 1; --j) {
pos[j] += c;
if (pos[j] >= static_cast<size_t>(orig_shape[j])) {
pos[j] = 0;
} else {
c = 0;
}
}
}
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(PadInst* pad_inst) {
Def orig_def{pad_inst, 0};
Def op0 = pad_inst->GetOperand(0);
Def op1 = pad_inst->GetOperand(1);
if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) ||
pad_inst->GetNumOfOperands() != 2 ||
pad_inst->GetMode() != PadMode::CONSTANT) {
return {orig_def, orig_def};
}
const Constant* data = DynCast<Constant>(op0.GetOwner());
const Constant* pad_amt = DynCast<Constant>(op1.GetOwner());
ConstantBuilder cb(pad_inst->GetParent()->GetParent());
auto dims = op0.GetType().GetNumOfDims();
std::vector<int64_t> shape(dims);
std::vector<int32_t> paddings_before(dims);
for (size_t i = 0; i < dims; ++i) {
int32_t before = pad_amt->GetDataPtr<int32_t>()[i * 2]; // NOLINT
int32_t after = pad_amt->GetDataPtr<int32_t>()[i * 2 + 1]; // NOLINT
shape[i] = op0.GetType().GetNumOfElementsInDim(i) + before + after;
paddings_before[i] = before;
}
halo::Type type{op0.GetType().GetDataType(), shape};
std::vector<char> w(type.GetTotalNumOfElements() *
data->GetElementSizeInBytes());
std::vector<size_t> dim_sizes(dims);
Pad(w.data(), static_cast<const char*>(data->GetRawDataPtr()),
op0.GetType().GetTotalNumOfElements(), data->GetElementSizeInBytes(),
op0.GetType().GetDimSizes(), shape, paddings_before);
auto new_inst = cb.CreateConstant("folded_pad", type, w.data());
return {orig_def, Def{new_inst, 0}};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ReshapeInst* reshape_inst) {
Def orig_def{reshape_inst, 0};
// for reshape(reshape(x, c0), c1), replace it with reshape(x, c1).
auto op0 = reshape_inst->GetOperand(0).GetDef();
if (IsA<Instruction>(op0)) {
const Instruction* op0_inst = Downcast<const Instruction>(op0);
if (op0_inst->GetOpCode() == OpCode::RESHAPE) {
IRBuilder builder(reshape_inst->GetParent());
builder.SetInsertAfter(reshape_inst);
auto new_inst = builder.CreateReshape(reshape_inst->GetName(),
op0_inst->GetOperand(0),
reshape_inst->GetOperand(1));
new_inst->GetResultsTypes()[0] = reshape_inst->GetResultsTypes()[0];
return {orig_def, Def{new_inst, 0}};
}
}
const auto& input_type = op0->GetResultType();
const auto& ret_type = reshape_inst->GetResultType();
if (input_type.IsValid() && ret_type.IsValid() && input_type == ret_type) {
return {orig_def, *op0};
}
if (IsA<Constant>(op0) && reshape_inst->GetResultType().IsValid()) {
Constant* src = DynCast<Constant>(op0);
Constant* new_c = nullptr;
if (op0->GetNumberOfUses() == 1) {
new_c = src;
} else {
ConstantBuilder cb(reshape_inst->GetParent()->GetParent());
new_c = cb.Clone(*src);
}
new_c->GetResultsTypes()[0] = reshape_inst->GetResultType();
return {orig_def, *new_c};
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ExpandDimsInst* inst) {
HLCHECK(inst->GetNumOfOperands() == 2);
auto input = inst->GetOperand(0);
const auto& input_type = input.GetType();
Def orig_def{inst, 0};
if (!input_type.IsValid() || !IsA<Constant>(inst->GetOperand(1))) {
return {orig_def, orig_def};
}
const Constant* shape = DynCast<Constant>(inst->GetOperand(1));
auto input_elem = input_type.GetTotalNumOfElements();
HLCHECK(shape->GetResultType().GetNumOfDims() == 1);
std::vector<int64_t> output_shape;
std::vector<int64_t> output_extends;
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
int shape_rank = shape->GetResultType().GetTotalNumOfElements();
int input_rank = input_type.GetNumOfDims();
auto src_extends = GetExtends(input_type.GetDimSizes());
for (int i = 0, e = std::max(shape_rank, input_rank); i < e; ++i) {
int input_idx = input_rank - 1 - i;
int shape_idx = shape_rank - 1 - i;
int64_t dim0 =
(input_idx < 0) ? 1 : input_type.GetNumOfElementsInDim(input_idx);
int64_t dim1 = (shape_idx < 0) ? 1 : shape->GetDataAsInt64(shape_idx);
HLCHECK(dim0 == dim1 || dim0 == 1 || dim1 == 1);
output_shape.push_back((dim0 == 1) ? dim1 : dim0);
bool is_bs = dim0 == 1;
output_extends.push_back(is_bs ? 0 : src_extends[input_idx]);
}
std::reverse(output_shape.begin(), output_shape.end());
std::reverse(output_extends.begin(), output_extends.end());
halo::Type ret_type{input_type.GetDataType(), output_shape};
auto ret_elem = ret_type.GetTotalNumOfElements();
ConstantBuilder cb(inst->GetParent()->GetParent());
if (input_elem == ret_elem) {
Constant* c = cb.CreateConstant(
inst->GetName() + "_expand",
halo::Type{DataType::INT64,
{static_cast<int64_t>(output_shape.size())}},
output_shape.data());
auto reshape =
builder.CreateReshape(inst->GetName(), {inst->GetOperand(0), *c});
return {orig_def, *reshape};
}
if (IsA<Constant>(inst->GetOperand(0))) {
const Constant* src = DynCast<Constant>(input);
DefaultDataLayout data_layout;
size_t elem_size = data_layout.Bytes(input_type.GetDataType());
std::vector<unsigned char> buf(ret_elem * elem_size);
const auto& dst_extends = GetExtends(output_shape);
for (int64_t dst_idx = 0; dst_idx < ret_elem; ++dst_idx) {
std::vector<int64_t> dst_dims(output_shape.size());
for (int64_t i = 0, e = dst_dims.size(), t = dst_idx; t >= 0 && i < e;
++i) {
dst_dims[i] = t / dst_extends[i];
t -= dst_dims[i] * dst_extends[i];
}
auto src_idx = std::inner_product(
output_extends.begin(), output_extends.end(), dst_dims.begin(), 0L);
const unsigned char* src_ptr =
static_cast<const unsigned char*>(src->GetRawDataPtr()) + // NOLINT.
src_idx * elem_size;
std::copy_n(src_ptr, elem_size, buf.begin() + dst_idx * elem_size);
}
Constant* c =
cb.CreateConstant(inst->GetName() + "_expand", ret_type, buf.data());
return {orig_def, *c};
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(BatchNormInst* inst) {
Def orig_def{inst, 0};
int num_inputs = inst->GetNumOfOperands();
const auto& input_type = inst->GetResultType();
auto input = inst->GetOperand(0);
// Not profitable if the mul cannot be fused.
auto input_op = IsA<Instruction>(input)
? DynCast<Instruction>(input)->GetOpCode()
: OpCode::INVALID;
bool is_profitable =
input_op == OpCode::CONV2D || input_op == OpCode::CONV2DTRANSPOSE;
if (disable_conv_bn_ || !is_profitable || num_inputs <= 4 ||
!input_type.IsValid() || input_type.GetNumOfDims() != 4 ||
!IsA<Constant>(inst->GetOperand(3)) ||
!IsA<Constant>(inst->GetOperand(4))) {
return {orig_def, orig_def};
}
auto scale = DynCast<Constant>(inst->GetOperand(1));
auto offset = DynCast<Constant>(inst->GetOperand(2));
auto mean = DynCast<Constant>(inst->GetOperand(3));
auto variance = DynCast<Constant>(inst->GetOperand(4));
int ch_dim = inst->GetDataFormat() == DataFormat::NCHW ? 1 : 3;
auto ch_num = input_type.GetNumOfElementsInDim(ch_dim);
const auto& mean_type = mean->GetResultType();
if (mean_type.GetTotalNumOfElements() != ch_num ||
variance->GetResultType().GetTotalNumOfElements() != ch_num ||
mean_type.GetDataType() != DataType::FLOAT32) {
return {orig_def, orig_def};
}
std::vector<float> mul_buf(ch_num);
std::vector<float> add_buf(ch_num);
float eps = inst->GetEpsilon();
// Convert BN to Ax + B.
for (int64_t i = 0; i < ch_num; ++i) {
mul_buf[i] = 1.0F / std::sqrt(variance->GetData<float>(i) + eps);
float s = scale->GetData<float>(i);
mul_buf[i] *= s;
float b = offset->GetData<float>(i);
add_buf[i] = -mean->GetData<float>(i) * mul_buf[i] + b;
}
std::vector<int64_t> shape(input_type.GetNumOfDims(), 1);
shape[ch_dim] = ch_num;
halo::Type ty{mean_type.GetDataType(), shape};
ConstantBuilder cb(inst->GetParent()->GetParent());
auto new_scale =
cb.CreateConstant(inst->GetName() + "_0", ty, mul_buf.data());
auto new_offset =
cb.CreateConstant(inst->GetName() + "_1", ty, add_buf.data());
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
auto new_mul = builder.CreateMul(inst->GetName() + "_mul", input, *new_scale);
auto new_add =
builder.CreateAdd(inst->GetName() + "_add", *new_mul, *new_offset);
return {orig_def, *new_add};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(StackInst* inst) {
Def orig_def{inst, 0};
int num_inputs = inst->GetNumOfOperands();
if (inst->GetAxis() != 0) {
return {orig_def, orig_def};
}
for (int i = 0; i < num_inputs; ++i) {
if (!IsA<Constant>(inst->GetOperand(i))) {
return {orig_def, orig_def};
}
}
// convert to an array of constant
const auto& input0_type = inst->GetOperand(0).GetType();
std::vector<int64_t> ret_shape(input0_type.GetDimSizes());
ret_shape.insert(ret_shape.begin(), num_inputs);
ConstantBuilder cb(inst->GetParent()->GetParent());
auto count = input0_type.GetTotalNumOfElements();
Constant* c_input0 = DynCast<Constant>(inst->GetOperand(0).GetOwner());
size_t copy_size = count * c_input0->GetElementSizeInBytes();
std::vector<char> buf(num_inputs * copy_size);
for (int i = 0; i < num_inputs; ++i) {
Constant* c_input_i = DynCast<Constant>(inst->GetOperand(i).GetOwner());
memcpy(&buf[copy_size * i], c_input_i->GetRawDataPtr(), copy_size);
}
halo::Type result_type{input0_type.GetDataType(), ret_shape};
auto new_def =
cb.CreateConstant(inst->GetName() + "_folding", result_type, buf.data());
return {orig_def, *new_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ZExtInst* inst) {
Def orig_def{inst, 0};
DataType ret_dt = inst->GetDataType();
auto op0 = inst->GetOperand(0);
const auto& op0_type = op0.GetType();
DataType src_dt = op0_type.GetDataType();
HLCHECK(halo::Type::IsIntegerType(src_dt) &&
halo::Type::IsIntegerType(ret_dt));
if (!op0_type.IsValid() || !IsA<Constant>(op0)) {
return {orig_def, orig_def};
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_src = DynCast<Constant>(op0.GetOwner());
if (ret_dt == DataType::INT32 && src_dt == DataType::BOOL) {
std::vector<int> ret;
ret.reserve(op0_type.GetTotalNumOfElements());
for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) {
ret.push_back(static_cast<int>(c_src->GetData<int8_t>(i)));
}
Constant* c_ret = cb.CreateConstant(
inst->GetName(), halo::Type{ret_dt, op0_type.GetDimSizes()},
ret.data());
return {orig_def, *c_ret};
}
if (ret_dt == DataType::INT32 && src_dt == DataType::INT64) {
std::vector<int32_t> ret;
ret.reserve(op0_type.GetTotalNumOfElements());
for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) {
ret.push_back(static_cast<int32_t>(c_src->GetData<int64_t>(i)));
}
Constant* c_ret = cb.CreateConstant(
inst->GetName() + "_folding",
halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data());
return {orig_def, *c_ret};
}
if (ret_dt == DataType::INT64 && src_dt == DataType::INT32) {
std::vector<int64_t> ret;
ret.reserve(op0_type.GetTotalNumOfElements());
for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) {
ret.push_back(static_cast<int64_t>(c_src->GetData<int32_t>(i)));
}
Constant* c_ret = cb.CreateConstant(
inst->GetName() + "_folding",
halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data());
return {orig_def, *c_ret};
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(RangeInst* inst) {
Def orig_def{inst, 0};
auto op0 = inst->GetOperand(0);
auto op1 = inst->GetOperand(1);
auto op2 = inst->GetOperand(2);
DataType dt = op0.GetType().GetDataType();
if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) ||
!IsA<Constant>(op2.GetOwner()) || dt != DataType::INT32) {
return {orig_def, orig_def};
}
int64_t num_elements = 0;
Constant* c_op0 = DynCast<Constant>(op0.GetOwner());
Constant* c_op1 = DynCast<Constant>(op1.GetOwner());
Constant* c_op2 = DynCast<Constant>(op2.GetOwner());
int begin = c_op0->GetData<int32_t>(0);
int end = c_op1->GetData<int32_t>(0);
int step = c_op2->GetData<int32_t>(0);
num_elements = std::max(0, (end - begin) / step);
HLCHECK(num_elements);
std::vector<int> ret_data(num_elements);
ret_data[0] = begin;
for (int i = 1; i < num_elements; ++i) {
ret_data[i] = ret_data[i - 1] + step;
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_ret =
cb.CreateConstant(inst->GetName() + "_folding",
halo::Type{dt, {num_elements}}, ret_data.data());
return {orig_def, *c_ret};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(SetDiff1DInst* inst) {
Def orig_def{inst, 0};
auto op0 = inst->GetOperand(0);
auto op1 = inst->GetOperand(1);
const auto& op0_type = op0.GetType();
const auto& op1_type = op1.GetType();
DataType dt = op0_type.GetDataType();
if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) ||
dt != DataType::INT32) {
return {orig_def, orig_def};
}
std::vector<int> ret_data;
std::unordered_set<int> diff_set;
Constant* c_op0 = DynCast<Constant>(op0.GetOwner());
Constant* c_op1 = DynCast<Constant>(op1.GetOwner());
for (int i = 0, e = op1_type.GetTotalNumOfElements(); i != e; ++i) {
diff_set.emplace(c_op1->GetData<int>(i));
}
for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) {
int data_i = c_op0->GetData<int>(i);
if (diff_set.count(data_i) == 0) {
ret_data.push_back(data_i);
}
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_ret = cb.CreateConstant(
inst->GetName() + "_folding",
halo::Type{dt, {static_cast<int64_t>(ret_data.size())}}, ret_data.data());
return {orig_def, *c_ret};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(GatherInst* inst) {
Def orig_def{inst, 0};
int axis = inst->GetAxis();
const auto& dst_type = inst->GetResultsTypes()[0];
const auto& type_op0 = inst->GetOperand(0).GetType();
const auto& op1 = inst->GetOperand(1);
// Gather(data, ZExt(index, int64)) ==> Gather(data, index)
if (IsA<Instruction>(op1) &&
DynCast<Instruction>(op1)->GetOpCode() == OpCode::ZEXT) {
IRBuilder builder(inst->GetParent());
ZExtInst* zext = DynCast<ZExtInst>(op1.GetDef());
builder.SetInsertAfter(inst);
auto ops = inst->GetOperands();
ops[1] = zext->GetOperand(0);
auto new_inst = builder.Clone(*inst, ops);
return {orig_def, *new_inst};
}
if (!type_op0.IsValid()) {
return {orig_def, orig_def};
}
if (axis < 0) {
axis += type_op0.GetNumOfDims();
}
HLCHECK(axis >= 0 && axis < static_cast<int>(type_op0.GetNumOfDims()));
for (size_t i = 0; i < inst->GetNumOfOperands(); ++i) {
if (!IsA<Constant>(inst->GetOperand(i).GetOwner())) {
return {orig_def, orig_def};
}
}
if (!dst_type.IsValid()) {
return {orig_def, orig_def};
}
Constant* c_op0 = DynCast<Constant>(inst->GetOperand(0).GetOwner());
const auto& type_op1 = inst->GetOperand(1).GetType();
Constant* c_op1 = DynCast<Constant>(inst->GetOperand(1).GetOwner());
DataType dt = dst_type.GetDataType();
DefaultDataLayout data_layout;
size_t byte_per_element = data_layout.Bytes(dt);
size_t bytes = byte_per_element * dst_type.GetTotalNumOfElements();
std::vector<unsigned char> buf(bytes);
size_t per_copy_bytes = byte_per_element;
auto dst_extends = GetExtends(dst_type.GetDimSizes());
auto src_extends = GetExtends(type_op0.GetDimSizes());
auto idx_extends = GetExtends(type_op1.GetDimSizes());
int64_t dst_rank = dst_type.GetNumOfDims();
if (dst_rank == 0 && dst_type.GetTotalNumOfElements() == 1) {
dst_rank = 1;
}
int op1_rank = type_op1.GetNumOfDims();
if (op1_rank == 0 && type_op1.GetTotalNumOfElements() == 1) {
op1_rank = 1;
}
for (int64_t dst_idx = 0, e = dst_type.GetTotalNumOfElements(); dst_idx < e;
++dst_idx) {
// map dst_idx to src_idx.
std::vector<int64_t> dst_dims(dst_rank);
for (int64_t i = 0, k = dst_idx; k > 0 && i < dst_rank; ++i) {
dst_dims[i] = k / dst_extends[i];
k -= dst_dims[i] * dst_extends[i];
}
std::vector<int64_t> src_dims(type_op0.GetNumOfDims());
for (int i = 0; i < dst_rank; ++i) {
if (i < axis) {
src_dims[i] = dst_dims[i];
} else if (i >= (axis + op1_rank)) {
src_dims[i - op1_rank + 1] = dst_dims[i];
} else {
int64_t idx = std::inner_product(idx_extends.begin(), idx_extends.end(),
dst_dims.begin() + axis, 0L);
src_dims[axis] = c_op1->GetDataAsInt64(idx);
}
}
int64_t src_idx = std::inner_product(src_dims.begin(), src_dims.end(),
src_extends.begin(), 0L);
unsigned char* src_ptr =
static_cast<unsigned char*>(c_op0->GetRawDataPtr()) + // NOLINT.
src_idx * per_copy_bytes;
std::copy_n(src_ptr, per_copy_bytes,
buf.begin() + dst_idx * per_copy_bytes);
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_ret =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, buf.data());
return {orig_def, *c_ret};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ConcatInst* inst) {
Def orig_def{inst, 0};
// Concat(Transpose(A), Transpose(B),...) => Transpose(Concat(A, B))
std::vector<int> perm;
size_t n = inst->GetNumOfOperands();
std::vector<Def> tr_ops;
tr_ops.reserve(n);
for (size_t i = 0; i < n; ++i) {
auto op = inst->GetOperand(i);
if (!IsA<Instruction>(op)) {
break;
}
const Instruction* op_inst = DynCast<Instruction>(op);
if (op_inst->GetOpCode() != OpCode::TRANSPOSE) {
break;
}
const TransposeInst* tr = DynCast<const TransposeInst>(op_inst);
if (i == 0) {
perm = tr->GetPermutation();
} else if (perm != tr->GetPermutation()) {
break;
}
tr_ops.push_back(tr->GetOperand(0));
}
if (tr_ops.size() == n) {
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
auto new_concat = builder.CreateConcat(inst->GetName(), tr_ops);
new_concat->SetAxis(perm[inst->GetAxis()]);
TransposeInst* new_tr =
builder.CreateTranspose(new_concat->GetName() + "_t", {*new_concat});
new_tr->SetPermutation(perm);
return {orig_def, *new_tr};
}
for (size_t i = 0; i < inst->GetNumOfOperands(); ++i) {
if (!IsA<Constant>(inst->GetOperand(i).GetOwner())) {
return {orig_def, orig_def};
}
}
int num_inputs = inst->GetN();
int axis = inst->GetAxis();
const auto& dst_type = inst->GetResultsTypes()[0];
if (!dst_type.IsValid() || axis != 0) {
return {orig_def, orig_def};
}
// Constant propagating on axis = 0
DataType dt = dst_type.GetDataType();
DefaultDataLayout data_layout;
size_t byte_per_element = data_layout.Bytes(dt);
size_t bytes = byte_per_element * dst_type.GetTotalNumOfElements();
std::vector<unsigned char> buf(bytes);
size_t offset = 0;
for (int i = 0; i < num_inputs; ++i) {
auto input = inst->GetOperand(i);
Constant* c_input = DynCast<Constant>(input.GetOwner());
size_t num_elements = input.GetType().GetTotalNumOfElements();
size_t copy_bytes = num_elements * byte_per_element;
std::copy_n(static_cast<unsigned char*>(c_input->GetRawDataPtr()),
copy_bytes, buf.begin() + offset);
offset += copy_bytes;
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_ret =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, buf.data());
return {orig_def, *c_ret};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(TransposeInst* inst) {
Def orig_def{inst, 0};
std::pair<Def, Def> ret{orig_def, orig_def};
const auto& input = inst->GetOperand(0);
// Fold constant perm op into attribute.
if (inst->GetNumOfOperands() == 2 && IsA<Constant>(inst->GetOperand(1))) {
const Constant* data = DynCast<Constant>(inst->GetOperand(1));
const auto& ty = data->GetResultType();
if (ty.GetDataType() == DataType::INT32) {
const int32_t* ptr = data->GetDataPtr<int32_t>();
std::vector<int> perms(ptr, ptr + ty.GetTotalNumOfElements()); // NOLINT
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
TransposeInst* new_inst =
builder.CreateTranspose(inst->GetName(), {input});
new_inst->SetPermutation(perms);
ret.second = *new_inst;
return ret;
}
}
const auto& perm = inst->GetPermutation();
auto input_type = (input.GetDef()->GetResultsTypes()[input.GetIdx()]);
int dims = -1;
std::vector<int64_t> new_shape;
std::vector<size_t> perm_strides;
std::vector<size_t> orig_strides;
if (input_type.IsValid()) {
const auto& orig_shape = input_type.GetDimSizes();
dims = orig_shape.size();
HLCHECK(orig_shape.size() == inst->GetPermutation().size());
orig_strides = std::vector<size_t>(dims, 1);
for (int i = dims - 2; i >= 0; --i) {
orig_strides[i] = orig_strides[i + 1] * orig_shape[i + 1];
}
new_shape = orig_shape;
perm_strides = orig_strides;
for (int i = 0; i < dims; ++i) {
new_shape[i] = orig_shape[perm[i]];
perm_strides[i] = orig_strides[perm[i]];
}
}
if (IsA<Constant>(input)) {
// Do transpose at compile time.
auto orig = DynCast<Constant>(input.GetOwner());
ConstantBuilder cb(inst->GetParent()->GetParent());
const auto& type = orig->GetResultType();
std::vector<int> pos(dims); // tracks the position of dst tensor.
size_t elem_size = orig->GetElementSizeInBytes();
size_t elem_cnt = type.GetTotalNumOfElements();
std::vector<char> buf(elem_size * elem_cnt);
for (size_t i = 0; i < elem_cnt; ++i) {
size_t offset = std::inner_product(pos.begin(), pos.end(),
perm_strides.begin(), 0UL) *
elem_size;
const char* src =
static_cast<const char*>(orig->GetRawDataPtr()) + offset; // NOLINT
memcpy(&buf[i * elem_size], src, elem_size);
int c = 1;
for (int i = dims - 1; i >= 0 && c == 1; --i) {
pos[i] += c;
if (pos[i] >= new_shape[i]) {
pos[i] = 0;
} else {
c = 0;
}
}
}
auto new_c = cb.CreateConstant(orig->GetName() + "_T",
halo::Type{type.GetDataType(), new_shape},
buf.data());
ret.second = *new_c;
return ret;
}
if (remove_input_transpose_ && input.GetUses().size() == 1) {
if (IsA<Argument>(input)) {
Argument* arg = DynCast<Argument>(input);
const auto& orig_dims = input.GetType().GetDimSizes();
const auto& perms = inst->GetPermutation();
auto new_dims = orig_dims;
for (int i = 0, e = orig_dims.size(); i < e; ++i) {
new_dims[i] = orig_dims[perms[i]];
}
halo::Type ty{input.GetType().GetDataType(), new_dims};
arg->SetType(ty);
ret.second = input;
return ret;
}
}
// Transpose(Transpose(in, perm0), perm1) => Transpose(in, perm2)
if (IsA<Instruction>(input) &&
(DynCast<Instruction>(input))->GetOpCode() == OpCode::TRANSPOSE) {
const TransposeInst* t0 = DynCast<TransposeInst>(input.GetOwner());
const auto& perm0 = t0->GetPermutation();
HLCHECK(perm0.size() == perm.size());
auto new_perm = perm0;
for (int i = 0, e = perm0.size(); i < e; ++i) {
new_perm[i] = perm[perm0[i]];
}
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
TransposeInst* new_trans =
builder.CreateTranspose(inst->GetName(), {t0->GetOperand(0)});
new_trans->SetPermutation(new_perm);
ret.second = *new_trans;
return ret;
}
// Check if it is a redundant permute (all other dims are 1)
const auto& type = input.GetType();
const auto& out_type = inst->GetResultType();
if (type.IsValid() && out_type.IsValid()) {
unsigned non_ones = 0;
for (auto& d : type.GetDimSizes()) {
non_ones += d == 1 ? 0 : 1;
}
if (non_ones == 1) {
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
ConstantBuilder cb(inst->GetParent()->GetParent());
halo::Type reshape_ty{DataType::INT64,
{static_cast<int64_t>(out_type.GetNumOfDims())}};
auto shape = cb.CreateConstant(inst->GetName() + "_reshape", reshape_ty,
out_type.GetDimSizes().data());
ReshapeInst* reshape =
builder.CreateReshape(inst->GetName(), {input, *shape});
reshape->GetResultsTypes()[0] = out_type;
ret.second = *reshape;
return ret;
}
}
// Check if a permutaton is redundant.
bool is_redundant = true;
for (int i = 0, e = perm.size(); i < e; ++i) {
if (perm[i] != i) {
is_redundant = false;
break;
}
}
if (is_redundant) {
ret.second = inst->GetOperand(0);
return ret;
}
// Transpose => Reshape if its' like (N, 1, H, W) => (N, H, W, 1)
if (dims > 0) {
const auto& orig_shape = input_type.GetDimSizes();
auto new_perm = perm;
for (int i = 0, a = 0; i < dims; ++i, ++a) {
if (orig_shape[i] == 1) {
for (auto& v : new_perm) {
if (v == a) {
v = -1; // skip the dim
}
if (v > a) {
--v;
}
}
--a;
}
}
bool reshapable = true;
for (int i = 0, c = 0; i < dims && reshapable; ++i) {
if (new_perm[i] >= 0) {
if (new_perm[i] != c++) {
reshapable = false;
}
}
}
if (reshapable) {
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_shape = cb.CreateConstant(
inst->GetName() + "_shape",
halo::Type{DataType::INT64, std::vector<int64_t>{dims}},
new_shape.data());
auto reshape = builder.CreateReshape(inst->GetName(),
{inst->GetOperand(0), *c_shape});
reshape->GetResultsTypes()[0] = inst->GetResultType();
ret.second = *reshape;
return ret;
}
}
return ret;
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(ReturnInst* inst) {
Def orig_def{inst, 0};
if (!remove_output_transpose_) {
return {orig_def, orig_def};
}
for (int i = 0, e = inst->GetNumOfOperands(); i < e; ++i) {
const auto& op = inst->GetOperand(i);
if (IsA<Instruction>(op) &&
DynCast<Instruction>(op)->GetOpCode() == OpCode::TRANSPOSE) {
inst->ReplaceOperandWith(i, DynCast<Instruction>(op)->GetOperand(0));
}
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(RandomUniformInst* inst) {
Def orig_def{inst, 0};
const auto& dst_type = inst->GetResultsTypes()[0];
if (dst_type.IsValid() && dst_type.GetDataType() == DataType::FLOAT32) {
auto noe = dst_type.GetTotalNumOfElements();
float max_val = inst->GetMaxval();
float min_val = inst->GetMinval();
// int seed = inst->GetSeed();
std::vector<float> ret(noe);
// std::random_device rd;
// std::mt19937 gen(rd());
std::mt19937 gen(1234); // NOLINT
std::uniform_real_distribution<> dis(min_val, max_val);
for (int i = 0; i < noe; ++i) {
ret[i] = dis(gen);
}
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_ret =
cb.CreateConstant(inst->GetName() + "_folding", dst_type, ret.data());
return {orig_def, *c_ret};
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(SliceInst* inst) {
Def orig_def{inst, 0};
auto op2 = inst->GetOperand(2);
const auto& dst_type = inst->GetResultsTypes()[0];
if (dst_type.IsValid() && IsA<Constant>(op2.GetOwner())) {
Constant* c_size = DynCast<Constant>(op2.GetOwner());
if (op2.GetType().GetDataType() == DataType::INT32) {
int dim = op2.GetType().GetTotalNumOfElements();
std::vector<int> size_adj(dim);
bool new_size = false;
for (int i = 0; i != dim; ++i) {
int size_i = c_size->GetData<int>(i);
if (size_i == -1) {
size_adj[i] = dst_type.GetNumOfElementsInDim(i);
new_size = true;
} else {
size_adj[i] = size_i;
}
}
if (new_size) {
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* c_new_size = cb.CreateConstant(
op2.GetOwner()->GetName() + "_adj", op2.GetType(), size_adj.data());
IRBuilder builder(inst->GetParent());
builder.SetInsertAfter(inst);
SliceInst* new_inst = builder.CreateSlice(
inst->GetName(),
{inst->GetOperand(0), inst->GetOperand(1), *c_new_size});
new_inst->GetResultsTypes()[0] = dst_type;
return {orig_def, *new_inst};
}
}
}
auto op0 = inst->GetOperand(0);
auto op1 = inst->GetOperand(1);
bool has_constant_steps =
(inst->GetNumOfOperands() < 4 || IsA<Constant>(inst->GetOperand(3)));
has_constant_steps &=
(inst->GetNumOfOperands() <= 4 || IsA<Constant>(inst->GetOperand(4)));
if (IsA<Constant>(op0) && IsA<Constant>(op1) && IsA<Constant>(op2) &&
inst->GetResultType().IsValid() && has_constant_steps) {
Constant* input = DynCast<Constant>(op0);
const auto& dt = inst->GetResultType();
std::vector<int64_t> data(dt.GetTotalNumOfElements());
auto starts = DynCast<Constant>(op1);
auto lens = DynCast<Constant>(op2);
// auto steps = DynCast<Constant>(op3);
// auto axes = DynCast<Constant>(op4);
auto rank = op0.GetType().GetNumOfDims();
if (rank == 1 && dt.GetDataType() == DataType::INT64) {
auto idx = starts->GetData<int32_t>(0);
auto len = lens->GetData<int32_t>(0);
HLCHECK(static_cast<size_t>(len) == data.size());
for (int i = 0; i < len; ++i) {
data[i] = input->GetData<int64_t>(idx + i);
}
ConstantBuilder cb(inst->GetParent()->GetParent());
auto c = cb.CreateConstant(inst->GetName(), dt, data.data());
return {orig_def, *c};
}
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(FPtoSIInst* inst) {
Def orig_def{inst, 0};
auto op0 = inst->GetOperand(0);
if (IsA<Constant>(op0)) {
auto src_ty = op0.GetType().GetDataType();
auto dst_ty = inst->GetResultType().GetDataType();
ConstantBuilder cb(inst->GetParent()->GetParent());
Constant* input = DynCast<Constant>(op0);
auto n = op0.GetType().GetTotalNumOfElements();
if (src_ty == DataType::FLOAT32 &&
(dst_ty == DataType::INT32 || dst_ty == DataType::INT64 ||
dst_ty == DataType::UINT32)) {
Constant* c = nullptr;
if (dst_ty == DataType::INT32) {
std::vector<int32_t> vals(n);
for (int64_t i = 0; i < n; ++i) {
vals[i] = input->GetData<float>(i);
}
c = cb.CreateConstant(inst->GetName(), inst->GetResultType(),
vals.data());
} else if (dst_ty == DataType::UINT32) {
std::vector<uint32_t> vals(n);
for (int64_t i = 0; i < n; ++i) {
vals[i] = input->GetData<float>(i);
}
c = cb.CreateConstant(inst->GetName(), inst->GetResultType(),
vals.data());
} else {
std::vector<int64_t> vals(n);
for (int64_t i = 0; i < n; ++i) {
vals[i] = input->GetData<float>(i);
}
c = cb.CreateConstant(inst->GetName(), inst->GetResultType(),
vals.data());
}
return {orig_def, *c};
}
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(SItoFPInst* inst) {
Def orig_def{inst, 0};
auto op0 = inst->GetOperand(0);
if (IsA<Instruction>(op0.GetOwner())) {
Instruction* reshape_inst = DynCast<Instruction>(op0.GetOwner());
if (reshape_inst->GetOpCode() == OpCode::RESHAPE &&
reshape_inst->GetNumberOfUses() == 1) {
auto op_reshape = reshape_inst->GetOperand(0);
if (IsA<Argument>(op_reshape.GetOwner())) {
Argument* arg = DynCast<Argument>(op_reshape.GetOwner());
if (arg->GetNumberOfUses() == 1 && op_reshape.GetType().IsValid()) {
arg->SetType(halo::Type{DataType::FLOAT32,
op_reshape.GetType().GetDimSizes()});
return {orig_def, *reshape_inst};
}
}
}
} else if (IsA<Argument>(op0.GetOwner()) && op0.GetType().IsValid() &&
DynCast<Argument>(op0.GetOwner())->GetNumberOfUses() == 1) {
Argument* arg = DynCast<Argument>(op0.GetOwner());
arg->SetType(halo::Type{DataType::FLOAT32, op0.GetType().GetDimSizes()});
return {orig_def, *arg};
} else if (IsA<Constant>(op0)) {
auto src_ty = op0.GetType().GetDataType();
Constant* input = DynCast<Constant>(op0);
auto n = op0.GetType().GetTotalNumOfElements();
if (inst->GetDataType() == DataType::FLOAT32 &&
(src_ty == DataType::INT32 || src_ty == DataType::INT64)) {
std::vector<float> vals(n);
for (int64_t i = 0; i < n; ++i) {
vals[i] = (src_ty == DataType::INT32) ? input->GetData<int32_t>(i)
: input->GetData<int64_t>(i);
}
ConstantBuilder cb(inst->GetParent()->GetParent());
auto c = cb.CreateConstant(inst->GetName(), inst->GetResultType(),
vals.data());
return {orig_def, *c};
}
}
return {orig_def, orig_def};
}
std::pair<Def, Def> InstSimplify::RunOnInstruction(OneHotInst* inst) {
Def orig_def{inst, 0};
// work around on cxx target when backend doens't support onehot.
if (!simplify_for_preprocess_) {
return {orig_def, orig_def};
}
auto on_value = inst->GetOperand(2);
auto off_value = inst->GetOperand(3);
const auto& dst_type = inst->GetResultsTypes()[0];
if (!IsA<Constant>(on_value.GetOwner()) ||
!IsA<Constant>(off_value.GetOwner()) || !dst_type.IsValid()) {
return {orig_def, orig_def};
}
auto op0 = inst->GetOperand(0);
if (IsA<Instruction>(op0.GetOwner())) {
Instruction* reshape_inst = DynCast<Instruction>(op0.GetOwner());
if (reshape_inst->GetOpCode() == OpCode::RESHAPE &&
reshape_inst->GetNumberOfUses() == 1) {
auto op_reshape = reshape_inst->GetOperand(0);
if (IsA<Argument>(op_reshape.GetOwner())) {
Argument* arg = DynCast<Argument>(op_reshape.GetOwner());
if (arg->GetNumberOfUses() == 1 && op_reshape.GetType().IsValid()) {
arg->SetType(halo::Type{on_value.GetType().GetDataType(),
dst_type.GetDimSizes()});
return {orig_def, *arg};
}
}
}
} else if (IsA<Argument>(op0.GetOwner()) && op0.GetType().IsValid() &&
DynCast<Argument>(op0.GetOwner())->GetNumberOfUses() == 1) {
Argument* arg = DynCast<Argument>(op0.GetOwner());
arg->SetType(
halo::Type{on_value.GetType().GetDataType(), dst_type.GetDimSizes()});
return {orig_def, *arg};
}
return {orig_def, orig_def};
}
bool InstSimplify::RunOnBasicBlock(BasicBlock* bb) {
bool changed = false;
for (auto& inst_t : *bb) {
Instruction* inst = inst_t.get();
if (inst->GetNumberOfUses() == 0) {
if (inst->GetOpCode() == OpCode::RETURN) {
RunOnInstruction(DynCast<ReturnInst>(inst));
}
continue;
}
std::pair<Def, Def> ret{Def{inst, 0}, Def{inst, 0}};
switch (inst->GetOpCode()) {
#define GET_INST_DOWNCAST_SWITCH_WITH_RETURN
#include "halo/lib/ir/instructions_info.def"
#undef GET_INST_DOWNCAST_SWITCH_WITH_RETURN
default: {
// skip extension instruction.
continue;
}
}
if (ret.first != ret.second) {
changed |= true;
if (ret.second.GetOwner() != nullptr) {
// Replace all uses
inst->ReplaceAllUsesWith(ret.first.GetIdx(), ret.second);
}
}
}
return changed;
}
} // end namespace halo
| 37.114492 | 80 | 0.604044 | xuhongyao |
e16fbd6bad4e3210e705d87fae229fa40a5a1b20 | 2,131 | hpp | C++ | include/agents.hpp | tomatenbrei/pomcpp | 55522748369bc167420f3ca5b0ecde314ca2fee3 | [
"MIT"
] | null | null | null | include/agents.hpp | tomatenbrei/pomcpp | 55522748369bc167420f3ca5b0ecde314ca2fee3 | [
"MIT"
] | 2 | 2020-06-30T12:01:51.000Z | 2021-05-14T13:57:48.000Z | include/agents.hpp | tomatenbrei/pomcpp | 55522748369bc167420f3ca5b0ecde314ca2fee3 | [
"MIT"
] | 2 | 2020-06-30T10:23:43.000Z | 2021-08-01T17:24:08.000Z | #ifndef RANDOM_AGENT_H
#define RANDOM_AGENT_H
#include <random>
#include "bboard.hpp"
#include "strategy.hpp"
namespace agents
{
/**
* Use this as an example to implement more sophisticated
* agents.
*
* @brief Randomly selects actions
*/
struct RandomAgent : bboard::Agent
{
std::mt19937_64 rng;
std::uniform_int_distribution<int> intDist;
RandomAgent();
bboard::Move act(const bboard::State* state) override;
};
/**
* @brief Randomly selects actions that are not laying bombs
*/
struct HarmlessAgent : bboard::Agent
{
std::mt19937_64 rng;
std::uniform_int_distribution<int> intDist;
HarmlessAgent();
bboard::Move act(const bboard::State* state) override;
};
/**
* @brief Selects Idle for every action
*/
struct LazyAgent : bboard::Agent
{
bboard::Move act(const bboard::State* state) override;
};
/**
* @brief Handcrafted agent by m2q
*/
struct SimpleAgent : bboard::Agent
{
std::mt19937_64 rng;
SimpleAgent();
SimpleAgent(long seed);
//////////////
// Specific //
//////////////
int danger = 0;
bboard::strategy::RMap r;
bboard::FixedQueue<bboard::Move, bboard::MOVE_COUNT> moveQueue;
// capacity of recent positions
static const int rpCapacity = 4;
bboard::FixedQueue<bboard::Position, rpCapacity> recentPositions;
virtual bboard::Move decide(const bboard::State* state);
bboard::Move act(const bboard::State* state) override;
void reset() override;
void PrintDetailedInfo();
};
/**
* @brief An improved version of SimpleAgent. Adds more randomization to get equal win rates and collects powerups.
* Also includes adjustments of parameters to (hopefully) result in better gameplay.
*/
struct SimpleUnbiasedAgent : SimpleAgent
{
std::array<int, 4> agentAxis;
std::array<bboard::Move, bboard::MOVE_COUNT> dirAxis;
std::array<int, bboard::BOARD_SIZE> boardAxisX;
std::array<int, bboard::BOARD_SIZE> boardAxisY;
SimpleUnbiasedAgent();
SimpleUnbiasedAgent(long seed);
bboard::Move decide(const bboard::State* state) override;
void reset() override;
};
}
#endif
| 20.892157 | 115 | 0.686063 | tomatenbrei |
e170671ba42c63be5c176a98927ed605da6525e8 | 3,914 | hpp | C++ | SimpleDB/src/core/sql/pragma.hpp | caivao/SimpleDB | ff90245c5ffc96ea84cf046596d690866c1c8cb6 | [
"MIT"
] | 1 | 2021-01-05T17:01:31.000Z | 2021-01-05T17:01:31.000Z | SimpleDB/src/core/sql/pragma.hpp | caivao/SimpleDB | ff90245c5ffc96ea84cf046596d690866c1c8cb6 | [
"MIT"
] | null | null | null | SimpleDB/src/core/sql/pragma.hpp | caivao/SimpleDB | ff90245c5ffc96ea84cf046596d690866c1c8cb6 | [
"MIT"
] | null | null | null | //
// pragma.hpp
// SimpleDB
//
// Created by lifeng on 2019/6/5.
// Copyright © 2019 feng. All rights reserved.
//
#ifndef pragma_hpp
#define pragma_hpp
#include "declare.hpp"
#include "describable.hpp"
namespace SDB {
class Pragma : public Describable {
public:
static const Pragma application_id;
static const Pragma auto_vacuum;
static const Pragma automatic_index;
static const Pragma busy_timeout;
static const Pragma cache_size;
static const Pragma cache_spill;
static const Pragma case_sensitive_like;
static const Pragma cell_size_check;
static const Pragma checkpoint_fullfsync;
static const Pragma cipher;
static const Pragma cipher_add_random;
static const Pragma cipher_default_kdf_iter;
static const Pragma cipher_default_page_size;
static const Pragma cipher_page_size;
static const Pragma cipher_default_use_hmac;
static const Pragma cipher_migrate;
static const Pragma cipher_profile;
static const Pragma cipher_provider;
static const Pragma cipher_provider_version;
static const Pragma cipher_use_hmac;
static const Pragma cipher_version;
static const Pragma collation_list;
static const Pragma compile_options;
static const Pragma count_changes;
static const Pragma data_store_directory;
static const Pragma data_version;
static const Pragma database_list;
static const Pragma default_cache_size;
static const Pragma defer_foreign_keys;
static const Pragma empty_result_callbacks;
static const Pragma encoding;
static const Pragma foreign_key_check;
static const Pragma foreign_key_list;
static const Pragma foreign_keys;
static const Pragma freelist_count;
static const Pragma full_column_names;
static const Pragma fullfsync;
static const Pragma ignore_check_constraints;
static const Pragma incremental_vacuum;
static const Pragma index_info;
static const Pragma index_list;
static const Pragma index_xinfo;
static const Pragma integrity_check;
static const Pragma journal_mode;
static const Pragma journal_size_limit;
static const Pragma key;
static const Pragma kdf_iter;
static const Pragma legacy_file_format;
static const Pragma locking_mode;
static const Pragma max_page_count;
static const Pragma mmap_size;
static const Pragma page_count;
static const Pragma page_size;
static const Pragma parser_trace;
static const Pragma query_only;
static const Pragma quick_check;
static const Pragma read_uncommitted;
static const Pragma recursive_triggers;
static const Pragma rekey;
static const Pragma reverse_unordered_selects;
static const Pragma schema_version;
static const Pragma secure_delete;
static const Pragma short_column_names;
static const Pragma shrink_memory;
static const Pragma soft_heap_limit;
static const Pragma stats;
static const Pragma synchronous;
static const Pragma table_info;
static const Pragma temp_store;
static const Pragma temp_store_directory;
static const Pragma threads;
static const Pragma user_version;
static const Pragma vdbe_addoptrace;
static const Pragma vdbe_debug;
static const Pragma vdbe_listing;
static const Pragma vdbe_trace;
static const Pragma wal_autocheckpoint;
static const Pragma wal_checkpoint;
static const Pragma writable_schema;
const std::string &name(void) const;
protected:
Pragma(const char *name);
};
}
#endif /* pragma_hpp */
| 36.240741 | 54 | 0.692897 | caivao |
e174846f52e77d02b4bfa32f795c1b02d57c8f8e | 9,465 | hpp | C++ | extlibs/include/Jopnal/Core/FileLoader.hpp | Jopnal/Jopmodel | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | [
"Zlib"
] | 2 | 2016-07-16T17:21:10.000Z | 2016-08-09T11:41:33.000Z | extlibs/include/Jopnal/Core/FileLoader.hpp | Jopnal/Jopmodel | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | [
"Zlib"
] | null | null | null | extlibs/include/Jopnal/Core/FileLoader.hpp | Jopnal/Jopmodel | cfd50b9fd24eaf63497bf5bed883f0b831d9ad65 | [
"Zlib"
] | null | null | null | // Jopnal Engine C++ Library
// Copyright (c) 2016 Team Jopnal
//
// 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 acknowledgement 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 GP_FILELOADER_HPP
#define GP_FILELOADER_HPP
// Headers
#include <Jopnal/Header.hpp>
#include <Jopnal/Core/Subsystem.hpp>
#include <string>
#include <vector>
//////////////////////////////////////////////
struct PHYSFS_File;
namespace Assimp
{
class Importer;
}
namespace jop
{
class JOP_API FileSystemInitializer final : public Subsystem
{
private:
JOP_DISALLOW_COPY_MOVE(FileSystemInitializer);
friend class ModelLoader;
static Assimp::Importer& getImporter();
public:
FileSystemInitializer(const char* arg);
~FileSystemInitializer();
};
class JOP_API FileLoader
{
private:
JOP_DISALLOW_COPY(FileLoader);
public:
/// Base directory for writing files
///
enum class Directory
{
Executable, ///< Executable directory
Resource, ///< Resource folder
User ///< User folder
};
public:
/// \brief Default constructor
///
/// Doesn't initialize any file handles.
///
FileLoader();
/// \brief Overloaded constructor
///
/// This will open the file for writing if found
///
/// \param path Path to file to open
///
/// \see isValid
///
explicit FileLoader(const std::string& path);
/// \brief Overloaded constructor
///
/// This will open the file for writing if found.
///
/// \param dir Base write directory
/// \param path Path to file to open
/// \param append Append to the file. False to clear the file before writing
///
/// \see isValid
///
FileLoader(const Directory dir, const std::string& path, const bool append);
/// \brief Move constructor
///
FileLoader(FileLoader&& other);
/// \brief Move assignment operator
///
/// \return Reference to self
///
FileLoader& operator =(FileLoader&& other);
/// \brief Destructor
///
/// Will close the file handle if open.
///
~FileLoader();
/// \brief Open a file for reading
///
/// \param path Path to the file
///
/// \return True if opened successfully
///
bool open(const std::string& path);
/// \brief Open a file for writing
///
/// \copydetails FileLoader(const Directory, const std::string&, const bool)
///
/// \return True if opened successfully
///
bool open(const Directory dir, const std::string& path, const bool append);
/// \brief Flush the file handle if open
///
void flush();
/// \brief Close the file handle if open
///
/// When writing, calling this means saving the file.
///
void close();
/// \brief Check if a file handle exists
///
/// \return True if a valid file handle exists
///
bool isValid() const;
/// \brief Read data
///
/// \param data Pointer to a pre-allocated data buffer
/// \param size Amount of data to read
///
/// \return Amount of data read in bytes
///
/// \see getSize
///
int64 read(void* data, const uint64 size);
/// \brief Write data
///
/// \param data Data to write
/// \param size Amount of data to write in bytes
///
/// \return Amount of data written in bytes
///
int64 write(const void* data, const uint64 size);
/// \brief Move the cursor to the given position
///
/// \param position The cursor position to set
///
/// \return True if successful
///
bool seek(const uint64 position);
/// \brief Get the current position of the cursor
///
/// \return Current position of the file read/write cursor
///
int64 tell();
/// \brief Get the size of the opened file
///
/// \return Size of the file
///
int64 getSize();
/// \copydoc isValid
///
operator bool() const;
/// \brief Check if a file exists
///
/// \param path Path to the file to check
///
/// \return True if the file exists
///
static bool fileExists(const std::string& path);
/// \brief Enumerate all files within a directory
///
/// \param path Path to a directory
/// \param list Reference to a list to fill with the file paths found
///
/// \see listFilesRecursive
///
static void listFiles(const std::string& path, std::vector<std::string>& list);
/// \brief Enumerate all files within a directory recursively
///
/// \param path Path to a directory
/// \param list Reference to a list to fill with the file paths found
///
/// \see listFiles
///
static void listFilesRecursive(const std::string& path, std::vector<std::string>& list);
/// \brief Delete a file
///
/// \param file Path to the file
///
/// \return True if file was deleted
///
static bool deleteFile(const std::string& file);
/// \brief Read a text file
///
/// \param path Path to the file to read
/// \param file Reference to a string to fill with the data
///
/// \return True if successful
///
static bool readTextfile(const std::string& path, std::string& file);
/// \brief Read a binary file
///
/// \param path Path to the file to read
/// \param buffer Reference to a buffer to fill with the data
///
/// \return True if successful
///
static bool readBinaryfile(const std::string& path, std::vector<uint8>& buffer);
/// \brief Write a text file
///
/// \param dir The base write directory
/// \param path The file path
/// \param text The text to write
/// \param append Append to file?
///
/// \return True if successful
///
static bool writeTextfile(const Directory dir, const std::string& path, const std::string& text, const bool append = false);
/// \brief Write a binary file
///
/// \param dir The base write directory
/// \param path The file path
/// \param data The binary data to write
/// \param bytes amount of bytes to write
/// \param append Append to file?
///
/// \return True if successful
///
static bool writeBinaryfile(const Directory dir, const std::string& path, const void* data, const std::size_t bytes, const bool append = false);
/// \brief Create a directory
///
/// If the directory already exists, this has no effect.
///
/// \param path The directory to create
///
/// \return True if successful
///
static bool makeDirectory(const std::string& path);
/// \brief Get a base directory as string
///
/// \param dir The base directory
///
/// \return Internal reference to the directory string
///
static const std::string& getDirectory(const Directory dir);
/// \brief Get the OS-specific directory separator
///
/// \return The directory separator
///
static char getDirectorySeparator();
/// \brief Read a resource file
///
/// This is mostly used internally.
///
/// \param id Identifier of the resource
/// \param buffer The data buffer
///
/// \return True if successful
///
static bool readResource(const int id, std::vector<uint8>& buffer);
/// \brief Enable/disable file system error checks
///
/// \param enable True to enable
///
static void enableErrorChecks(const bool enable);
/// \brief Check if file system error checks are enabled
///
/// \return True if enabled
///
static bool errorChecksEnabled();
private:
PHYSFS_File* m_file; ///< File handle
};
}
#endif | 28.856707 | 152 | 0.55383 | Jopnal |
e174bb27f06f5c3215bc0dac6b91b42a1b116872 | 7,498 | cpp | C++ | components/protocols/onewire/onewire.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | 2 | 2021-07-19T12:03:39.000Z | 2021-07-22T18:37:45.000Z | components/protocols/onewire/onewire.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | null | null | null | components/protocols/onewire/onewire.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | 1 | 2021-07-08T09:07:10.000Z | 2021-07-08T09:07:10.000Z | #include "onewire.h"
#include "hardware_defs.h"
OneWire::OneWire(GPIO_Basic *gpio){
this->gpio = gpio;
reset_search();
}
// Perform the onewire reset function. We will wait up to 250uS for
// the bus to come high, if it doesn't then it is broken or shorted
// and we return a 0;
//
// Returns 1 if a device asserted a presence pulse, 0 otherwise.
//
uint8_t OneWire::reset(void){
uint8_t r;
uint8_t retries = 125;
gpio->mode(GPIO_MODE_INPUT);
// wait until the wire is high... just in case
do {
if (--retries == 0) return 0;
delay_us(2);
} while ( !gpio->read());
disable_interrupts();
//Invertida as linhas abaixo
gpio->mode(GPIO_MODE_OUTPUT);
gpio->write(0);
enable_interrupts();
delay_us(480);
disable_interrupts();
gpio->mode(GPIO_MODE_INPUT);
delay_us(70);
r = !gpio->read();
enable_interrupts();
delay_us(410);
return r;
}
//
// Write a bit. Port and bit is used to cut lookup time and provide
// more certain timing.
//
void OneWire::write_bit(uint8_t v)
{
if (v & 1) {
disable_interrupts();
gpio->mode(GPIO_MODE_OUTPUT);
gpio->write(0);
delay_us(10);
gpio->write(1);
enable_interrupts();
delay_us(55);
} else {
disable_interrupts();
gpio->mode(GPIO_MODE_OUTPUT);
gpio->write(0);
delay_us(65);
gpio->write(1);
enable_interrupts();
delay_us(5);
}
}
//
// Read a bit. Port and bit is used to cut lookup time and provide
// more certain timing.
//
uint8_t OneWire::read_bit(void)
{
uint8_t r;
disable_interrupts();
gpio->mode(GPIO_MODE_OUTPUT);
gpio->write(0);
delay_us(3);
gpio->mode(GPIO_MODE_INPUT);
delay_us(10);
r = gpio->read();
enable_interrupts();
delay_us(53);
return r;
}
//
// Write a byte. The writing code uses the active drivers to raise the
// pin high, if you need power after the write (e.g. DS18S20 in
// parasite power mode) then set 'power' to 1, otherwise the pin will
// go tri-state at the end of the write to avoid heating in a short or
// other mishap.
//
void OneWire::write(uint8_t v, uint8_t power /* = 0 */) {
uint8_t bitMask;
for (bitMask = 0x01; bitMask; bitMask <<= 1) {
write_bit( (bitMask & v)?1:0);
}
if ( !power) {
disable_interrupts();
gpio->mode(GPIO_MODE_INPUT);
gpio->write(0);
enable_interrupts();
}
}
void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) {
for (uint16_t i = 0 ; i < count ; i++)
write(buf[i]);
if (!power) {
disable_interrupts();
gpio->mode(GPIO_MODE_INPUT);
gpio->write(0);
enable_interrupts();
}
}
//
// Read a byte
//
uint8_t OneWire::read() {
uint8_t bitMask;
uint8_t r = 0;
for (bitMask = 0x01; bitMask; bitMask <<= 1) {
if ( OneWire::read_bit()) r |= bitMask;
}
return r;
}
void OneWire::read_bytes(uint8_t *buf, uint16_t count) {
for (uint16_t i = 0 ; i < count ; i++)
buf[i] = read();
}
//
// Do a ROM select
//
void OneWire::select(const uint8_t rom[8]){
uint8_t i;
write(MATCH_ROM); // Choose ROM
for (i = 0; i < 8; i++) write(rom[i]);
}
//
// Do a ROM skip
//
void OneWire::skip(){
write(SKIP_ROM); // Skip ROM
}
void OneWire::depower(){
gpio->mode(GPIO_MODE_INPUT);
}
//
// You need to use this function to start a search again from the beginning.
// You do not need to do it for the first search, though you could.
//
void OneWire::reset_search()
{
// reset the search state
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
for(int i = 7; ; i--) {
ROM_NO[i] = 0;
if ( i == 0) break;
}
}
// Setup the search to find the device type 'family_code' on the next call
// to search(*newAddr) if it is present.
//
void OneWire::target_search(uint8_t family_code){
// set the search state to find SearchFamily type devices
ROM_NO[0] = family_code;
for (uint8_t i = 1; i < 8; i++)
ROM_NO[i] = 0;
LastDiscrepancy = 64;
LastFamilyDiscrepancy = 0;
LastDeviceFlag = FALSE;
}
//
// Perform a search. If this function returns a '1' then it has
// enumerated the next device and you may retrieve the ROM from the
// OneWire::address variable. If there are no devices, no further
// devices, or something horrible happens in the middle of the
// enumeration then a 0 is returned. If a new device is found then
// its address is copied to newAddr. Use OneWire::reset_search() to
// start over.
//
// --- Replaced by the one from the Dallas Semiconductor web site ---
//--------------------------------------------------------------------------
// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing
// search state.
// Return TRUE : device found, ROM number in ROM_NO buffer
// FALSE : device not found, end of search
//
uint8_t OneWire::search(uint8_t *newAddr)
{
uint8_t id_bit_number;
uint8_t last_zero, rom_byte_number, search_result;
uint8_t id_bit, cmp_id_bit;
unsigned char rom_byte_mask, search_direction;
// initialize for search
id_bit_number = 1;
last_zero = 0;
rom_byte_number = 0;
rom_byte_mask = 1;
search_result = 0;
// if the last call was not the last one
if (!LastDeviceFlag){
// 1-Wire reset
if (!reset()){
// reset the search
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
return FALSE;
}
// issue the search command
write(SEARCH_ROM);
// loop to do the search
do{
// read a bit and its complement
id_bit = read_bit();
cmp_id_bit = read_bit();
// check for no devices on 1-wire
if ((id_bit == 1) && (cmp_id_bit == 1))
break;
else{
// all devices coupled have 0 or 1
if (id_bit != cmp_id_bit)
search_direction = id_bit; // bit write value for search
else{
// if this discrepancy if before the Last Discrepancy
// on a previous next then pick the same as last time
if (id_bit_number < LastDiscrepancy)
search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0);
else
// if equal to last pick 1, if not then pick 0
search_direction = (id_bit_number == LastDiscrepancy);
// if 0 was picked then record its position in LastZero
if (search_direction == 0){
last_zero = id_bit_number;
// check for Last discrepancy in family
if (last_zero < 9)
LastFamilyDiscrepancy = last_zero;
}
}
// set or clear the bit in the ROM byte rom_byte_number
// with mask rom_byte_mask
if (search_direction == 1)
ROM_NO[rom_byte_number] |= rom_byte_mask;
else
ROM_NO[rom_byte_number] &= ~rom_byte_mask;
// serial number search direction write bit
write_bit(search_direction);
// increment the byte counter id_bit_number
// and shift the mask rom_byte_mask
id_bit_number++;
rom_byte_mask <<= 1;
// if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask
if (rom_byte_mask == 0){
rom_byte_number++;
rom_byte_mask = 1;
}
}
}while(rom_byte_number < 8); // loop until through all ROM bytes 0-7
// if the search was successful then
if (!(id_bit_number < 65)){
// search successful so set LastDiscrepancy,LastDeviceFlag,search_result
LastDiscrepancy = last_zero;
// check for last device
if (LastDiscrepancy == 0)
LastDeviceFlag = TRUE;
search_result = TRUE;
}
}
// if no device found then reset counters so next 'search' will be like a first
if (!search_result || !ROM_NO[0]){
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
search_result = FALSE;
}
for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i];
return search_result;
}
| 23.803175 | 85 | 0.662443 | thmalmeida |
e17894aa7d464a7cf6880a7f155981729bdcfb8b | 34,828 | hpp | C++ | src/axom/mint/mesh/Mesh.hpp | raineyeh/axom | 57a6ef7ab50e113e4cf4b639657eb84ff10789c0 | [
"BSD-3-Clause"
] | 86 | 2019-04-12T20:39:37.000Z | 2022-01-28T17:06:08.000Z | src/axom/mint/mesh/Mesh.hpp | raineyeh/axom | 57a6ef7ab50e113e4cf4b639657eb84ff10789c0 | [
"BSD-3-Clause"
] | 597 | 2019-04-25T22:36:16.000Z | 2022-03-31T20:21:54.000Z | src/axom/mint/mesh/Mesh.hpp | raineyeh/axom | 57a6ef7ab50e113e4cf4b639657eb84ff10789c0 | [
"BSD-3-Clause"
] | 21 | 2019-06-27T15:53:08.000Z | 2021-09-30T20:17:41.000Z | // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
// other Axom Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
#ifndef MINT_MESH_HPP_
#define MINT_MESH_HPP_
#include "axom/core/Macros.hpp" // for Axom macros
#include "axom/mint/mesh/CellTypes.hpp" // for CellType enum
#include "axom/mint/config.hpp" // for mint compile-time type
#include "axom/mint/mesh/FieldAssociation.hpp" // for FieldAssociation enum
#include "axom/mint/mesh/FieldData.hpp" // for mint::FieldData
#include "axom/mint/mesh/MeshCoordinates.hpp" // for mint::MeshCoordinates
#include "axom/mint/mesh/MeshTypes.hpp" // for MeshType enum
#include "axom/slic/interface/slic.hpp" // for SLIC macros
namespace axom
{
/* Forward declarations */
#ifdef AXOM_MINT_USE_SIDRE
namespace sidre
{
class Group;
}
#endif
namespace mint
{
/* Forward declarations */
class Field;
class Mesh;
/// \name Free Methods
/// @{
#ifdef AXOM_MINT_USE_SIDRE
/*!
* \brief Creates a mesh instance from the given Sidre group.
*
* \param [in] group pointer to the root group of the mesh in Sidre.
* \param [in] topo topology associated with the requested mesh (optional)
*
* \return m pointer to a mesh instance corresponding to the specified group.
*
* \note If a topology name is not provided, the implementation will construct
* a mesh based on the 1st topology group under the parent "topologies"
* group.
*
* \note Ownership of the resulting mesh object is passed to the caller.
*
* \note When using Mint with Sidre, Sidre maintains ownership of the data.
* Although the data can be modified via calls to Mint, groups and views
* cannot be deleted. The data remains persistent in Sidre once the mesh
* object goes out-of-scope.
*
* \pre group != nullptr
* \pre blueprint::isValidRootGroup( group ) == true
* \post m != nullptr
*/
Mesh* getMesh(sidre::Group* group, const std::string& topo = "");
#endif
/// @}
/*!
* \class Mesh
*
* \brief Base class that defines the core API common to all Mesh types.
*
* A Mesh, \f$ \mathcal{M}(\Omega) \f$, provides an approximation of a physical
* domain, \f$ \Omega \in \mathcal{R}^d \f$, where \f$ d \in [1,3] \f$ . The
* Mesh is essentially a discrete representation of a problem and is used to
* facilitate the analysis, e.g., FEA, CFD, etc. The solution domain is
* approximated by dividing it into a finite number of <em> nodes </em> and
* <em> cells </em> at which the variables of the underlying mathematical model
* (i.e., a PDE) are then computed via a numerical method, such as,
* Finite Difference (FD), Finite Volume (FV) or Finite Element (FE), chief
* among them.
*
* There are a variety of mesh types. Mint supports the following mesh types:
*
* * <b> Structured (Curvilinear) Mesh </b> <br />
*
* A <em> structured mesh </em> divides the solution domain according to a
* logical grid where each node/cell of the mesh can be uniquely identified
* by a corresponding logical ijk-index. The nodes of the mesh are found at
* the intersection of the grid lines, but, are explicitly defined via a
* mapping onto the physical Cartesian coordinate system of the domain. For
* this reason, these types of meshes are also called <em> mapped </em> or
* <em> body-fitted </em> meshes.
*
* However, the mesh topology (e.g., connectivity, neighbor information) is
* implicitly defined by the logical indexing scheme. For example, a
* structured mesh is composed of <em> quadrilateral </em> cells in 2-D and
* <em> hexahedron </em> cells in 3-D. Given the logical index of a cell
* one can compute the node indices of the cell and neighbor information by
* performing simple shift operations on the associated index.
*
* * <b> Rectilinear Mesh </b> <br />
*
* A <em> rectilinear mesh </em>, also known as a product mesh, is similar
* to the <em> structured mesh </em> in that it is also defined according to
* a logical indexing scheme and has implicit topology.
*
* However, the nodes and cells on a <em> rectilinear mesh </em> are arranged
* on a regular lattice that is axis-aligned with the Cartesian coordinate
* system. In contrast to the general <em> structured mesh </em>, the
* <em> rectilinear mesh </em> does not explicitly define **all** the nodes
* of the mesh. Instead, the nodes are only defined along each coordinate
* axis and may have variable spacing between nodes. Given a logical index,
* the corresponding physical position of a node can be evaluated by taking
* the cartesian product of the corresponding coordinate along each
* coordinate axis.
*
* * <b> Uniform Mesh </b> <br />
*
* A <em> uniform mesh </em>, also called a regular mesh, subdivides the
* domain in cells that have uniform spacing across each coordinate axis.
* Similar to the <em> structured mesh </em>, a <em> uniform mesh </em>
* adheres to the same logical indexing scheme and implicit topology
* representation. Moreover, The nodes and cells of a <em> uniform </em> mesh
* are arranged on a regular lattice as with the <em> rectilinear mesh </em>.
* However, both topology and geometry is implicitly defined on a
* <em> uniform mesh </em>. The geometry is solely defined by an origin,
* \f$ \hat{x_0} \f$ and spacing, \f$ \hat{h} \f$, along each axis. The
* coordinates of a node can be evaluated algebraically by the following:
* \f$ \hat{p} = \hat{x_0} + \hat{i} \times \hat{h} \f$, where \f$\hat{i}\f$
* is the logical ijk-index of the corresponding node.
*
* * <b> Unstructured Mesh </b> <br />
*
* An <em> unstructured mesh </em> stores both node and topology information
* explicitly. This allows the flexibility of discretizing the solution
* domain using a variety of cell types not just quadrilateral (in 2D) or
* hexahedral (in 3D) cells. Due to this added flexibility, the use of
* <em> unstructured meshes </em> is more common when dealing with complex
* geometries. However, <em> unstructured meshes </em> require additional
* storage and generally incur some performance penalty to store, create and
* access mesh topology information respectively.
*
* Mint classifies <em> unstructured meshes </em> in two basic types based on
* the underlying mesh topology:
*
* * <b> Single Cell Topology </b>
*
* In this case, the <em> unstructured mesh </em> consists of a single cell
* type, e.g., a quad or triangle mesh in 2D, or, a hex or tet mesh in 3D.
* In this case the underlying implementation is optimized for the
* specified cell type (specified in the constructor).
*
* * <b> Mixed Cell Topology </b>
*
* When <em> mixed cell topology </em> is specified, the <em> unstructured
* mesh </em> can be composed of any of the supported cell types, e.g.,
* a mesh consisting of both quads and triangles. This mode incurs
* additional overhead for storage and access to mesh topology information,
* since it requires indirection.
*
* The list of supported cell types for an <em> unstructured mesh </em> is
* available in CellTypes.hpp
*
* * <b> Particle Mesh </b> <br />
*
* A <em> particle mesh </em> discretizes the solution domain using
* a set of discrete particle elements which correspond to the the nodes
* of the mesh. There is no ordering imposed on the particles and the
* coordinates of the particles are explicitly defined. A particle mesh
* has no connectivity information connecting the particles, which is why
* in literature methods using a particle discretization are also referred
* to as <em> meshless </em> or <em> meshfree </em> methods.
*
* The Mesh class provides the means to create, access and remove fields on
* a mesh given the field name and its association. The field association
* designates the corresponding mesh entity at which the field is stored, e.g.
* whether the field is stored at the nodes or cell centers. A Field may be a
* scalar quantity, e.g., pressure, or a vector field, such as, velocity.
*
* \warning When using Sidre, field names have to be unique. For example, if
* there exists a "pressure" node-centered field, there cannot be a
* corresponding cell-centered field.
*
* \note Mesh is a base class and cannot be instantiated directly
*
* \note Typically, the computational mesh can be defined across one or more
* <em> blocks </em>, e.g., for multi-block problems, where each block is
* subsequently decomposed into several <em> partitions </em> for parallel
* computation. A Mesh instance represents a <em> single </em> partition for
* a given block.
*
* \see mint::UnstructuredMesh
* \see mint::StructuredMesh
* \see mint::CurvilinearMesh
* \see mint::RectilinearMesh
* \see mint::UniformMesh
* \see mint::Field
* \see mint::FieldData
* \see mint::MeshTypes
*/
class Mesh
{
public:
/*!
* \brief Default constructor. Disabled.
*/
Mesh() = delete;
/// \name Virtual methods
/// @{
/*!
* \brief Destructor.
*/
virtual ~Mesh();
/// \name Cells
/// @{
/*!
* \brief Returns the number of cells in this mesh instance.
* \return N the number of cells
* \post N >= 0
*/
virtual IndexType getNumberOfCells() const = 0;
/*!
* \brief Returns the capacity for number of cell in this mesh instance.
* \return N the cell capacity
* \post N >= 0
*/
virtual IndexType getCellCapacity() const { return getNumberOfCells(); }
/*!
* \brief Return the type of the given cell.
*
* \param [in] cellID the ID of the cell in question, this parameter is
* ignored if hasMixedCellTypes() == false.
*
* \pre 0 <= cellID < getNumberOfCells()
*/
virtual CellType getCellType(IndexType cellID = 0) const = 0;
/*!
* \brief Return the number of nodes associated with the given cell.
*
* \param [in] cellID the ID of the cell in question, this parameter is
* ignored unless hasMixedCellTypes() == true.
*
* \pre 0 <= cellID < getNumberOfCells()
*/
virtual IndexType getNumberOfCellNodes(IndexType cellID = 0) const = 0;
/*!
* \brief Copy the connectivity of the given cell into the provided buffer.
* The buffer must be of length at least getNumberOfCellNodes( cellID ).
*
* \param [in] cellID the ID of the cell in question.
* \param [out] nodes the buffer into which the connectivity is copied, must
* be of length at least getNumberOfCellNodes( cellID ).
*
* \return The number of nodes for the given cell.
*
* \pre nodes != nullptr
* \pre 0 <= cellID < getNumberOfCells()
*/
virtual IndexType getCellNodeIDs(IndexType AXOM_NOT_USED(cellID),
IndexType* AXOM_NOT_USED(nodes)) const = 0;
/*!
* \brief Return the number of faces associated with the given cell.
*
* \param [in] cellID the ID of the cell in question.
*/
virtual IndexType getNumberOfCellFaces(
IndexType AXOM_NOT_USED(cellID) = 0) const = 0;
/*!
* \brief Populates the given buffer with the IDs of the faces of the given
* cell and returns the number of faces.
*
* \param [in] cellID the ID of the cellID in question.
* \param [out] faces buffer to populate with the face IDs. Must be of length
* at least getNumberOfCellFaces( cellID ).
*
* \pre faces != nullptr
* \pre 0 <= cellID < getNumberOfCells()
*/
virtual IndexType getCellFaceIDs(IndexType AXOM_NOT_USED(cellID),
IndexType* AXOM_NOT_USED(faces)) const = 0;
/// @}
/// \name Nodes
/// @{
/*!
* \brief Returns the number of nodes in this mesh instance.
* \return N the number of nodes
* \post N >= 0
*/
virtual IndexType getNumberOfNodes() const = 0;
/*!
* \brief Returns the capacity for number of nodes in this mesh instance.
* \return N the node capacity
* \post N >= 0
*/
virtual IndexType getNodeCapacity() const { return getNumberOfNodes(); }
/*!
* \brief Copy the coordinates of the given node into the provided buffer.
*
* \param [in] nodeID the ID of the node in question.
* \param [in] coords the buffer to copy the coordinates into, of length at
* least getDimension().
*
* \pre 0 <= nodeID < getNumberOfNodes()
* \pre coords != nullptr
*/
virtual void getNode(IndexType nodeID, double* node) const = 0;
/*!
* \brief Returns pointer to the requested mesh coordinate buffer.
*
* \param [in] dim the dimension of the requested coordinate buffer
* \return ptr pointer to the coordinate buffer.
*
* \note if hasExplicitCoordinates() == true then the length of the returned
* buffer is getNumberOfNodes(). Otherwise the UniformMesh returns
* nullptr and the RectilinearMesh returns a pointer to the associated
* dimension scale which is of length
* static_cast< RectilinearMesh* >( this )->getNodeResolution().
*
* \pre dim >= 0 && dim < dimension()
* \pre dim == X_COORDINATE || dim == Y_COORDINATE || dim == Z_COORDINATE
*/
/// @{
virtual double* getCoordinateArray(int dim) = 0;
virtual const double* getCoordinateArray(int dim) const = 0;
/// @}
/// @}
/// \name Faces
/// @{
/*!
* \brief Returns the number of faces in this mesh instance.
* \return N the number of faces
* \post N >= 0
*/
virtual IndexType getNumberOfFaces() const = 0;
/*!
* \brief Returns the capacity for number of faces in this mesh instance.
* \return N the face capacity
* \post N >= 0
*/
virtual IndexType getFaceCapacity() const { return getNumberOfFaces(); }
/*!
* \brief Return the type of the given face.
*
* \param [in] faceID the ID of the face in question.
*/
virtual CellType getFaceType(IndexType AXOM_NOT_USED(faceID)) const = 0;
/*!
* \brief Return the number of nodes associated with the given face.
*
* \param [in] faceID the ID of the face in question.
*/
virtual IndexType getNumberOfFaceNodes(IndexType AXOM_NOT_USED(faceID)) const = 0;
/*!
* \brief Copy the IDs of the nodes that compose the given face into the
* provided buffer.
*
* \param [in] faceID the ID of the face in question.
* \param [out] nodes the buffer into which the node IDs are copied, must
* be of length at least getNumberOfFaceNodes().
*
* \return The number of nodes for the given face.
*
* \pre nodes != nullptr
* \pre 0 <= faceID < getNumberOfFaces()
*/
virtual IndexType getFaceNodeIDs(IndexType AXOM_NOT_USED(faceID),
IndexType* AXOM_NOT_USED(nodes)) const = 0;
/*!
* \brief Copy the IDs of the cells adjacent to the given face into the
* provided indices.
*
* \param [in] faceID the ID of the face in question.
* \param [out] cellIDOne the ID of the first cell.
* \param [out] cellIDTwo the ID of the second cell.
*
* \note If no cell exists (the face is external) then the ID will be set to
* -1.
*
* \pre 0 <= faceID < getNumberOfFaces()
*/
virtual void getFaceCellIDs(IndexType AXOM_NOT_USED(faceID),
IndexType& AXOM_NOT_USED(cellIDOne),
IndexType& AXOM_NOT_USED(cellIDTwo)) const = 0;
/// @}
/// \name Edges
/// @{
/*!
* \brief Returns the number of edges in this mesh instance.
* \return N the number of edges
* \post N >= 0
*/
virtual IndexType getNumberOfEdges() const = 0;
/*!
* \brief Returns the capacity for number of edges in this mesh instance.
* \return N the edge capacity
* \post N >= 0
*/
virtual IndexType getEdgeCapacity() const { return getNumberOfEdges(); }
/*!
* \brief Returns true iff the mesh was constructed with external arrays.
* \return status true if the mesh points to external buffers, else, false.
*/
virtual bool isExternal() const = 0;
/// @}
/// @}
/// \name Mesh Attribute get/set Methods
/// @{
/*!
* \brief Returns the dimension for this mesh instance.
* \return ndims the dimension of this mesh instance.
* \post ndims >= 1 && ndims <= 3
*/
inline int getDimension() const { return m_ndims; }
/*!
* \brief Returns the ID of this mesh instance.
* \return Id the ID of the mesh.
*/
inline int getBlockId() const { return m_block_idx; }
/*!
* \brief set the block ID of this mesh instance.
*
* \param [in] ID the new block ID.
*
* \post getBlockId() == ID
*/
void setBlockId(int ID);
/*!
* \brief Returns the partition ID of this mesh instance.
* \return partitionId the partition ID of the mesh.
*/
inline int getPartitionId() const { return m_part_idx; }
/*!
* \brief set the partition ID of this mesh instance.
*
* \param [in] ID the new partition ID.
*
* \post getPartitionId() == ID
*/
void setPartitionId(int ID);
/*!
* \brief Returns the mesh type of this mesh instance.
* \return meshType the mesh type
* \see MeshType
*/
inline int getMeshType() const { return m_type; }
/*!
* \brief Checks if this mesh instance has explicit coordinates.
* \return status true iff the mesh defines coordinates explicitly.
*/
inline bool hasExplicitCoordinates() const { return m_explicit_coords; }
/*!
* \brief Checks if this mesh instance has explicit connectivity.
* \return status true iff the mesh defines cell connectivity explicitly.
*/
inline bool hasExplicitConnectivity() const
{
return m_explicit_connectivity;
}
/*!
* \brief Checks if the mesh has mixed cell types, e.g., consisting of both
* triangle and quad elements or hex,pyramid,prisms and tets in 3-D.
* \return status true iff the mesh has mixed cell types.
*/
inline bool hasMixedCellTypes() const { return m_has_mixed_topology; }
/*!
* \brief Returns true if the mesh type is structured.
* \return status true if the mesh type is structured, else, false.
*/
inline bool isStructured() const
{
return ((m_type == STRUCTURED_CURVILINEAR_MESH) ||
(m_type == STRUCTURED_RECTILINEAR_MESH) ||
(m_type == STRUCTURED_UNIFORM_MESH));
}
/*!
* \brief Returns true if the mesh type is unstructured.
* \return status true if the mesh type is unstructured, else, false.
*/
inline bool isUnstructured() const { return (m_type == UNSTRUCTURED_MESH); }
/*!
* \brief Checks if this Mesh instance is associated with a Sidre Group.
* \return status true if the Mesh is associated with a group in a Sidre
* hierarchy, else, false.
*/
inline bool hasSidreGroup() const;
#ifdef AXOM_MINT_USE_SIDRE
/*!
* \brief Return a pointer to the sidre::Group associated with this Mesh
* instance or nullptr if none exists.
*/
inline sidre::Group* getSidreGroup() { return m_group; }
/*!
* \brief Return the name of the topology associated with this Mesh instance,
* the return value is undefined if the mesh is not in sidre.
*/
inline const std::string& getTopologyName() const { return m_topology; }
/*!
* \brief Return the name of the coordset associated with this Mesh instance,
* the return value is undefined if the mesh is not in sidre.
*/
inline const std::string& getCoordsetName() const { return m_coordset; }
#endif
/// @}
/// \name Methods to Create, Access & Remove Fields from a Mesh
/// @{
/*!
* \brief Returns const pointer to the FieldData instance with the specified
* mesh field association, e.g., NODE_CENTERED, CELL_CENTERED, etc.
*
* \param [in] association the specified mesh field association
* \return fd pointer to the requested FieldData instance
*
* \pre association >= 0 && association < NUM_FIELD_ASSOCIATION
* \post fd != nullptr
*
* \see FieldAssociation
* \see FieldData
*/
inline const FieldData* getFieldData(int association) const;
/*!
* \brief Check if a field with the given name and association exists.
*
* \param [in] name the name of the field in query.
* \param [in] association the field association (optional)
*
* \return status true if the field exists, else, false.
*
* \note If an association is not explicitly specified, the code will check
* if a field by the given name exists in any available centeering.
*
* \pre name.empty()==false
* \pre association >= 0 && association < NUM_FIELD_ASSOCIATION
*
* \see FieldAssociation
*/
inline bool hasField(const std::string& name,
int association = ANY_CENTERING) const;
/*!
* \brief Creates a new field with the given name and specified mesh field
* association, e.g., NODE_CENTERED, CELL_CENTERED, etc.
*
* \param [in] name the name of the new field.
* \param [in] association the mesh field association.
* \param [in] num_components number of components of the field (optional).
* \param [in] storeInSidre indicates whether to store the field in the
* corresponding Sidre group (optional).
* \param [in] capacity
*
* \return ptr raw pointer to the data buffer of the new field.
*
* \note This method throws an error and aborts if any of the pre-conditions
* is not satisfied.
*
* \pre name.empty() == false
* \pre hasField( name ) == false
* \pre association >= 0 && association < NUM_FIELD_ASSOCIATION
*
* \post ptr != nullptr
* \post hasField( name ) == true
*
* \see FieldAssociation
*/
template <typename T>
inline T* createField(const std::string& name,
int association,
IndexType num_components = 1,
bool storeInSidre = true);
/*!
* \brief Creates a new field from an external buffer that has the given name
* and specified mesh field association, e.g., NODE_CENTERED, CELL_CENTERED,
* etc.
*
* \param [in] name the name of the new field.
* \param [in] association the mesh field association.
* \param [in] data pointer to the external data buffer.
* \param [in] num_components number of components of the field (optional).
*
* \return ptr raw pointer to the data buffer of the new field.
*
* \note This method throws an error and aborts if any of the pre-conditions
* is not satisfied.
*
* \pre name.empty() == false
* \pre hasField( name ) == false
* \pre data != nullptr
* \pre association >= 0 && association < NUM_FIELD_ASSOCIATION
*
* \post ptr != nullptr
* \post ptr == data
* \post hasField( name ) == true
*
* \see FieldAssociation
*/
template <typename T>
inline T* createField(const std::string& name,
int association,
T* data,
IndexType num_components = 1,
IndexType capacity = USE_DEFAULT);
/*!
* \brief Removes the field with the given name and specified association.
*
* \param [in] name the name of the field to remove.
* \param [in] association the mesh field association.
*
* \return status true if the field is removed successfully, else, false.
*
* \pre name.emtpy() == false
* \pre association >= 0 && association < NUM_FIELD_ASSOCIATION
*
* \see FieldAssociation
*/
inline bool removeField(const std::string& name, int association);
/*!
* \brief Returns pointer to buffer of the field with the given ane and
* specified mesh field association.
*
* \param [in] name the name of the requested field.
* \param [in] association the mesh field association.
* \param [out] num_components the number of components per tuple (optional).
*
* \return ptr raw pointer to the data buffer of the requested field.
*
* \pre name.empty() == false
* \pre hasField( name )
* \pre association >= 0 && association < NUM_FIELD_ASSOCIATION
*
* \see FieldAssociation
*/
/// @{
template <typename T>
inline T* getFieldPtr(const std::string& name,
int association,
IndexType& num_components);
template <typename T>
inline T* getFieldPtr(const std::string& name, int association);
template <typename T>
inline const T* getFieldPtr(const std::string& name,
int association,
IndexType& num_components) const;
template <typename T>
inline const T* getFieldPtr(const std::string& name, int association) const;
/// @}
/// @}
protected:
/// \name Protected Members
/// @{
int m_ndims; /*! mesh dimension */
int m_type; /*! the type of the mesh */
int m_block_idx; /*! the Block ID of the mesh */
int m_part_idx; /*! the partition ID of the mesh */
bool m_explicit_coords;
bool m_explicit_connectivity;
bool m_has_mixed_topology;
FieldData* m_mesh_fields[NUM_FIELD_ASSOCIATIONS];
#ifdef AXOM_MINT_USE_SIDRE
sidre::Group* m_group;
std::string m_topology;
std::string m_coordset;
#endif
/// @}
/// \name Protected Constructors (used in derived classes )
/// @{
/*!
* \brief Mesh Constructor.
*
* \param [in] ndims the number of dimensions
* \param [in] type the mesh type.
* \param [in] blockId the block ID for this mesh instance.
* \param [in] partId the partition ID for this mesh instance.
*/
Mesh(int ndims, int type);
#ifdef AXOM_MINT_USE_SIDRE
/*!
* \brief Constructor for use with a group that already has data.
*
* \param [in] group the sidre::Group to use.
* \param [in] topo optional argument specifying the name of the topology
* associated with this Mesh instance.
*
* \note If a topology name is not provided, the implementation will construct
* a mesh based on the 1st topology group under the parent "topologies"
* group.
*
* \pre group != nullptr.
* \pre blueprint::isValidRootGroup( group ) == true
*
* \see sidre::Group
*/
Mesh(sidre::Group* group, const std::string& topo = "");
/*!
* \brief Constructor for use with an empty group.
*
* \param [in] ndims the number of dimensions
* \param [in] type the mesh type.
* \param [in] group the sidre::Group to use.
* \param [in] topo the name of the associated topology group.
* \param [in] coordset the name of the associated coordset group.
*
* \note If a topology and coordset name is not provided a default name is
* used by the implementation.
*
* \pre group != nullptr.
* \pre group->getNumGroups() == 0
* \pre group->getNumViews() == 0
* \post blueprint::isValidRootGroup( group )
*
* \see sidre::Group
*/
Mesh(int ndims,
int type,
sidre::Group* group,
const std::string& topo,
const std::string& coordset);
/*!
* \brief Helper method to return the associated coordset group.
* \return coordset the associated coordset group.
*
* \pre m_group != nullptr
* \pre blueprint::isValidRootGroup( m_group )
* \post blueprint::isValidCoordsetGroup( coordset )
*/
sidre::Group* getCoordsetGroup();
/*!
* \brief Helper method to return the associated topology group.
* \return topology the associated topology group.
*
* \pre m_group != nullptr
* \pre blueprint::isValidRootGroup( m_group )
* \post blueprint::isValidTopologyGroup( topology )
*/
sidre::Group* getTopologyGroup();
#endif
/// @}
private:
/*!
* \brief Get the info corresponding to the given mesh field association.
*
* \param [in] association the mesh field association, e.g., NODE_CENTERED.
* \param [out] num_tuples the number of tuples in the associated FieldData.
* \param [out] capacity the capacity of the associated FieldData.
*/
void getFieldInfo(int association,
IndexType& num_tuples,
IndexType& capacity) const;
/*!
* \brief Helper method to check if the mesh type is valid.
* \return status true if the mesh type is valie, else, false.
*/
inline bool validMeshType() const
{
return ((m_type >= 0) && (m_type < mint::NUM_MESH_TYPES));
}
/*!
* \brief Helper method to check if the mesh dimension is valid.
* \return status true if the mesh dimension is valid, else, false.
*/
inline bool validDimension() const { return (m_ndims >= 1 && m_ndims <= 3); }
/*!
* \brief Allocates the FieldData internal data-structures.
* \note Helper method that is called from the constructor.
*/
void allocateFieldData();
/*!
* \brief Deallocates the FieldData internal data-structures.
* \note Helper method that is called by the destructor.
*/
void deallocateFieldData();
DISABLE_COPY_AND_ASSIGNMENT(Mesh);
DISABLE_MOVE_AND_ASSIGNMENT(Mesh);
};
//------------------------------------------------------------------------------
// IMPLEMENTATION OF TEMPLATE & IN-LINE METHODS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
inline bool Mesh::hasSidreGroup() const
{
#ifdef AXOM_MINT_USE_SIDRE
return (m_group != nullptr);
#else
return false;
#endif
}
//------------------------------------------------------------------------------
inline const FieldData* Mesh::getFieldData(int association) const
{
SLIC_ERROR_IF(association < 0 || association >= NUM_FIELD_ASSOCIATIONS,
"invalid field association [" << association << "]");
SLIC_ERROR_IF(m_mesh_fields[association] == nullptr,
"null field data object w/association [" << association << "]");
SLIC_ERROR_IF(m_type == PARTICLE_MESH && association != NODE_CENTERED,
"a particle mesh may only store node-centered fields");
return m_mesh_fields[association];
}
//------------------------------------------------------------------------------
inline bool Mesh::hasField(const std::string& name, int association) const
{
bool found = false;
if(association == mint::ANY_CENTERING)
{
int N = (m_type == mint::PARTICLE_MESH) ? 1 : mint::NUM_FIELD_ASSOCIATIONS;
for(int i = 0; !found && i < N; ++i)
{
const FieldData* fd = getFieldData(i);
SLIC_ASSERT(fd != nullptr);
found = fd->hasField(name);
}
}
else
{
const FieldData* fd = getFieldData(association);
SLIC_ASSERT(fd != nullptr);
found = fd->hasField(name);
}
return (found);
}
//------------------------------------------------------------------------------
template <typename T>
inline T* Mesh::createField(const std::string& name,
int association,
IndexType num_components,
bool storeInSidre)
{
SLIC_ERROR_IF(hasField(name), "a field with the same name already exists!");
FieldData* fd = const_cast<FieldData*>(getFieldData(association));
SLIC_ASSERT(fd != nullptr);
IndexType num_tuples, capacity;
getFieldInfo(association, num_tuples, capacity);
T* ptr =
fd->createField<T>(name, num_tuples, num_components, capacity, storeInSidre);
if(num_tuples > 0)
{
SLIC_ASSERT(ptr != nullptr);
}
return (ptr);
}
//------------------------------------------------------------------------------
template <typename T>
inline T* Mesh::createField(const std::string& name,
int association,
T* data,
IndexType num_components,
IndexType capacity)
{
SLIC_ERROR_IF(hasField(name), "a field with the same name already exists!");
SLIC_ASSERT(data != nullptr);
FieldData* fd = const_cast<FieldData*>(getFieldData(association));
SLIC_ASSERT(fd != nullptr);
IndexType num_tuples, dummy1;
getFieldInfo(association, num_tuples, dummy1);
T* ptr = fd->createField<T>(name, data, num_tuples, num_components, capacity);
SLIC_ASSERT(ptr == data);
return (ptr);
}
//------------------------------------------------------------------------------
inline bool Mesh::removeField(const std::string& name, int association)
{
bool status = false;
FieldData* fd = const_cast<FieldData*>(getFieldData(association));
const bool hasField = fd->hasField(name);
SLIC_WARNING_IF(!hasField, "field [" << name << "] does not exist!");
if(hasField)
{
fd->removeField(name);
status = true;
}
return (status);
}
//------------------------------------------------------------------------------
template <typename T>
inline T* Mesh::getFieldPtr(const std::string& name, int association)
{
IndexType num_components = 0;
return getFieldPtr<T>(name, association, num_components);
}
//------------------------------------------------------------------------------
template <typename T>
inline T* Mesh::getFieldPtr(const std::string& name,
int association,
IndexType& num_components)
{
const Mesh* self = const_cast<const Mesh*>(this);
const T* ptr = self->getFieldPtr<T>(name, association, num_components);
return (const_cast<T*>(ptr));
}
//------------------------------------------------------------------------------
template <typename T>
inline const T* Mesh::getFieldPtr(const std::string& name, int association) const
{
IndexType num_components = 0;
return getFieldPtr<T>(name, association, num_components);
}
//------------------------------------------------------------------------------
template <typename T>
inline const T* Mesh::getFieldPtr(const std::string& name,
int association,
IndexType& num_components) const
{
const FieldData* fd = getFieldData(association);
SLIC_ASSERT(fd != nullptr);
IndexType num_tuples = 0;
const T* ptr = fd->getFieldPtr<T>(name, num_tuples, num_components);
SLIC_ASSERT(ptr != nullptr);
return (ptr);
}
//------------------------------------------------------------------------------
inline void Mesh::getFieldInfo(int association,
IndexType& num_tuples,
IndexType& capacity) const
{
switch(association)
{
case NODE_CENTERED:
num_tuples = getNumberOfNodes();
capacity = getNodeCapacity();
break;
case CELL_CENTERED:
num_tuples = getNumberOfCells();
capacity = getCellCapacity();
break;
case FACE_CENTERED:
num_tuples = getNumberOfFaces();
capacity = getFaceCapacity();
break;
default:
SLIC_ASSERT(association == EDGE_CENTERED);
num_tuples = getNumberOfEdges();
capacity = getEdgeCapacity();
break;
} // END switch
}
} /* namespace mint */
} /* namespace axom */
#endif /* MINT_MESH_HPP_ */
| 33.264565 | 84 | 0.639572 | raineyeh |
e18342bcebf327def64cb9a88aa04b7e893c2857 | 2,200 | cc | C++ | src/atlas/grid/detail/spacing/gaussian/N80.cc | wdeconinck/atlas | 8949d2b362b9b5431023a967bcf4ca84f6b8ce05 | [
"Apache-2.0"
] | 3 | 2021-08-17T03:08:45.000Z | 2021-09-09T09:22:54.000Z | src/atlas/grid/detail/spacing/gaussian/N80.cc | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | 62 | 2020-10-21T15:27:38.000Z | 2022-03-28T12:42:43.000Z | src/atlas/grid/detail/spacing/gaussian/N80.cc | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | 1 | 2021-03-10T19:19:08.000Z | 2021-03-10T19:19:08.000Z | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
// TL159
#include "atlas/grid/detail/spacing/gaussian/N.h"
namespace atlas {
namespace grid {
namespace spacing {
namespace gaussian {
DEFINE_GAUSSIAN_LATITUDES(
80, LIST( 89.141519426461, 88.029428867952, 86.910770814124, 85.790628883637, 84.669924084447, 83.548946912542,
82.427817524008, 81.306594522669, 80.185309872477, 79.063982481409, 77.942624246673, 76.821243027100,
75.699844222011, 74.578431663296, 73.457008145583, 72.335575754909, 71.214136079887, 70.092690351624,
68.971239538936, 67.849784414670, 66.728325602882, 65.606863613010, 64.485398865043, 63.363931708341,
62.242462435891, 61.120991295252, 59.999518497040, 58.878044221583, 57.756568624184, 56.635091839330,
55.513613984077, 54.392135160792, 53.270655459398, 52.149174959220, 51.027693730509, 49.906211835711,
48.784729330535, 47.663246264843, 46.541762683406, 45.420278626548, 44.298794130694, 43.177309228835,
42.055823950935, 40.934338324279, 39.812852373771, 38.691366122202, 37.569879590471, 36.448392797794,
35.326905761872, 34.205418499049, 33.083931024447, 31.962443352088, 30.840955495002, 29.719467465319,
28.597979274357, 27.476490932696, 26.355002450251, 25.233513836324, 24.112025099671, 22.990536248541,
21.869047290730, 20.747558233616, 19.626069084199, 18.504579849136, 17.383090534771, 16.261601147162,
15.140111692111, 14.018622175186, 12.897132601745, 11.775642976956, 10.654153305818, 9.532663593176,
8.411173843743, 7.289684062115, 6.168194252784, 5.046704420157, 3.925214568566, 2.803724702287,
1.682234825547, 0.560744942544 ) )
} // namespace gaussian
} // namespace spacing
} // namespace grid
} // namespace atlas
| 55 | 115 | 0.726818 | wdeconinck |
e184190113e5855db318513c6add2d7386339f9d | 34,893 | cpp | C++ | Source/Macad.Occt/Generated/Adaptor2d.cpp | zhyifei/Macad3D | 55d92a7de53a1fc8f4453c09b162c261a40586f0 | [
"MIT"
] | 107 | 2020-11-29T18:01:50.000Z | 2022-03-31T13:54:40.000Z | Source/Macad.Occt/Generated/Adaptor2d.cpp | zhyifei/Macad3D | 55d92a7de53a1fc8f4453c09b162c261a40586f0 | [
"MIT"
] | 10 | 2021-03-12T18:34:24.000Z | 2022-01-08T21:03:58.000Z | Source/Macad.Occt/Generated/Adaptor2d.cpp | zhyifei/Macad3D | 55d92a7de53a1fc8f4453c09b162c261a40586f0 | [
"MIT"
] | 42 | 2021-01-07T06:23:24.000Z | 2022-03-29T10:03:51.000Z | // Generated wrapper code for package Adaptor2d
#include "OcctPCH.h"
#include "Adaptor2d.h"
using namespace System::Runtime::InteropServices; // for class Marshal
#include "Adaptor2d.h"
#include "Geom2dAdaptor.h"
#include "ProjLib.h"
#include "BRepAdaptor.h"
#include "Standard.h"
#include "GeomAbs.h"
#include "TColStd.h"
#include "gp.h"
#include "Geom2d.h"
//---------------------------------------------------------------------
// Class Adaptor2d_HCurve2d
//---------------------------------------------------------------------
Macad::Occt::Adaptor2d_HCurve2d::Adaptor2d_HCurve2d(Macad::Occt::Adaptor2d_HCurve2d^ parameter1)
: Macad::Occt::Standard_Transient(BaseClass::InitMode::Uninitialized)
{
throw gcnew System::NotImplementedException("Native class is abstract");
}
Macad::Occt::Adaptor2d_HCurve2d::Adaptor2d_HCurve2d()
: Macad::Occt::Standard_Transient(BaseClass::InitMode::Uninitialized)
{
throw gcnew System::NotImplementedException("Native class is abstract");
}
Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HCurve2d::Curve2d()
{
::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d();
*_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HCurve2d*)_NativeInstance)->Curve2d();
return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result);
}
double Macad::Occt::Adaptor2d_HCurve2d::FirstParameter()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->FirstParameter();
}
double Macad::Occt::Adaptor2d_HCurve2d::LastParameter()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->LastParameter();
}
Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_HCurve2d::Continuity()
{
return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_HCurve2d*)_NativeInstance)->Continuity();
}
int Macad::Occt::Adaptor2d_HCurve2d::NbIntervals(Macad::Occt::GeomAbs_Shape S)
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S);
}
void Macad::Occt::Adaptor2d_HCurve2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S)
{
((::Adaptor2d_HCurve2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S);
}
Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_HCurve2d::Trim(double First, double Last, double Tol)
{
Handle(::Adaptor2d_HCurve2d) _result;
_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Trim(First, Last, Tol);
return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get());
}
bool Macad::Occt::Adaptor2d_HCurve2d::IsClosed()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsClosed();
}
bool Macad::Occt::Adaptor2d_HCurve2d::IsPeriodic()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsPeriodic();
}
double Macad::Occt::Adaptor2d_HCurve2d::Period()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Period();
}
Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_HCurve2d::Value(double U)
{
return Macad::Occt::Pnt2d(((::Adaptor2d_HCurve2d*)_NativeInstance)->Value(U));
}
void Macad::Occt::Adaptor2d_HCurve2d::D0(double U, Macad::Occt::Pnt2d% P)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
((::Adaptor2d_HCurve2d*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P);
}
void Macad::Occt::Adaptor2d_HCurve2d::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V = &V;
((::Adaptor2d_HCurve2d*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V);
}
void Macad::Occt::Adaptor2d_HCurve2d::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
((::Adaptor2d_HCurve2d*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2);
}
void Macad::Occt::Adaptor2d_HCurve2d::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3;
((::Adaptor2d_HCurve2d*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3);
}
Macad::Occt::Vec2d Macad::Occt::Adaptor2d_HCurve2d::DN(double U, int N)
{
return Macad::Occt::Vec2d(((::Adaptor2d_HCurve2d*)_NativeInstance)->DN(U, N));
}
double Macad::Occt::Adaptor2d_HCurve2d::Resolution(double R3d)
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Resolution(R3d);
}
Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_HCurve2d::GetGeomType()
{
return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_HCurve2d*)_NativeInstance)->GetType();
}
Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_HCurve2d::Line()
{
::gp_Lin2d* _result = new ::gp_Lin2d();
*_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Line();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result);
}
Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_HCurve2d::Circle()
{
::gp_Circ2d* _result = new ::gp_Circ2d();
*_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Circle();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result);
}
Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_HCurve2d::Ellipse()
{
::gp_Elips2d* _result = new ::gp_Elips2d();
*_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Ellipse();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result);
}
Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_HCurve2d::Hyperbola()
{
::gp_Hypr2d* _result = new ::gp_Hypr2d();
*_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Hyperbola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result);
}
Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_HCurve2d::Parabola()
{
::gp_Parab2d* _result = new ::gp_Parab2d();
*_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Parabola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result);
}
int Macad::Occt::Adaptor2d_HCurve2d::Degree()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Degree();
}
bool Macad::Occt::Adaptor2d_HCurve2d::IsRational()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsRational();
}
int Macad::Occt::Adaptor2d_HCurve2d::NbPoles()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbPoles();
}
int Macad::Occt::Adaptor2d_HCurve2d::NbKnots()
{
return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbKnots();
}
Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_HCurve2d::Bezier()
{
Handle(::Geom2d_BezierCurve) _result;
_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Bezier();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get());
}
Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_HCurve2d::BSpline()
{
Handle(::Geom2d_BSplineCurve) _result;
_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->BSpline();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get());
}
Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted(::Adaptor2d_HCurve2d* instance)
{
if( instance == nullptr )
return nullptr;
if (instance->IsKind(STANDARD_TYPE(::Adaptor2d_HLine2d)))
return Macad::Occt::Adaptor2d_HLine2d::CreateDowncasted((::Adaptor2d_HLine2d*)instance);
if (instance->IsKind(STANDARD_TYPE(::Adaptor2d_HOffsetCurve)))
return Macad::Occt::Adaptor2d_HOffsetCurve::CreateDowncasted((::Adaptor2d_HOffsetCurve*)instance);
if (instance->IsKind(STANDARD_TYPE(::Geom2dAdaptor_GHCurve)))
return Macad::Occt::Geom2dAdaptor_GHCurve::CreateDowncasted((::Geom2dAdaptor_GHCurve*)instance);
if (instance->IsKind(STANDARD_TYPE(::ProjLib_HProjectedCurve)))
return Macad::Occt::ProjLib_HProjectedCurve::CreateDowncasted((::ProjLib_HProjectedCurve*)instance);
if (instance->IsKind(STANDARD_TYPE(::ProjLib_HCompProjectedCurve)))
return Macad::Occt::ProjLib_HCompProjectedCurve::CreateDowncasted((::ProjLib_HCompProjectedCurve*)instance);
if (instance->IsKind(STANDARD_TYPE(::BRepAdaptor_HCurve2d)))
return Macad::Occt::BRepAdaptor_HCurve2d::CreateDowncasted((::BRepAdaptor_HCurve2d*)instance);
return gcnew Macad::Occt::Adaptor2d_HCurve2d( instance );
}
//---------------------------------------------------------------------
// Class Adaptor2d_Curve2d
//---------------------------------------------------------------------
Macad::Occt::Adaptor2d_Curve2d::Adaptor2d_Curve2d(Macad::Occt::Adaptor2d_Curve2d^ parameter1)
: BaseClass<::Adaptor2d_Curve2d>(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::Adaptor2d_Curve2d(*(::Adaptor2d_Curve2d*)parameter1->NativeInstance);
}
Macad::Occt::Adaptor2d_Curve2d::Adaptor2d_Curve2d()
: BaseClass<::Adaptor2d_Curve2d>(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::Adaptor2d_Curve2d();
}
double Macad::Occt::Adaptor2d_Curve2d::FirstParameter()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->FirstParameter();
}
double Macad::Occt::Adaptor2d_Curve2d::LastParameter()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->LastParameter();
}
Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_Curve2d::Continuity()
{
return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_Curve2d*)_NativeInstance)->Continuity();
}
int Macad::Occt::Adaptor2d_Curve2d::NbIntervals(Macad::Occt::GeomAbs_Shape S)
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S);
}
void Macad::Occt::Adaptor2d_Curve2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S)
{
((::Adaptor2d_Curve2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S);
}
Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_Curve2d::Trim(double First, double Last, double Tol)
{
Handle(::Adaptor2d_HCurve2d) _result;
_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Trim(First, Last, Tol);
return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get());
}
bool Macad::Occt::Adaptor2d_Curve2d::IsClosed()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsClosed();
}
bool Macad::Occt::Adaptor2d_Curve2d::IsPeriodic()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsPeriodic();
}
double Macad::Occt::Adaptor2d_Curve2d::Period()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->Period();
}
Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_Curve2d::Value(double U)
{
return Macad::Occt::Pnt2d(((::Adaptor2d_Curve2d*)_NativeInstance)->Value(U));
}
void Macad::Occt::Adaptor2d_Curve2d::D0(double U, Macad::Occt::Pnt2d% P)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
((::Adaptor2d_Curve2d*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P);
}
void Macad::Occt::Adaptor2d_Curve2d::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V = &V;
((::Adaptor2d_Curve2d*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V);
}
void Macad::Occt::Adaptor2d_Curve2d::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
((::Adaptor2d_Curve2d*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2);
}
void Macad::Occt::Adaptor2d_Curve2d::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3;
((::Adaptor2d_Curve2d*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3);
}
Macad::Occt::Vec2d Macad::Occt::Adaptor2d_Curve2d::DN(double U, int N)
{
return Macad::Occt::Vec2d(((::Adaptor2d_Curve2d*)_NativeInstance)->DN(U, N));
}
double Macad::Occt::Adaptor2d_Curve2d::Resolution(double R3d)
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->Resolution(R3d);
}
Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_Curve2d::GetGeomType()
{
return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_Curve2d*)_NativeInstance)->GetType();
}
Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_Curve2d::Line()
{
::gp_Lin2d* _result = new ::gp_Lin2d();
*_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Line();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result);
}
Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_Curve2d::Circle()
{
::gp_Circ2d* _result = new ::gp_Circ2d();
*_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Circle();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result);
}
Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_Curve2d::Ellipse()
{
::gp_Elips2d* _result = new ::gp_Elips2d();
*_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Ellipse();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result);
}
Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_Curve2d::Hyperbola()
{
::gp_Hypr2d* _result = new ::gp_Hypr2d();
*_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Hyperbola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result);
}
Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_Curve2d::Parabola()
{
::gp_Parab2d* _result = new ::gp_Parab2d();
*_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Parabola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result);
}
int Macad::Occt::Adaptor2d_Curve2d::Degree()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->Degree();
}
bool Macad::Occt::Adaptor2d_Curve2d::IsRational()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsRational();
}
int Macad::Occt::Adaptor2d_Curve2d::NbPoles()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbPoles();
}
int Macad::Occt::Adaptor2d_Curve2d::NbKnots()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbKnots();
}
int Macad::Occt::Adaptor2d_Curve2d::NbSamples()
{
return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbSamples();
}
Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_Curve2d::Bezier()
{
Handle(::Geom2d_BezierCurve) _result;
_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Bezier();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get());
}
Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_Curve2d::BSpline()
{
Handle(::Geom2d_BSplineCurve) _result;
_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->BSpline();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get());
}
//---------------------------------------------------------------------
// Class Adaptor2d_Line2d
//---------------------------------------------------------------------
Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d()
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::Adaptor2d_Line2d();
}
Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d(Macad::Occt::Pnt2d P, Macad::Occt::Dir2d D, double UFirst, double ULast)
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Dir2d> pp_D = &D;
_NativeInstance = new ::Adaptor2d_Line2d(*(gp_Pnt2d*)pp_P, *(gp_Dir2d*)pp_D, UFirst, ULast);
}
Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d(Macad::Occt::Adaptor2d_Line2d^ parameter1)
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::Adaptor2d_Line2d(*(::Adaptor2d_Line2d*)parameter1->NativeInstance);
}
void Macad::Occt::Adaptor2d_Line2d::Load(Macad::Occt::gp_Lin2d^ L)
{
((::Adaptor2d_Line2d*)_NativeInstance)->Load(*(::gp_Lin2d*)L->NativeInstance);
}
void Macad::Occt::Adaptor2d_Line2d::Load(Macad::Occt::gp_Lin2d^ L, double UFirst, double ULast)
{
((::Adaptor2d_Line2d*)_NativeInstance)->Load(*(::gp_Lin2d*)L->NativeInstance, UFirst, ULast);
}
double Macad::Occt::Adaptor2d_Line2d::FirstParameter()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->FirstParameter();
}
double Macad::Occt::Adaptor2d_Line2d::LastParameter()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->LastParameter();
}
Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_Line2d::Continuity()
{
return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_Line2d*)_NativeInstance)->Continuity();
}
int Macad::Occt::Adaptor2d_Line2d::NbIntervals(Macad::Occt::GeomAbs_Shape S)
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S);
}
void Macad::Occt::Adaptor2d_Line2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S)
{
((::Adaptor2d_Line2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S);
}
Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_Line2d::Trim(double First, double Last, double Tol)
{
Handle(::Adaptor2d_HCurve2d) _result;
_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Trim(First, Last, Tol);
return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get());
}
bool Macad::Occt::Adaptor2d_Line2d::IsClosed()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->IsClosed();
}
bool Macad::Occt::Adaptor2d_Line2d::IsPeriodic()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->IsPeriodic();
}
double Macad::Occt::Adaptor2d_Line2d::Period()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->Period();
}
Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_Line2d::Value(double X)
{
return Macad::Occt::Pnt2d(((::Adaptor2d_Line2d*)_NativeInstance)->Value(X));
}
void Macad::Occt::Adaptor2d_Line2d::D0(double X, Macad::Occt::Pnt2d% P)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
((::Adaptor2d_Line2d*)_NativeInstance)->D0(X, *(gp_Pnt2d*)pp_P);
}
void Macad::Occt::Adaptor2d_Line2d::D1(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V = &V;
((::Adaptor2d_Line2d*)_NativeInstance)->D1(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V);
}
void Macad::Occt::Adaptor2d_Line2d::D2(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
((::Adaptor2d_Line2d*)_NativeInstance)->D2(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2);
}
void Macad::Occt::Adaptor2d_Line2d::D3(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3;
((::Adaptor2d_Line2d*)_NativeInstance)->D3(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3);
}
Macad::Occt::Vec2d Macad::Occt::Adaptor2d_Line2d::DN(double U, int N)
{
return Macad::Occt::Vec2d(((::Adaptor2d_Line2d*)_NativeInstance)->DN(U, N));
}
double Macad::Occt::Adaptor2d_Line2d::Resolution(double R3d)
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->Resolution(R3d);
}
Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_Line2d::GetGeomType()
{
return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_Line2d*)_NativeInstance)->GetType();
}
Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_Line2d::Line()
{
::gp_Lin2d* _result = new ::gp_Lin2d();
*_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Line();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result);
}
Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_Line2d::Circle()
{
::gp_Circ2d* _result = new ::gp_Circ2d();
*_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Circle();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result);
}
Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_Line2d::Ellipse()
{
::gp_Elips2d* _result = new ::gp_Elips2d();
*_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Ellipse();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result);
}
Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_Line2d::Hyperbola()
{
::gp_Hypr2d* _result = new ::gp_Hypr2d();
*_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Hyperbola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result);
}
Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_Line2d::Parabola()
{
::gp_Parab2d* _result = new ::gp_Parab2d();
*_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Parabola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result);
}
int Macad::Occt::Adaptor2d_Line2d::Degree()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->Degree();
}
bool Macad::Occt::Adaptor2d_Line2d::IsRational()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->IsRational();
}
int Macad::Occt::Adaptor2d_Line2d::NbPoles()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->NbPoles();
}
int Macad::Occt::Adaptor2d_Line2d::NbKnots()
{
return ((::Adaptor2d_Line2d*)_NativeInstance)->NbKnots();
}
Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_Line2d::Bezier()
{
Handle(::Geom2d_BezierCurve) _result;
_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Bezier();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get());
}
Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_Line2d::BSpline()
{
Handle(::Geom2d_BSplineCurve) _result;
_result = ((::Adaptor2d_Line2d*)_NativeInstance)->BSpline();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get());
}
//---------------------------------------------------------------------
// Class Adaptor2d_HLine2d
//---------------------------------------------------------------------
Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d()
: Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized)
{
NativeInstance = new ::Adaptor2d_HLine2d();
}
Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d(Macad::Occt::Adaptor2d_Line2d^ C)
: Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized)
{
NativeInstance = new ::Adaptor2d_HLine2d(*(::Adaptor2d_Line2d*)C->NativeInstance);
}
Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d(Macad::Occt::Adaptor2d_HLine2d^ parameter1)
: Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized)
{
NativeInstance = new ::Adaptor2d_HLine2d(*(::Adaptor2d_HLine2d*)parameter1->NativeInstance);
}
void Macad::Occt::Adaptor2d_HLine2d::Set(Macad::Occt::Adaptor2d_Line2d^ C)
{
((::Adaptor2d_HLine2d*)_NativeInstance)->Set(*(::Adaptor2d_Line2d*)C->NativeInstance);
}
Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HLine2d::Curve2d()
{
::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d();
*_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HLine2d*)_NativeInstance)->Curve2d();
return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result);
}
Macad::Occt::Adaptor2d_Line2d^ Macad::Occt::Adaptor2d_HLine2d::ChangeCurve2d()
{
::Adaptor2d_Line2d* _result = new ::Adaptor2d_Line2d();
*_result = ((::Adaptor2d_HLine2d*)_NativeInstance)->ChangeCurve2d();
return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Line2d(_result);
}
Macad::Occt::Adaptor2d_HLine2d^ Macad::Occt::Adaptor2d_HLine2d::CreateDowncasted(::Adaptor2d_HLine2d* instance)
{
return gcnew Macad::Occt::Adaptor2d_HLine2d( instance );
}
//---------------------------------------------------------------------
// Class Adaptor2d_OffsetCurve
//---------------------------------------------------------------------
Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve()
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::Adaptor2d_OffsetCurve();
}
Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C)
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance;
_NativeInstance = new ::Adaptor2d_OffsetCurve(h_C);
C->NativeInstance = h_C.get();
}
Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C, double Offset)
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance;
_NativeInstance = new ::Adaptor2d_OffsetCurve(h_C, Offset);
C->NativeInstance = h_C.get();
}
Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C, double Offset, double WFirst, double WLast)
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance;
_NativeInstance = new ::Adaptor2d_OffsetCurve(h_C, Offset, WFirst, WLast);
C->NativeInstance = h_C.get();
}
Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_OffsetCurve^ parameter1)
: Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::Adaptor2d_OffsetCurve(*(::Adaptor2d_OffsetCurve*)parameter1->NativeInstance);
}
void Macad::Occt::Adaptor2d_OffsetCurve::Load(Macad::Occt::Adaptor2d_HCurve2d^ S)
{
Handle(::Adaptor2d_HCurve2d) h_S = S->NativeInstance;
((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(h_S);
S->NativeInstance = h_S.get();
}
void Macad::Occt::Adaptor2d_OffsetCurve::Load(double Offset)
{
((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(Offset);
}
void Macad::Occt::Adaptor2d_OffsetCurve::Load(double Offset, double WFirst, double WLast)
{
((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(Offset, WFirst, WLast);
}
Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_OffsetCurve::Curve()
{
Handle(::Adaptor2d_HCurve2d) _result;
_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Curve();
return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get());
}
double Macad::Occt::Adaptor2d_OffsetCurve::Offset()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Offset();
}
double Macad::Occt::Adaptor2d_OffsetCurve::FirstParameter()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->FirstParameter();
}
double Macad::Occt::Adaptor2d_OffsetCurve::LastParameter()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->LastParameter();
}
Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_OffsetCurve::Continuity()
{
return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_OffsetCurve*)_NativeInstance)->Continuity();
}
int Macad::Occt::Adaptor2d_OffsetCurve::NbIntervals(Macad::Occt::GeomAbs_Shape S)
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S);
}
void Macad::Occt::Adaptor2d_OffsetCurve::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S)
{
((::Adaptor2d_OffsetCurve*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S);
}
Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_OffsetCurve::Trim(double First, double Last, double Tol)
{
Handle(::Adaptor2d_HCurve2d) _result;
_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Trim(First, Last, Tol);
return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get());
}
bool Macad::Occt::Adaptor2d_OffsetCurve::IsClosed()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsClosed();
}
bool Macad::Occt::Adaptor2d_OffsetCurve::IsPeriodic()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsPeriodic();
}
double Macad::Occt::Adaptor2d_OffsetCurve::Period()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Period();
}
Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_OffsetCurve::Value(double U)
{
return Macad::Occt::Pnt2d(((::Adaptor2d_OffsetCurve*)_NativeInstance)->Value(U));
}
void Macad::Occt::Adaptor2d_OffsetCurve::D0(double U, Macad::Occt::Pnt2d% P)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
((::Adaptor2d_OffsetCurve*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P);
}
void Macad::Occt::Adaptor2d_OffsetCurve::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V = &V;
((::Adaptor2d_OffsetCurve*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V);
}
void Macad::Occt::Adaptor2d_OffsetCurve::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
((::Adaptor2d_OffsetCurve*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2);
}
void Macad::Occt::Adaptor2d_OffsetCurve::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3)
{
pin_ptr<Macad::Occt::Pnt2d> pp_P = &P;
pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1;
pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2;
pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3;
((::Adaptor2d_OffsetCurve*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3);
}
Macad::Occt::Vec2d Macad::Occt::Adaptor2d_OffsetCurve::DN(double U, int N)
{
return Macad::Occt::Vec2d(((::Adaptor2d_OffsetCurve*)_NativeInstance)->DN(U, N));
}
double Macad::Occt::Adaptor2d_OffsetCurve::Resolution(double R3d)
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Resolution(R3d);
}
Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_OffsetCurve::GetGeomType()
{
return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_OffsetCurve*)_NativeInstance)->GetType();
}
Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_OffsetCurve::Line()
{
::gp_Lin2d* _result = new ::gp_Lin2d();
*_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Line();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result);
}
Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_OffsetCurve::Circle()
{
::gp_Circ2d* _result = new ::gp_Circ2d();
*_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Circle();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result);
}
Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_OffsetCurve::Ellipse()
{
::gp_Elips2d* _result = new ::gp_Elips2d();
*_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Ellipse();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result);
}
Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_OffsetCurve::Hyperbola()
{
::gp_Hypr2d* _result = new ::gp_Hypr2d();
*_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Hyperbola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result);
}
Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_OffsetCurve::Parabola()
{
::gp_Parab2d* _result = new ::gp_Parab2d();
*_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Parabola();
return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result);
}
int Macad::Occt::Adaptor2d_OffsetCurve::Degree()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Degree();
}
bool Macad::Occt::Adaptor2d_OffsetCurve::IsRational()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsRational();
}
int Macad::Occt::Adaptor2d_OffsetCurve::NbPoles()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbPoles();
}
int Macad::Occt::Adaptor2d_OffsetCurve::NbKnots()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbKnots();
}
Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_OffsetCurve::Bezier()
{
Handle(::Geom2d_BezierCurve) _result;
_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Bezier();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get());
}
Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_OffsetCurve::BSpline()
{
Handle(::Geom2d_BSplineCurve) _result;
_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->BSpline();
return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get());
}
int Macad::Occt::Adaptor2d_OffsetCurve::NbSamples()
{
return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbSamples();
}
//---------------------------------------------------------------------
// Class Adaptor2d_HOffsetCurve
//---------------------------------------------------------------------
Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve()
: Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized)
{
NativeInstance = new ::Adaptor2d_HOffsetCurve();
}
Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve(Macad::Occt::Adaptor2d_OffsetCurve^ C)
: Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized)
{
NativeInstance = new ::Adaptor2d_HOffsetCurve(*(::Adaptor2d_OffsetCurve*)C->NativeInstance);
}
Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve(Macad::Occt::Adaptor2d_HOffsetCurve^ parameter1)
: Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized)
{
NativeInstance = new ::Adaptor2d_HOffsetCurve(*(::Adaptor2d_HOffsetCurve*)parameter1->NativeInstance);
}
void Macad::Occt::Adaptor2d_HOffsetCurve::Set(Macad::Occt::Adaptor2d_OffsetCurve^ C)
{
((::Adaptor2d_HOffsetCurve*)_NativeInstance)->Set(*(::Adaptor2d_OffsetCurve*)C->NativeInstance);
}
Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HOffsetCurve::Curve2d()
{
::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d();
*_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HOffsetCurve*)_NativeInstance)->Curve2d();
return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result);
}
Macad::Occt::Adaptor2d_OffsetCurve^ Macad::Occt::Adaptor2d_HOffsetCurve::ChangeCurve2d()
{
::Adaptor2d_OffsetCurve* _result = new ::Adaptor2d_OffsetCurve();
*_result = ((::Adaptor2d_HOffsetCurve*)_NativeInstance)->ChangeCurve2d();
return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_OffsetCurve(_result);
}
Macad::Occt::Adaptor2d_HOffsetCurve^ Macad::Occt::Adaptor2d_HOffsetCurve::CreateDowncasted(::Adaptor2d_HOffsetCurve* instance)
{
return gcnew Macad::Occt::Adaptor2d_HOffsetCurve( instance );
}
| 36.158549 | 149 | 0.70358 | zhyifei |
e1872723f039006da4b07196cad3e3e9f20bab9e | 761 | hpp | C++ | include/dish2/peripheral/readable_state/introspective_state/ResourceStockpile.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 1 | 2021-02-12T23:53:55.000Z | 2021-02-12T23:53:55.000Z | include/dish2/peripheral/readable_state/introspective_state/ResourceStockpile.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | include/dish2/peripheral/readable_state/introspective_state/ResourceStockpile.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | #pragma once
#ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE
#define DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE
#include "../../../../../third-party/conduit/include/uitsl/datastructs/PodLeafNode.hpp"
#include "../../../../../third-party/conduit/include/uitsl/meta/TypeName.hpp"
namespace dish2 {
struct ResourceStockpile : public uitsl::PodLeafNode<float> {
// inherit constructors
using parent_t = uitsl::PodLeafNode<float>;
using parent_t::parent_t;
};
} // namespace dish2
namespace uitsl {
UITSL_ENABLE_TYPENAME( dish2::ResourceStockpile );
} // namespace uitsl
#endif // #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE
| 30.44 | 99 | 0.802891 | schregardusc |
e189593b28f70587cb413a088631a6bce990f455 | 833 | cpp | C++ | UAlbertaBot/Source/strategies/protoss/DarkTemplarRush.cpp | kant2002/ualbertabot | b4c75be8bf023f289f2e58e49ad600a9bda38fcd | [
"MIT"
] | 2 | 2017-07-06T18:27:41.000Z | 2018-03-14T06:19:43.000Z | UAlbertaBot/Source/strategies/protoss/DarkTemplarRush.cpp | kant2002/ualbertabot | b4c75be8bf023f289f2e58e49ad600a9bda38fcd | [
"MIT"
] | 18 | 2017-10-29T20:37:47.000Z | 2019-08-25T16:01:28.000Z | UAlbertaBot/Source/strategies/protoss/DarkTemplarRush.cpp | kant2002/ualbertabot | b4c75be8bf023f289f2e58e49ad600a9bda38fcd | [
"MIT"
] | 1 | 2017-09-13T07:02:23.000Z | 2017-09-13T07:02:23.000Z | #include "DarkTemplarRush.h"
#include "..\..\UnitUtil.h"
using UAlbertaBot::MetaPairVector;
using UAlbertaBot::MetaPair;
using UAlbertaBot::UnitUtil::GetAllUnitCount;
AKBot::DarkTemplarRush::DarkTemplarRush(BWAPI::Player self)
: _self(self)
{
}
void AKBot::DarkTemplarRush::getBuildOrderGoal(MetaPairVector& goal, int currentFrame) const
{
int numDragoons = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Dragoon);
int numNexusAll = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Nexus);
int numDarkTeplar = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Dark_Templar);
goal.push_back(MetaPair(BWAPI::UnitTypes::Protoss_Dark_Templar, numDarkTeplar + 2));
// if we have a 2nd nexus then get some goons out
if (numNexusAll >= 2)
{
goal.push_back(MetaPair(BWAPI::UnitTypes::Protoss_Dragoon, numDragoons + 4));
}
}
| 30.851852 | 92 | 0.77431 | kant2002 |
e18a7f00e225b168bb40fc8abd06d9cca70c28c8 | 422 | hpp | C++ | toy_compiler/munster/ast/op/assign_op.hpp | Wmbat/toy_compiler | 370a2e76aaaa874de5fb6c25e0755638dd84b8b4 | [
"MIT"
] | null | null | null | toy_compiler/munster/ast/op/assign_op.hpp | Wmbat/toy_compiler | 370a2e76aaaa874de5fb6c25e0755638dd84b8b4 | [
"MIT"
] | null | null | null | toy_compiler/munster/ast/op/assign_op.hpp | Wmbat/toy_compiler | 370a2e76aaaa874de5fb6c25e0755638dd84b8b4 | [
"MIT"
] | null | null | null | #pragma once
#include <toy_compiler/munster/ast/op/op.hpp>
namespace munster::ast
{
class assign_op : public op
{
public:
using ptr = std::unique_ptr<assign_op>;
public:
assign_op(node_ptr val_0, node_ptr id_decl, node_ptr val_1);
void accept(visitor_variant &visitor) const override;
[[nodiscard]] auto to_string() const -> std::string override;
};
} // namespace munster::ast
| 21.1 | 67 | 0.680095 | Wmbat |
e18bc9c979aba4446d9350ecabb781c2d4c78e3f | 3,886 | cpp | C++ | src/sim/Cache/ZCacheV2.cpp | heyyod/AttilaSimulator | cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1 | [
"BSD-3-Clause"
] | null | null | null | src/sim/Cache/ZCacheV2.cpp | heyyod/AttilaSimulator | cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1 | [
"BSD-3-Clause"
] | null | null | null | src/sim/Cache/ZCacheV2.cpp | heyyod/AttilaSimulator | cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
*
* Copyright (c) 2002 - 2011 by Computer Architecture Department,
* Universitat Politecnica de Catalunya.
* All rights reserved.
*
* The contents of this file may not b;e disclosed to third parties,
* copied or duplicated in any form, in whole or in part, without the
* prior permission of the authors, Computer Architecture Department
* and Universitat Politecnica de Catalunya.
*
* $RCSfile: ZCacheV2.cpp,v $
* $Revision: 1.5 $
* $Author: vmoya $
* $Date: 2008-03-02 19:09:17 $
*
* Z Cache class implementation file.
*
*/
/**
*
* @file ZCacheV2.cpp
*
* Implements the Z Cache class. This class the cache used for access to the Z buffer in a GPU.
*
*/
#include "ZCacheV2.h"
#include "GPUMath.h"
#include "FragmentOpEmulator.h"
using namespace gpu3d;
// Z Cache class counter. Used to create identifiers for the created Z Caches
// that are then used to access the Memory Controller.
u32bit ZCacheV2::cacheCounter = 0;
// Z cache constructor.
ZCacheV2::ZCacheV2(u32bit ways, u32bit lines, u32bit lineSz,
u32bit readP, u32bit writeP, u32bit pWidth, u32bit reqQSize, u32bit inReqs,
u32bit outReqs, bool zComprDisabled, u32bit numStampUnits, u32bit stampUnitStride, u32bit maxZBlocks, u32bit blocksPerCycle,
u32bit compCycles, u32bit decompCycles, char *postfix
#if KONDAMASK_CACHE_DECAY
, u32bit decayInterval
#endif
) :
ROPCache(ways, lines, lineSz, readP, writeP, pWidth, reqQSize,
inReqs, outReqs, zComprDisabled, numStampUnits, stampUnitStride, maxZBlocks, blocksPerCycle, compCycles,
decompCycles, ZSTENCILTEST, "ZCache", postfix
#if KONDAMASK_CACHE_DECAY
, decayInterval
#endif
)
{
// Get the Z Cache identifier.
cacheID = cacheCounter;
// Update the number of created Z Caches.
cacheCounter++;
// Set reset value for clear.
for (u32bit i = 0; i < (MAX_BYTES_PER_PIXEL >> 2); i++)
((u32bit *) clearResetValue)[i] = 0x00ffffff;
}
// Clears the Z cache.
bool ZCacheV2::clear(u32bit depth, u8bit stencil)
{
// Reset the cache.
if (clearMode)
{
// Check clear cycles remaining.
if (clearCycles > 0)
{
// Update clear cycles.
clearCycles--;
// Check if end of clear.
if (clearCycles == 0)
{
// Set the clear value registers.
clearDepth = depth;
clearStencil = stencil;
// Set the ROP data clear value
((u32bit *) clearROPValue)[0] = (clearStencil << 24) | (clearDepth & 0x00ffffff);
/* Unset reset mode. */
clearMode = FALSE;
}
}
}
else
{
// NOTE: SHOULD TAKE INTO ACCOUNT THE RESOLUTION SO NOT ALL
// BLOCKS HAD TO BE CLEARED EVEN IF UNUSED AT CURRENT RESOLUTION.
// Set clear cycles.
clearCycles = (u32bit) ceil((f32bit) maxBlocks / (f32bit) blocksCycle);
// Set clear mode.
clearMode = TRUE;
// Reset the cache.
resetMode = TRUE;
}
return clearMode;
}
// Check HZ updates.
bool ZCacheV2::updateHZ(u32bit &block, u32bit &z)
{
// Check if there is an updated block.
if (blockWasWritten)
{
// Return block identifier and block Z.
block = writtenBlock;
z = wrBlockMaxVal;
// Reset updated HZ block flag.
blockWasWritten = false;
return true;
}
else
return false;
}
void ZCacheV2::processNextWrittenBlock(u8bit* outputBuffer, u32bit size)
{
u32bit* data = (u32bit*) outputBuffer;
u32bit dataSize = size / sizeof(u32bit);
u32bit maxZ;
// Calculate the maximum depth/Z.
FragmentOpEmulator::blockMaxZ(data, dataSize, maxZ);
// Store for later use
wrBlockMaxVal = maxZ;
}
// Copies the block state memory.
void ZCacheV2::copyBlockStateMemory(ROPBlockState *buffer, u32bit blocks)
{
GPU_ASSERT(
if (blocks > maxBlocks)
panic("ZCache", "copyBlockSateMemory", "More blocks to copy than blocks in the state memory.");
)
// Copy the block states.
memcpy(buffer, blockState, sizeof(ROPBlockState) * blocks);
}
| 24.136646 | 125 | 0.687597 | heyyod |
e18c0b85c91b24131d254205f3ca587b8c9ba794 | 3,214 | hpp | C++ | Include/Injector/Engine.hpp | InjectorGames/Inject | 09e74a83c287b81fd8272c10d6bae2b1aa785c0e | [
"BSD-3-Clause"
] | 2 | 2019-12-10T16:26:58.000Z | 2020-04-17T11:47:42.000Z | Include/Injector/Engine.hpp | InjectorGames/Inject | 09e74a83c287b81fd8272c10d6bae2b1aa785c0e | [
"BSD-3-Clause"
] | 28 | 2020-08-17T12:39:50.000Z | 2020-11-16T20:42:50.000Z | Include/Injector/Engine.hpp | InjectorGames/InjectorEngine | 09e74a83c287b81fd8272c10d6bae2b1aa785c0e | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "Injector/Defines.hpp"
#include "Injector/ECS/EcsManager.hpp"
#include "Injector/Mathematics/Matrix4.hpp"
#include "Injector/Graphics/GraphicsAPI.hpp"
#include <chrono>
namespace Injector
{
class Engine final
{
private:
static bool engineInitialized;
static bool networkInitialized;
static bool graphicsInitialized;
static bool virtualRealityInitialized;
static bool updateRunning;
static bool capUpdateRate;
static int targetUpdateRate;
static std::chrono::steady_clock::
time_point updateStartTick;
static double updateStartTime;
static double updateDeltaTime;
static GraphicsAPI graphicsAPI;
static FloatMatrix4 hmdModelMatrix;
static FloatMatrix4 leftEyeModelMatrix;
static FloatMatrix4 rightEyeModelMatrix;
static FloatMatrix4 leftEyeProjMatrix;
static FloatMatrix4 rightEyeProjMatrix;
static std::vector<std::shared_ptr<EcsManager>> managers;
public:
static bool getCapUpdateRate() noexcept;
static void setCapUpdateRate(bool cap = true) noexcept;
static int getTargetUpdateRate() noexcept;
static void setTargetUpdateRate(int ups = 60) noexcept;
static std::chrono::steady_clock::
time_point getUpdateStartTick() noexcept;
static double getUpdateStartTime() noexcept;
static double getUpdateDeltaTime() noexcept;
static void initializeEngine(
int majorVersion = INJECTOR_VERSION_MAJOR,
int minorVersion = INJECTOR_VERSION_MINOR,
int patchVersion = INJECTOR_VERSION_PATCH);
static void terminateEngine();
static bool isEngineInitialized() noexcept;
static void initializeNetwork();
static void terminateNetwork();
static bool isNetworkInitialized();
static void glfwErrorCallback(
int error,
const char* description);
static void initializeGraphics(
GraphicsAPI graphicsAPI = GraphicsAPI::OpenGL);
static void terminateGraphics();
static bool isGraphicsInitialized() noexcept;
static void initializeVirtualReality();
static void terminateVirtualReality();
static bool isVirtualRealityInitialized() noexcept;
static void startUpdateLoop();
static void stopUpdateLoop() noexcept;
static bool getUpdateRunning() noexcept;
static std::chrono::steady_clock::
time_point getTickNow() noexcept;
static double getTimeNow() noexcept;
static GraphicsAPI getGraphicsAPI() noexcept;
static const FloatMatrix4& getHmdModelMatrix() noexcept;
static const FloatMatrix4& getLeftEyeModelMatrix() noexcept;
static const FloatMatrix4& getRightEyeModelMatrix() noexcept;
static const FloatMatrix4& getLeftEyeProjMatrix() noexcept;
static const FloatMatrix4& getRightEyeProjMatrix() noexcept;
static bool addManager(
const std::shared_ptr<EcsManager>& manager) noexcept;
static bool removeManager(
const std::shared_ptr<EcsManager>& manager) noexcept;
static bool containsManager(
const std::shared_ptr<EcsManager>& manager) noexcept;
static void removeManagers() noexcept;
static size_t getManagerCount() noexcept;
template<class T = EcsManager, class ...Args>
static std::shared_ptr<T> createManager(Args... args) noexcept
{
auto manager = std::make_shared<T>(args...);
managers.push_back(manager);
return manager;
}
};
}
| 30.903846 | 64 | 0.780647 | InjectorGames |
e18e7a47b50ebb9e3ebd0b6d16fea63bd85063e2 | 17,049 | cpp | C++ | src/materialsystem/stdshaders_old/spritecard.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/materialsystem/stdshaders_old/spritecard.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/materialsystem/stdshaders_old/spritecard.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: shader for drawing sprites as cards, with animation frame lerping
//
// $Header: $
// $NoKeywords: $
//===========================================================================//
#include "BaseVSShader.h"
#include "convar.h"
// STDSHADER_DX9_DLL_EXPORT
#include "spritecard_ps20.inc"
#include "spritecard_ps20b.inc"
#include "spritecard_vs20.inc"
#include "splinecard_vs20.inc"
#if SUPPORT_DX8
// STDSHADER_DX8_DLL_EXPORT
#include "spritecard_vs11.inc"
#include "spritecard_ps11.inc"
#include "splinecard_vs11.inc"
#endif
#include "tier0/icommandline.h" //command line
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define DEFAULT_PARTICLE_FEATHERING_ENABLED 1
#ifdef STDSHADER_DX8_DLL_EXPORT
DEFINE_FALLBACK_SHADER( Spritecard, Spritecard_DX8 )
#endif
int GetDefaultDepthFeatheringValue( void ) //Allow the command-line to go against the default soft-particle value
{
static int iRetVal = -1;
if( iRetVal == -1 )
{
# if( DEFAULT_PARTICLE_FEATHERING_ENABLED == 1 )
{
if( CommandLine()->CheckParm( "-softparticlesdefaultoff" ) )
iRetVal = 0;
else
iRetVal = 1;
}
# else
{
if( CommandLine()->CheckParm( "-softparticlesdefaulton" ) )
iRetVal = 1;
else
iRetVal = 0;
}
# endif
}
// On low end parts on the Mac, we reduce particles and shut off depth blending here
static ConVarRef mat_reduceparticles( "mat_reduceparticles" );
if ( mat_reduceparticles.GetBool() )
{
iRetVal = 0;
}
return iRetVal;
}
#ifdef STDSHADER_DX9_DLL_EXPORT
BEGIN_VS_SHADER_FLAGS( Spritecard, "Help for Spritecard", SHADER_NOT_EDITABLE )
#else
BEGIN_VS_SHADER_FLAGS( Spritecard_DX8, "Help for Spritecard_DX8", SHADER_NOT_EDITABLE )
#endif
BEGIN_SHADER_PARAMS
SHADER_PARAM( DEPTHBLEND, SHADER_PARAM_TYPE_INTEGER, "0", "fade at intersection boundaries" )
SHADER_PARAM( DEPTHBLENDSCALE, SHADER_PARAM_TYPE_FLOAT, "50.0", "Amplify or reduce DEPTHBLEND fading. Lower values make harder edges." )
SHADER_PARAM( ORIENTATION, SHADER_PARAM_TYPE_INTEGER, "0", "0 = always face camera, 1 = rotate around z, 2= parallel to ground" )
SHADER_PARAM( ADDBASETEXTURE2, SHADER_PARAM_TYPE_FLOAT, "0.0", "amount to blend second texture into frame by" )
SHADER_PARAM( OVERBRIGHTFACTOR, SHADER_PARAM_TYPE_FLOAT, "1.0", "overbright factor for texture. For HDR effects.")
SHADER_PARAM( DUALSEQUENCE, SHADER_PARAM_TYPE_INTEGER, "0", "blend two separate animated sequences.")
SHADER_PARAM( SEQUENCE_BLEND_MODE, SHADER_PARAM_TYPE_INTEGER, "0", "defines the blend mode between the images un dual sequence particles. 0 = avg, 1=alpha from first, rgb from 2nd, 2= first over second" )
SHADER_PARAM( MAXLUMFRAMEBLEND1, SHADER_PARAM_TYPE_INTEGER, "0", "instead of blending between animation frames for the first sequence, select pixels based upon max luminance" )
SHADER_PARAM( MAXLUMFRAMEBLEND2, SHADER_PARAM_TYPE_INTEGER, "0", "instead of blending between animation frames for the 2nd sequence, select pixels based upon max luminance" )
SHADER_PARAM( RAMPTEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "if specified, then the red value of the image is used to index this ramp to produce the output color" )
SHADER_PARAM( ZOOMANIMATESEQ2, SHADER_PARAM_TYPE_FLOAT, "1.0", "amount to gradually zoom between frames on the second sequence. 2.0 will double the size of a frame over its lifetime.")
SHADER_PARAM( EXTRACTGREENALPHA, SHADER_PARAM_TYPE_INTEGER, "0", "grayscale data sitting in green/alpha channels")
SHADER_PARAM( ADDOVERBLEND, SHADER_PARAM_TYPE_INTEGER, "0", "use ONE:INVSRCALPHA blending")
SHADER_PARAM( ADDSELF, SHADER_PARAM_TYPE_FLOAT, "0.0", "amount of base texture to additively blend in" )
SHADER_PARAM( BLENDFRAMES, SHADER_PARAM_TYPE_BOOL, "1", "whether or not to smoothly blend between animated frames" )
SHADER_PARAM( MINSIZE, SHADER_PARAM_TYPE_FLOAT, "0.0", "minimum screen fractional size of particle")
SHADER_PARAM( STARTFADESIZE, SHADER_PARAM_TYPE_FLOAT, "10.0", "screen fractional size to start fading particle out")
SHADER_PARAM( ENDFADESIZE, SHADER_PARAM_TYPE_FLOAT, "20.0", "screen fractional size to finish fading particle out")
SHADER_PARAM( MAXSIZE, SHADER_PARAM_TYPE_FLOAT, "20.0", "maximum screen fractional size of particle")
SHADER_PARAM( USEINSTANCING, SHADER_PARAM_TYPE_BOOL, "1", "whether to use GPU vertex instancing (submit 1 vert per particle quad)")
SHADER_PARAM( SPLINETYPE, SHADER_PARAM_TYPE_INTEGER, "0", "spline type 0 = none, 1=ctamull rom")
SHADER_PARAM( MAXDISTANCE, SHADER_PARAM_TYPE_FLOAT, "100000.0", "maximum distance to draw particles at")
SHADER_PARAM( FARFADEINTERVAL, SHADER_PARAM_TYPE_FLOAT, "400.0", "interval over which to fade out far away particles")
END_SHADER_PARAMS
SHADER_INIT_PARAMS()
{
INIT_FLOAT_PARM( MAXDISTANCE, 100000.0);
INIT_FLOAT_PARM( FARFADEINTERVAL, 400.0);
INIT_FLOAT_PARM( MAXSIZE, 20.0 );
INIT_FLOAT_PARM( ENDFADESIZE, 20.0 );
INIT_FLOAT_PARM( STARTFADESIZE, 10.0 );
INIT_FLOAT_PARM( DEPTHBLENDSCALE, 50.0 );
INIT_FLOAT_PARM( OVERBRIGHTFACTOR, 1.0 );
INIT_FLOAT_PARM( ADDBASETEXTURE2, 0.0 );
INIT_FLOAT_PARM( ADDSELF, 0.0 );
INIT_FLOAT_PARM( ZOOMANIMATESEQ2, 0.0 );
if ( !params[DEPTHBLEND]->IsDefined() )
{
params[ DEPTHBLEND ]->SetIntValue( GetDefaultDepthFeatheringValue() );
}
if ( !g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
params[ DEPTHBLEND ]->SetIntValue( 0 );
}
if ( !params[DUALSEQUENCE]->IsDefined() )
{
params[DUALSEQUENCE]->SetIntValue( 0 );
}
if ( !params[MAXLUMFRAMEBLEND1]->IsDefined() )
{
params[MAXLUMFRAMEBLEND1]->SetIntValue( 0 );
}
if ( !params[MAXLUMFRAMEBLEND2]->IsDefined() )
{
params[MAXLUMFRAMEBLEND2]->SetIntValue( 0 );
}
if ( !params[EXTRACTGREENALPHA]->IsDefined() )
{
params[EXTRACTGREENALPHA]->SetIntValue( 0 );
}
if ( !params[ADDOVERBLEND]->IsDefined() )
{
params[ADDOVERBLEND]->SetIntValue( 0 );
}
if ( !params[BLENDFRAMES]->IsDefined() )
{
params[ BLENDFRAMES ]->SetIntValue( 1 );
}
if ( !params[USEINSTANCING]->IsDefined() )
{
params[ USEINSTANCING ]->SetIntValue( IsX360() ? 1 : 0 );
}
SET_FLAGS2( MATERIAL_VAR2_IS_SPRITECARD );
}
SHADER_FALLBACK
{
#ifdef STDSHADER_DX9_DLL_EXPORT
if ( g_pHardwareConfig->GetDXSupportLevel() < 90 )
return "SpriteCard_DX8";
#endif
#ifdef STDSHADER_DX8_DLL_EXPORT
// STDSHADER_DX8_DLL_EXPORT
if ( g_pHardwareConfig->GetDXSupportLevel() < 80 )
return "Wireframe";
#endif
return 0;
}
SHADER_INIT
{
#ifdef STDSHADER_DX9_DLL_EXPORT
const bool bDX8 = false;
#endif
#ifdef STDSHADER_DX8_DLL_EXPORT
const bool bDX8 = true;
#endif
SET_FLAGS2( MATERIAL_VAR2_LIGHTING_VERTEX_LIT );
if ( params[BASETEXTURE]->IsDefined() )
{
bool bExtractGreenAlpha = false;
if ( params[EXTRACTGREENALPHA]->IsDefined() )
{
bExtractGreenAlpha = params[EXTRACTGREENALPHA]->GetIntValue() != 0;
}
LoadTexture( BASETEXTURE, !bExtractGreenAlpha && !bDX8 ? TEXTUREFLAGS_SRGB : 0 );
}
if ( params[RAMPTEXTURE]->IsDefined() )
{
LoadTexture( RAMPTEXTURE, TEXTUREFLAGS_SRGB );
}
}
SHADER_DRAW
{
#ifdef STDSHADER_DX9_DLL_EXPORT
const bool bDX8 = false;
#endif
#ifdef STDSHADER_DX8_DLL_EXPORT
const bool bDX8 = true;
#endif
bool bUseRampTexture = (! bDX8 ) && ( params[RAMPTEXTURE]->IsDefined() );
bool bZoomSeq2 = (! bDX8 ) && ( ( params[ZOOMANIMATESEQ2]->GetFloatValue()) > 1.0 );
bool bDepthBlend = (! bDX8 ) && ( params[DEPTHBLEND]->GetIntValue() != 0 );
bool bAdditive2ndTexture = params[ADDBASETEXTURE2]->GetFloatValue() != 0.0;
int nSplineType = params[SPLINETYPE]->GetIntValue();
SHADOW_STATE
{
bool bSecondSequence = params[DUALSEQUENCE]->GetIntValue() != 0;
bool bAddOverBlend = params[ADDOVERBLEND]->GetIntValue() != 0;
bool bExtractGreenAlpha = (! bDX8 ) && ( params[EXTRACTGREENALPHA]->GetIntValue() != 0 );
bool bBlendFrames = (! bDX8 ) && ( params[BLENDFRAMES]->GetIntValue() != 0 );
if ( nSplineType )
{
bBlendFrames = false;
}
bool bAddSelf = params[ADDSELF]->GetFloatValue() != 0.0;
bool bUseInstancing = IsX360() ? ( params[ USEINSTANCING ]->GetIntValue() != 0 ) : false;
if ( nSplineType )
bUseInstancing = false;
// draw back-facing because of yaw spin
pShaderShadow->EnableCulling( false );
// Be sure not to write to dest alpha
pShaderShadow->EnableAlphaWrites( false );
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
if ( bDX8 )
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true );
if ( bAdditive2ndTexture && bDX8 )
pShaderShadow->EnableTexture( SHADER_SAMPLER3, true );
if ( bUseRampTexture )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true );
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER1, true );
}
if ( bDepthBlend )
{
pShaderShadow->EnableTexture( SHADER_SAMPLER2, true );
}
if ( bAdditive2ndTexture || bAddSelf )
pShaderShadow->EnableAlphaTest( false );
else
pShaderShadow->EnableAlphaTest( true );
pShaderShadow->AlphaFunc( SHADER_ALPHAFUNC_GREATER, 0.01f );
if ( bAdditive2ndTexture || bAddOverBlend || bAddSelf )
{
EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
}
else
{
if ( IS_FLAG_SET(MATERIAL_VAR_ADDITIVE) )
{
EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE );
}
else
{
EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
}
}
unsigned int flags = VERTEX_POSITION | VERTEX_COLOR;
static int s_TexCoordSize[8]={4, // 0 = sheet bounding uvs, frame0
4, // 1 = sheet bounding uvs, frame 1
4, // 2 = frame blend, rot, radius, ???
2, // 3 = corner identifier ( 0/0,1/0,1/1, 1/0 )
4, // 4 = texture 2 bounding uvs
4, // 5 = second sequence bounding uvs, frame0
4, // 6 = second sequence bounding uvs, frame1
4, // 7 = second sequence frame blend, ?,?,?
};
static int s_TexCoordSizeSpline[]={4, // 0 = sheet bounding uvs, frame0
4, // 1 = sheet bounding uvs, frame 1
4, // 2 = frame blend, rot, radius, ???
4, // 3 = corner identifier ( 0/0,1/0,1/1, 1/0 )
4, // 4 = texture 2 bounding uvs
4, // 5 = second sequence bounding uvs, frame0
4, // 6 = second sequence bounding uvs, frame1
4, // 7 = second sequence frame blend, ?,?,?
};
int numTexCoords = 4;
if ( true /* bAdditive2ndTexture */ ) // there is no branch for 2nd texture in the VS! -henryg
{
numTexCoords = 5;
}
if ( bSecondSequence )
{
// the whole shebang - 2 sequences, with a possible multi-image sequence first
numTexCoords = 8;
}
pShaderShadow->VertexShaderVertexFormat( flags,
numTexCoords,
nSplineType? s_TexCoordSizeSpline : s_TexCoordSize, 0 );
if ( bDX8 )
{
#if SUPPORT_DX8
if ( nSplineType )
{
DECLARE_STATIC_VERTEX_SHADER( splinecard_vs11 );
SET_STATIC_VERTEX_SHADER( splinecard_vs11 );
}
else
{
DECLARE_STATIC_VERTEX_SHADER( spritecard_vs11 );
if ( bSecondSequence )
bAdditive2ndTexture = false;
SET_STATIC_VERTEX_SHADER_COMBO( DUALSEQUENCE, false );
SET_STATIC_VERTEX_SHADER_COMBO( ZOOM_ANIMATE_SEQ2, false );
SET_STATIC_VERTEX_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha );
SET_STATIC_VERTEX_SHADER( spritecard_vs11 );
}
DECLARE_STATIC_PIXEL_SHADER( spritecard_ps11 );
SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture );
SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf );
SET_STATIC_PIXEL_SHADER_COMBO( USEALPHAASRGB, bSecondSequence );
SET_STATIC_PIXEL_SHADER( spritecard_ps11 );
#endif
}
else
{
if ( nSplineType )
{
DECLARE_STATIC_VERTEX_SHADER( splinecard_vs20 );
SET_STATIC_VERTEX_SHADER( splinecard_vs20 );
}
else
{
DECLARE_STATIC_VERTEX_SHADER( spritecard_vs20 );
SET_STATIC_VERTEX_SHADER_COMBO( DUALSEQUENCE, bSecondSequence );
SET_STATIC_VERTEX_SHADER_COMBO( ZOOM_ANIMATE_SEQ2, bZoomSeq2 );
SET_STATIC_VERTEX_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha );
SET_STATIC_VERTEX_SHADER_COMBO( USE_INSTANCING, bUseInstancing );
SET_STATIC_VERTEX_SHADER( spritecard_vs20 );
}
if( g_pHardwareConfig->SupportsPixelShaders_2_b() )
{
DECLARE_STATIC_PIXEL_SHADER( spritecard_ps20b );
SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture );
SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf );
SET_STATIC_PIXEL_SHADER_COMBO( ANIMBLEND, bBlendFrames );
SET_STATIC_PIXEL_SHADER_COMBO( DUALSEQUENCE, bSecondSequence );
SET_STATIC_PIXEL_SHADER_COMBO( SEQUENCE_BLEND_MODE, bSecondSequence ? params[SEQUENCE_BLEND_MODE]->GetIntValue() : 0 );
SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND1, params[MAXLUMFRAMEBLEND1]->GetIntValue() );
SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND2, bSecondSequence? params[MAXLUMFRAMEBLEND1]->GetIntValue() : 0 );
SET_STATIC_PIXEL_SHADER_COMBO( COLORRAMP, bUseRampTexture );
SET_STATIC_PIXEL_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha );
SET_STATIC_PIXEL_SHADER_COMBO( DEPTHBLEND, bDepthBlend );
SET_STATIC_PIXEL_SHADER( spritecard_ps20b );
}
else
{
DECLARE_STATIC_PIXEL_SHADER( spritecard_ps20 );
SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture );
SET_STATIC_PIXEL_SHADER_COMBO( DUALSEQUENCE, bSecondSequence );
SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf );
SET_STATIC_PIXEL_SHADER_COMBO( ANIMBLEND, bBlendFrames );
SET_STATIC_PIXEL_SHADER_COMBO( SEQUENCE_BLEND_MODE, bSecondSequence ? params[SEQUENCE_BLEND_MODE]->GetIntValue() : 0 );
SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND1, params[MAXLUMFRAMEBLEND1]->GetIntValue() );
SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND2, bSecondSequence? params[MAXLUMFRAMEBLEND1]->GetIntValue() : 0 );
SET_STATIC_PIXEL_SHADER_COMBO( COLORRAMP, bUseRampTexture );
SET_STATIC_PIXEL_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha );
SET_STATIC_PIXEL_SHADER( spritecard_ps20 );
}
if ( !bDX8 )
pShaderShadow->EnableSRGBWrite( true );
if( !bExtractGreenAlpha && !bDX8 )
pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, true );
}
}
DYNAMIC_STATE
{
BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME );
if ( bDX8 ) // bind on 2nd sampelr so we can lerp
BindTexture( SHADER_SAMPLER1, BASETEXTURE, FRAME );
if ( bDX8 && bAdditive2ndTexture )
BindTexture( SHADER_SAMPLER3, BASETEXTURE, FRAME );
if ( bUseRampTexture && ( !bDX8 ) )
{
BindTexture( SHADER_SAMPLER1, RAMPTEXTURE, FRAME );
}
if ( bDepthBlend )
{
pShaderAPI->BindStandardTexture( SHADER_SAMPLER2, TEXTURE_FRAME_BUFFER_FULL_DEPTH );
}
LoadViewportTransformScaledIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_10 );
int nOrientation = params[ORIENTATION]->GetIntValue();
nOrientation = clamp( nOrientation, 0, 2 );
// We need these only when screen-orienting
if ( nOrientation == 0 )
{
LoadModelViewMatrixIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0 );
LoadProjectionMatrixIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_3 );
}
if ( bZoomSeq2 )
{
float flZScale=1.0/(params[ZOOMANIMATESEQ2]->GetFloatValue());
float C0[4]={ (float)(0.5*(1.0+flZScale)), flZScale, 0, 0 };
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_7, C0,
ARRAYSIZE(C0)/4 );
}
// set fade constants in vsconsts 8 and 9
float flMaxDistance = params[MAXDISTANCE]->GetFloatValue();
float flStartFade = max( 1.f, flMaxDistance - params[FARFADEINTERVAL]->GetFloatValue() );
float VC0[8]={ params[MINSIZE]->GetFloatValue(), params[MAXSIZE]->GetFloatValue(),
params[STARTFADESIZE]->GetFloatValue(), params[ENDFADESIZE]->GetFloatValue(),
flStartFade, (float)(1.0/(flMaxDistance-flStartFade)),
0,0 };
pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_8, VC0, ARRAYSIZE(VC0)/4 );
pShaderAPI->SetDepthFeatheringPixelShaderConstant( 2, params[DEPTHBLENDSCALE]->GetFloatValue() );
float C0[4]={ params[ADDBASETEXTURE2]->GetFloatValue(),
params[OVERBRIGHTFACTOR]->GetFloatValue(),
params[ADDSELF]->GetFloatValue(),
0.0f };
if ( bDX8 && ( !bAdditive2ndTexture ) ) // deal with 0..1 limit for pix shader constants
{
C0[2] *= 0.25;
C0[1] *= 0.25;
}
pShaderAPI->SetPixelShaderConstant( 0, C0, ARRAYSIZE(C0)/4 );
if ( g_pHardwareConfig->GetDXSupportLevel() < 90 )
{
#if SUPPORT_DX8
if ( nSplineType )
{
DECLARE_DYNAMIC_VERTEX_SHADER( splinecard_vs11 );
SET_DYNAMIC_VERTEX_SHADER( splinecard_vs11 );
}
else
{
DECLARE_DYNAMIC_VERTEX_SHADER( spritecard_vs11 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( ORIENTATION, nOrientation );
SET_DYNAMIC_VERTEX_SHADER( spritecard_vs11 );
}
#endif
}
else
{
if ( nSplineType )
{
DECLARE_DYNAMIC_VERTEX_SHADER( splinecard_vs20 );
SET_DYNAMIC_VERTEX_SHADER( splinecard_vs20 );
}
else
{
DECLARE_DYNAMIC_VERTEX_SHADER( spritecard_vs20 );
SET_DYNAMIC_VERTEX_SHADER_COMBO( ORIENTATION, nOrientation );
SET_DYNAMIC_VERTEX_SHADER( spritecard_vs20 );
}
}
}
Draw( );
}
END_SHADER
| 35.152577 | 204 | 0.732301 | cstom4994 |
e1951ff900b94c2a88f1985b1d765e3dbfba4cda | 15,051 | cpp | C++ | third_party/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp | 5GApp/tensorflow | ca87089f9e0073bad9fc999ce9c318f661d2e425 | [
"Apache-2.0"
] | 1 | 2019-12-23T20:23:43.000Z | 2019-12-23T20:23:43.000Z | third_party/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp | 5GApp/tensorflow | ca87089f9e0073bad9fc999ce9c318f661d2e425 | [
"Apache-2.0"
] | null | null | null | third_party/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp | 5GApp/tensorflow | ca87089f9e0073bad9fc999ce9c318f661d2e425 | [
"Apache-2.0"
] | 1 | 2020-04-22T01:47:46.000Z | 2020-04-22T01:47:46.000Z | //===- LowerUniformRealMath.cpp ------------------------------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "UniformKernelUtils.h"
#include "mlir/Dialect/FxpMathOps/FxpMathOps.h"
#include "mlir/Dialect/FxpMathOps/Passes.h"
#include "mlir/Dialect/StandardOps/Ops.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
using namespace mlir::fxpmath;
using namespace mlir::fxpmath::detail;
using namespace mlir::quant;
namespace {
struct LowerUniformRealMathPass
: public FunctionPass<LowerUniformRealMathPass> {
void runOnFunction() override;
};
struct LowerUniformCastsPass : public FunctionPass<LowerUniformCastsPass> {
void runOnFunction() override;
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Dequantize
//===----------------------------------------------------------------------===//
static ValuePtr emitUniformPerLayerDequantize(Location loc, ValuePtr input,
UniformQuantizedType elementType,
PatternRewriter &rewriter) {
// Pre-conditions.
if (!elementType.isSigned()) {
// TODO: Support unsigned storage type.
emitWarning(loc, "unimplemented: dequantize signed uniform");
return nullptr;
}
Type storageType = elementType.castToStorageType(input->getType());
Type realType = elementType.castToExpressedType(input->getType());
Type intermediateType =
castElementType(storageType, IntegerType::get(32, rewriter.getContext()));
assert(storageType && "cannot cast to storage type");
assert(realType && "cannot cast to expressed type");
// Cast to storage type.
input = rewriter.create<StorageCastOp>(loc, storageType, input);
// Promote to intermediate type.
input = rewriter.create<ConvertISOp>(loc, intermediateType, input);
// Apply zero-point offset.
if (elementType.getZeroPoint() != 0) {
ValuePtr negZeroPointConst = rewriter.create<ConstantOp>(
loc, broadcastScalarConstIntValue(intermediateType,
-elementType.getZeroPoint()));
input = rewriter.create<AddIOp>(loc, input, negZeroPointConst);
}
// Convert to float.
input = rewriter.create<ConvertISToFOp>(loc, realType, input);
// Mul by scale.
ValuePtr scaleConst = rewriter.create<ConstantOp>(
loc, broadcastScalarConstFloatValue(realType,
APFloat(elementType.getScale())));
return rewriter.create<MulFOp>(loc, input, scaleConst);
}
static ValuePtr
emitUniformPerAxisDequantize(Location loc, ValuePtr input,
UniformQuantizedPerAxisType elementType,
PatternRewriter &rewriter) {
// TODO: Support per-axis dequantize.
rewriter.getContext()->getDiagEngine().emit(loc, DiagnosticSeverity::Warning)
<< "unimplemented: per-axis uniform dequantization";
return nullptr;
}
static ValuePtr emitDequantize(Location loc, ValuePtr input,
PatternRewriter &rewriter) {
Type inputType = input->getType();
QuantizedType qElementType =
QuantizedType::getQuantizedElementType(inputType);
if (auto uperLayerElementType =
qElementType.dyn_cast_or_null<UniformQuantizedType>()) {
return emitUniformPerLayerDequantize(loc, input, uperLayerElementType,
rewriter);
} else if (auto uperAxisElementType =
qElementType.dyn_cast_or_null<UniformQuantizedPerAxisType>()) {
return emitUniformPerAxisDequantize(loc, input, uperAxisElementType,
rewriter);
} else {
return nullptr;
}
}
namespace {
struct UniformDequantizePattern : public OpRewritePattern<DequantizeCastOp> {
using OpRewritePattern<DequantizeCastOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(DequantizeCastOp op,
PatternRewriter &rewriter) const override {
Type inputType = op.arg()->getType();
Type outputType = op.getResult()->getType();
QuantizedType inputElementType =
QuantizedType::getQuantizedElementType(inputType);
Type expressedOutputType = inputElementType.castToExpressedType(inputType);
if (expressedOutputType != outputType) {
// Not a valid uniform cast.
return matchFailure();
}
ValuePtr dequantizedValue = emitDequantize(op.getLoc(), op.arg(), rewriter);
if (!dequantizedValue) {
return matchFailure();
}
rewriter.replaceOp(op, dequantizedValue);
return matchSuccess();
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Elementwise add
//===----------------------------------------------------------------------===//
static LogicalResult
tryRewriteAffineAddEwIsomorphicSigned(const UniformBinaryOpInfo &info,
PatternRewriter &rewriter) {
if (!info.resultType.isSigned() || info.lhsType != info.resultType ||
info.rhsType != info.resultType) {
return failure();
}
// Choose a byte aligned intermediate width big enough to perform the
// calculation without overflow.
// TODO: This should probably be made just big enough to avoid overflow and
// leave the downstream tooling to decide how to align that to machine
// word sizes.
unsigned intermediateWidth =
info.resultType.getStorageTypeIntegralWidth() <= 8 ? 16 : 32;
IntegerType intermediateElementType =
IntegerType::get(intermediateWidth, rewriter.getContext());
Type intermediateType =
castElementType(info.resultStorageType, intermediateElementType);
// Cast operands to storage type.
ValuePtr lhsValue = rewriter
.create<StorageCastOp>(info.op->getLoc(),
info.lhsStorageType, info.lhs)
.getResult();
ValuePtr rhsValue = rewriter
.create<StorageCastOp>(info.op->getLoc(),
info.rhsStorageType, info.rhs)
.getResult();
// Cast to the intermediate sized type.
lhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType,
lhsValue);
rhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType,
rhsValue);
// Add.
ValuePtr resultValue =
rewriter.create<AddIOp>(info.op->getLoc(), lhsValue, rhsValue);
// Zero point offset adjustment.
// result = (lhs - zp) + (rhs - zp) + zp
// zpOffset = -zp
int zpOffset = -1 * info.resultType.getZeroPoint();
if (zpOffset != 0) {
ValuePtr zpOffsetConst = rewriter.create<ConstantOp>(
info.op->getLoc(),
broadcastScalarConstIntValue(intermediateType, zpOffset));
resultValue =
rewriter.create<AddIOp>(info.op->getLoc(), resultValue, zpOffsetConst);
}
// Clamp.
auto clampMinMax = info.getClampMinMax(intermediateElementType);
resultValue = rewriter.create<ClampISOp>(
info.op->getLoc(), resultValue, clampMinMax.first, clampMinMax.second);
// Convert back to original type.
resultValue = rewriter.create<ConvertISOp>(
info.op->getLoc(), info.resultStorageType, resultValue);
// Cast back for new result.
rewriter.replaceOpWithNewOp<StorageCastOp>(
info.op, info.getQuantizedResultType(), resultValue);
return success();
}
//===----------------------------------------------------------------------===//
// Elementwise mul
//===----------------------------------------------------------------------===//
static LogicalResult
tryRewriteAffineMulEwSigned(const UniformBinaryOpInfo &info,
PatternRewriter &rewriter) {
if (!info.resultType.isSigned()) {
return failure();
}
double outputMultiplierReal = info.lhsType.getScale() *
info.rhsType.getScale() /
info.resultType.getScale();
if (outputMultiplierReal > 1.0) {
info.op->emitWarning(
"unimplemented: cannot multiply with multiplier > 1.0");
return failure();
}
// TODO: Choose an appropriate intermediate width for muls > 8 bits to
// avoid overflow.
unsigned intermediateWidth = 32;
IntegerType intermediateElementType =
IntegerType::get(intermediateWidth, rewriter.getContext());
Type intermediateType =
castElementType(info.resultStorageType, intermediateElementType);
// Cast operands to storage type.
ValuePtr lhsValue = rewriter
.create<StorageCastOp>(info.op->getLoc(),
info.lhsStorageType, info.lhs)
.getResult();
ValuePtr rhsValue = rewriter
.create<StorageCastOp>(info.op->getLoc(),
info.rhsStorageType, info.rhs)
.getResult();
// Cast to the intermediate sized type.
lhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType,
lhsValue);
rhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType,
rhsValue);
// Apply argument zeroPoints.
if (info.lhsType.getZeroPoint() != 0) {
ValuePtr zpOffsetConst = rewriter.create<ConstantOp>(
info.op->getLoc(), broadcastScalarConstIntValue(
intermediateType, -info.lhsType.getZeroPoint()));
lhsValue =
rewriter.create<AddIOp>(info.op->getLoc(), lhsValue, zpOffsetConst);
}
if (info.rhsType.getZeroPoint() != 0) {
ValuePtr zpOffsetConst = rewriter.create<ConstantOp>(
info.op->getLoc(), broadcastScalarConstIntValue(
intermediateType, -info.rhsType.getZeroPoint()));
rhsValue =
rewriter.create<AddIOp>(info.op->getLoc(), rhsValue, zpOffsetConst);
}
// Mul.
ValuePtr resultValue =
rewriter.create<MulIOp>(info.op->getLoc(), lhsValue, rhsValue);
// Scale output.
QuantizedMultiplierSmallerThanOneExp outputMultiplier(outputMultiplierReal);
resultValue = rewriter.create<VecScalarSaturatingRoundingDoublingHighMulISOp>(
info.op->getLoc(), resultValue,
IntegerAttr::get(intermediateElementType, outputMultiplier.multiplier));
resultValue = rewriter.create<RoundingDivideByPotISOp>(
info.op->getLoc(), resultValue,
IntegerAttr::get(intermediateElementType, -outputMultiplier.exponent));
// Zero point offset adjustment.
if (info.resultType.getZeroPoint() != 0) {
ValuePtr zpOffsetConst = rewriter.create<ConstantOp>(
info.op->getLoc(),
broadcastScalarConstIntValue(intermediateType,
info.resultType.getZeroPoint()));
resultValue =
rewriter.create<AddIOp>(info.op->getLoc(), resultValue, zpOffsetConst);
}
// Clamp.
auto clampMinMax = info.getClampMinMax(intermediateElementType);
resultValue = rewriter.create<ClampISOp>(
info.op->getLoc(), resultValue, clampMinMax.first, clampMinMax.second);
// Convert back to original type.
resultValue = rewriter.create<ConvertISOp>(
info.op->getLoc(), info.resultStorageType, resultValue);
// Cast back for new result.
rewriter.replaceOpWithNewOp<StorageCastOp>(
info.op, info.getQuantizedResultType(), resultValue);
return success();
}
namespace {
struct UniformRealAddEwPattern : public OpRewritePattern<RealAddEwOp> {
using OpRewritePattern<RealAddEwOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(RealAddEwOp op,
PatternRewriter &rewriter) const override {
const UniformBinaryOpInfo info(op, op.lhs(), op.rhs(), op.clamp_min(),
op.clamp_max());
if (!info.isValid()) {
return matchFailure();
}
// Try all of the permutations we support.
if (succeeded(tryRewriteAffineAddEwIsomorphicSigned(info, rewriter))) {
return matchSuccess();
}
return matchFailure();
}
};
struct UniformRealMulEwPattern : public OpRewritePattern<RealMulEwOp> {
using OpRewritePattern<RealMulEwOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(RealMulEwOp op,
PatternRewriter &rewriter) const override {
const UniformBinaryOpInfo info(op, op.lhs(), op.rhs(), op.clamp_min(),
op.clamp_max());
if (!info.isValid()) {
return matchFailure();
}
// Try all of the permutations we support.
if (succeeded(tryRewriteAffineMulEwSigned(info, rewriter))) {
return matchSuccess();
}
return matchFailure();
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// LowerUniformRealMath pass
//===----------------------------------------------------------------------===//
void LowerUniformRealMathPass::runOnFunction() {
auto fn = getFunction();
OwningRewritePatternList patterns;
auto *context = &getContext();
patterns.insert<UniformRealAddEwPattern, UniformRealMulEwPattern>(context);
applyPatternsGreedily(fn, patterns);
}
OpPassBase<FuncOp> *mlir::fxpmath::createLowerUniformRealMathPass() {
return new LowerUniformRealMathPass();
}
static PassRegistration<LowerUniformRealMathPass> lowerUniformRealMathPass(
"fxpmath-lower-uniform-real-math",
"Lowers uniform-quantized real math ops to integer arithmetic.");
//===----------------------------------------------------------------------===//
// LowerUniformCasts pass
//===----------------------------------------------------------------------===//
void LowerUniformCastsPass::runOnFunction() {
auto fn = getFunction();
OwningRewritePatternList patterns;
auto *context = &getContext();
patterns.insert<UniformDequantizePattern>(context);
applyPatternsGreedily(fn, patterns);
}
OpPassBase<FuncOp> *mlir::fxpmath::createLowerUniformCastsPass() {
return new LowerUniformCastsPass();
}
static PassRegistration<LowerUniformCastsPass>
lowerUniformCastsPass("fxpmath-lower-uniform-casts",
"Lowers uniform-quantized casts.");
| 37.347395 | 80 | 0.626669 | 5GApp |
e1966c6c4425affb914d7da7a176e9cf8053850b | 30,144 | cpp | C++ | src/frameworks/av/media/libstagefright/codecs/amrwb/src/mime_io.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | src/frameworks/av/media/libstagefright/codecs/amrwb/src/mime_io.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | src/frameworks/av/media/libstagefright/codecs/amrwb/src/mime_io.cpp | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | 12 | 2020-04-15T11:37:33.000Z | 2021-09-13T13:19:04.000Z | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.173
ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
Available from http://www.3gpp.org
(C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
------------------------------------------------------------------------------
Pathname: ./src/mime_io.cpp
Date: 05/07/2007
------------------------------------------------------------------------------
REVISION HISTORY
Description:
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
[input_variable_name] = [description of the input to module, its type
definition, and length (when applicable)]
Local Stores/Buffers/Pointers Needed:
[local_store_name] = [description of the local store, its type
definition, and length (when applicable)]
[local_buffer_name] = [description of the local buffer, its type
definition, and length (when applicable)]
[local_ptr_name] = [description of the local pointer, its type
definition, and length (when applicable)]
Global Stores/Buffers/Pointers Needed:
[global_store_name] = [description of the global store, its type
definition, and length (when applicable)]
[global_buffer_name] = [description of the global buffer, its type
definition, and length (when applicable)]
[global_ptr_name] = [description of the global pointer, its type
definition, and length (when applicable)]
Outputs:
[return_variable_name] = [description of data/pointer returned
by module, its type definition, and length
(when applicable)]
Pointers and Buffers Modified:
[variable_bfr_ptr] points to the [describe where the
variable_bfr_ptr points to, its type definition, and length
(when applicable)]
[variable_bfr] contents are [describe the new contents of
variable_bfr]
Local Stores Modified:
[local_store_name] = [describe new contents, its type
definition, and length (when applicable)]
Global Stores Modified:
[global_store_name] = [describe new contents, its type
definition, and length (when applicable)]
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
[Describe what the module does by using the variable names
listed in the Input and Output Definitions Section above.]
------------------------------------------------------------------------------
REQUIREMENTS
[List requirements to be satisfied by this module.]
------------------------------------------------------------------------------
REFERENCES
[List all references used in designing this module.]
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
RESOURCES USED
STACK USAGE:
DATA MEMORY USED: x words
PROGRAM MEMORY USED: x words
CLOCK CYCLES:
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "pv_amr_wb_type_defs.h"
#include "pvamrwbdecoder_api.h"
#include "pvamrwbdecoder.h"
#include "pvamrwbdecoder_mem_funcs.h"
#include "pvamrwbdecoder_cnst.h"
#include "dtx.h"
#include "mime_io.h"
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/
#define MRSID 9
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/
const uint8 toc_byte[16] = {0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C,
0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C
};
/* number of speech bits for all modes */
const int16 unpacked_size[16] =
{
132, 177, 253, 285,
317, 365, 397, 461,
477, 35, 0, 0,
0, 0, 0, 0
};
/* size of packed frame for each mode, excluding TOC byte */
const int16 packed_size[16] = {17, 23, 32, 36, 40, 46, 50, 58,
60, 5, 0, 0, 0, 0, 0, 0
};
/* number of unused speech bits in packed format for each mode */
const int16 unused_size[16] = {4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0};
/* sorting tables for all modes */
const int16 sort_660[132] =
{
0, 5, 6, 7, 61, 84, 107, 130, 62, 85,
8, 4, 37, 38, 39, 40, 58, 81, 104, 127,
60, 83, 106, 129, 108, 131, 128, 41, 42, 80,
126, 1, 3, 57, 103, 82, 105, 59, 2, 63,
109, 110, 86, 19, 22, 23, 64, 87, 18, 20,
21, 17, 13, 88, 43, 89, 65, 111, 14, 24,
25, 26, 27, 28, 15, 16, 44, 90, 66, 112,
9, 11, 10, 12, 67, 113, 29, 30, 31, 32,
34, 33, 35, 36, 45, 51, 68, 74, 91, 97,
114, 120, 46, 69, 92, 115, 52, 75, 98, 121,
47, 70, 93, 116, 53, 76, 99, 122, 48, 71,
94, 117, 54, 77, 100, 123, 49, 72, 95, 118,
55, 78, 101, 124, 50, 73, 96, 119, 56, 79,
102, 125
};
const int16 sort_885[177] =
{
0, 4, 6, 7, 5, 3, 47, 48, 49, 112,
113, 114, 75, 106, 140, 171, 80, 111, 145, 176,
77, 108, 142, 173, 78, 109, 143, 174, 79, 110,
144, 175, 76, 107, 141, 172, 50, 115, 51, 2,
1, 81, 116, 146, 19, 21, 12, 17, 18, 20,
16, 25, 13, 10, 14, 24, 23, 22, 26, 8,
15, 52, 117, 31, 82, 147, 9, 33, 11, 83,
148, 53, 118, 28, 27, 84, 149, 34, 35, 29,
46, 32, 30, 54, 119, 37, 36, 39, 38, 40,
85, 150, 41, 42, 43, 44, 45, 55, 60, 65,
70, 86, 91, 96, 101, 120, 125, 130, 135, 151,
156, 161, 166, 56, 87, 121, 152, 61, 92, 126,
157, 66, 97, 131, 162, 71, 102, 136, 167, 57,
88, 122, 153, 62, 93, 127, 158, 67, 98, 132,
163, 72, 103, 137, 168, 58, 89, 123, 154, 63,
94, 128, 159, 68, 99, 133, 164, 73, 104, 138,
169, 59, 90, 124, 155, 64, 95, 129, 160, 69,
100, 134, 165, 74, 105, 139, 170
};
const int16 sort_1265[253] =
{
0, 4, 6, 93, 143, 196, 246, 7, 5, 3,
47, 48, 49, 50, 51, 150, 151, 152, 153, 154,
94, 144, 197, 247, 99, 149, 202, 252, 96, 146,
199, 249, 97, 147, 200, 250, 100, 203, 98, 148,
201, 251, 95, 145, 198, 248, 52, 2, 1, 101,
204, 155, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
156, 31, 102, 205, 9, 33, 11, 103, 206, 54,
157, 28, 27, 104, 207, 34, 35, 29, 46, 32,
30, 55, 158, 37, 36, 39, 38, 40, 105, 208,
41, 42, 43, 44, 45, 56, 106, 159, 209, 57,
66, 75, 84, 107, 116, 125, 134, 160, 169, 178,
187, 210, 219, 228, 237, 58, 108, 161, 211, 62,
112, 165, 215, 67, 117, 170, 220, 71, 121, 174,
224, 76, 126, 179, 229, 80, 130, 183, 233, 85,
135, 188, 238, 89, 139, 192, 242, 59, 109, 162,
212, 63, 113, 166, 216, 68, 118, 171, 221, 72,
122, 175, 225, 77, 127, 180, 230, 81, 131, 184,
234, 86, 136, 189, 239, 90, 140, 193, 243, 60,
110, 163, 213, 64, 114, 167, 217, 69, 119, 172,
222, 73, 123, 176, 226, 78, 128, 181, 231, 82,
132, 185, 235, 87, 137, 190, 240, 91, 141, 194,
244, 61, 111, 164, 214, 65, 115, 168, 218, 70,
120, 173, 223, 74, 124, 177, 227, 79, 129, 182,
232, 83, 133, 186, 236, 88, 138, 191, 241, 92,
142, 195, 245
};
const int16 sort_1425[285] =
{
0, 4, 6, 101, 159, 220, 278, 7, 5, 3,
47, 48, 49, 50, 51, 166, 167, 168, 169, 170,
102, 160, 221, 279, 107, 165, 226, 284, 104, 162,
223, 281, 105, 163, 224, 282, 108, 227, 106, 164,
225, 283, 103, 161, 222, 280, 52, 2, 1, 109,
228, 171, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
172, 31, 110, 229, 9, 33, 11, 111, 230, 54,
173, 28, 27, 112, 231, 34, 35, 29, 46, 32,
30, 55, 174, 37, 36, 39, 38, 40, 113, 232,
41, 42, 43, 44, 45, 56, 114, 175, 233, 62,
120, 181, 239, 75, 133, 194, 252, 57, 115, 176,
234, 63, 121, 182, 240, 70, 128, 189, 247, 76,
134, 195, 253, 83, 141, 202, 260, 92, 150, 211,
269, 84, 142, 203, 261, 93, 151, 212, 270, 85,
143, 204, 262, 94, 152, 213, 271, 86, 144, 205,
263, 95, 153, 214, 272, 64, 122, 183, 241, 77,
135, 196, 254, 65, 123, 184, 242, 78, 136, 197,
255, 87, 145, 206, 264, 96, 154, 215, 273, 58,
116, 177, 235, 66, 124, 185, 243, 71, 129, 190,
248, 79, 137, 198, 256, 88, 146, 207, 265, 97,
155, 216, 274, 59, 117, 178, 236, 67, 125, 186,
244, 72, 130, 191, 249, 80, 138, 199, 257, 89,
147, 208, 266, 98, 156, 217, 275, 60, 118, 179,
237, 68, 126, 187, 245, 73, 131, 192, 250, 81,
139, 200, 258, 90, 148, 209, 267, 99, 157, 218,
276, 61, 119, 180, 238, 69, 127, 188, 246, 74,
132, 193, 251, 82, 140, 201, 259, 91, 149, 210,
268, 100, 158, 219, 277
};
const int16 sort_1585[317] =
{
0, 4, 6, 109, 175, 244, 310, 7, 5, 3,
47, 48, 49, 50, 51, 182, 183, 184, 185, 186,
110, 176, 245, 311, 115, 181, 250, 316, 112, 178,
247, 313, 113, 179, 248, 314, 116, 251, 114, 180,
249, 315, 111, 177, 246, 312, 52, 2, 1, 117,
252, 187, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
188, 31, 118, 253, 9, 33, 11, 119, 254, 54,
189, 28, 27, 120, 255, 34, 35, 29, 46, 32,
30, 55, 190, 37, 36, 39, 38, 40, 121, 256,
41, 42, 43, 44, 45, 56, 122, 191, 257, 63,
129, 198, 264, 76, 142, 211, 277, 89, 155, 224,
290, 102, 168, 237, 303, 57, 123, 192, 258, 70,
136, 205, 271, 83, 149, 218, 284, 96, 162, 231,
297, 62, 128, 197, 263, 75, 141, 210, 276, 88,
154, 223, 289, 101, 167, 236, 302, 58, 124, 193,
259, 71, 137, 206, 272, 84, 150, 219, 285, 97,
163, 232, 298, 59, 125, 194, 260, 64, 130, 199,
265, 67, 133, 202, 268, 72, 138, 207, 273, 77,
143, 212, 278, 80, 146, 215, 281, 85, 151, 220,
286, 90, 156, 225, 291, 93, 159, 228, 294, 98,
164, 233, 299, 103, 169, 238, 304, 106, 172, 241,
307, 60, 126, 195, 261, 65, 131, 200, 266, 68,
134, 203, 269, 73, 139, 208, 274, 78, 144, 213,
279, 81, 147, 216, 282, 86, 152, 221, 287, 91,
157, 226, 292, 94, 160, 229, 295, 99, 165, 234,
300, 104, 170, 239, 305, 107, 173, 242, 308, 61,
127, 196, 262, 66, 132, 201, 267, 69, 135, 204,
270, 74, 140, 209, 275, 79, 145, 214, 280, 82,
148, 217, 283, 87, 153, 222, 288, 92, 158, 227,
293, 95, 161, 230, 296, 100, 166, 235, 301, 105,
171, 240, 306, 108, 174, 243, 309
};
const int16 sort_1825[365] =
{
0, 4, 6, 121, 199, 280, 358, 7, 5, 3,
47, 48, 49, 50, 51, 206, 207, 208, 209, 210,
122, 200, 281, 359, 127, 205, 286, 364, 124, 202,
283, 361, 125, 203, 284, 362, 128, 287, 126, 204,
285, 363, 123, 201, 282, 360, 52, 2, 1, 129,
288, 211, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
212, 31, 130, 289, 9, 33, 11, 131, 290, 54,
213, 28, 27, 132, 291, 34, 35, 29, 46, 32,
30, 55, 214, 37, 36, 39, 38, 40, 133, 292,
41, 42, 43, 44, 45, 56, 134, 215, 293, 198,
299, 136, 120, 138, 60, 279, 58, 62, 357, 139,
140, 295, 156, 57, 219, 297, 63, 217, 137, 170,
300, 222, 64, 106, 61, 78, 294, 92, 142, 141,
135, 221, 296, 301, 343, 59, 298, 184, 329, 315,
220, 216, 265, 251, 218, 237, 352, 223, 157, 86,
171, 87, 164, 351, 111, 302, 65, 178, 115, 323,
72, 192, 101, 179, 93, 73, 193, 151, 337, 309,
143, 274, 69, 324, 165, 150, 97, 338, 110, 310,
330, 273, 68, 107, 175, 245, 114, 79, 113, 189,
246, 259, 174, 71, 185, 96, 344, 100, 322, 83,
334, 316, 333, 252, 161, 348, 147, 82, 269, 232,
260, 308, 353, 347, 163, 231, 306, 320, 188, 270,
146, 177, 266, 350, 256, 85, 149, 116, 191, 160,
238, 258, 336, 305, 255, 88, 224, 99, 339, 230,
228, 227, 272, 242, 241, 319, 233, 311, 102, 74,
180, 275, 66, 194, 152, 325, 172, 247, 244, 261,
117, 158, 166, 354, 75, 144, 108, 312, 94, 186,
303, 80, 234, 89, 195, 112, 340, 181, 345, 317,
326, 276, 239, 167, 118, 313, 70, 355, 327, 253,
190, 176, 271, 104, 98, 153, 103, 90, 76, 267,
277, 248, 225, 262, 182, 84, 154, 235, 335, 168,
331, 196, 341, 249, 162, 307, 148, 349, 263, 321,
257, 243, 229, 356, 159, 119, 67, 187, 173, 145,
240, 77, 304, 332, 314, 342, 109, 254, 81, 278,
105, 91, 346, 318, 183, 250, 197, 328, 95, 155,
169, 268, 226, 236, 264
};
const int16 sort_1985[397] =
{
0, 4, 6, 129, 215, 304, 390, 7, 5, 3,
47, 48, 49, 50, 51, 222, 223, 224, 225, 226,
130, 216, 305, 391, 135, 221, 310, 396, 132, 218,
307, 393, 133, 219, 308, 394, 136, 311, 134, 220,
309, 395, 131, 217, 306, 392, 52, 2, 1, 137,
312, 227, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
228, 31, 138, 313, 9, 33, 11, 139, 314, 54,
229, 28, 27, 140, 315, 34, 35, 29, 46, 32,
30, 55, 230, 37, 36, 39, 38, 40, 141, 316,
41, 42, 43, 44, 45, 56, 142, 231, 317, 63,
73, 92, 340, 82, 324, 149, 353, 159, 334, 165,
338, 178, 163, 254, 77, 168, 257, 153, 343, 57,
248, 238, 79, 252, 166, 67, 80, 201, 101, 267,
143, 164, 341, 255, 339, 187, 376, 318, 78, 328,
362, 115, 232, 242, 253, 290, 276, 62, 58, 158,
68, 93, 179, 319, 148, 169, 154, 72, 385, 329,
333, 344, 102, 83, 144, 233, 323, 124, 243, 192,
354, 237, 64, 247, 202, 209, 150, 116, 335, 268,
239, 299, 188, 196, 298, 94, 195, 258, 123, 363,
384, 109, 325, 371, 170, 370, 84, 110, 295, 180,
74, 210, 191, 106, 291, 205, 367, 381, 377, 206,
355, 122, 119, 120, 383, 160, 105, 108, 277, 380,
294, 284, 285, 345, 208, 269, 249, 366, 386, 300,
297, 259, 125, 369, 197, 97, 194, 286, 211, 281,
280, 183, 372, 87, 155, 283, 59, 348, 327, 184,
76, 111, 330, 203, 349, 69, 98, 152, 145, 189,
66, 320, 337, 173, 358, 251, 198, 174, 263, 262,
126, 241, 193, 88, 388, 117, 95, 387, 112, 359,
287, 244, 103, 272, 301, 171, 162, 234, 273, 127,
373, 181, 292, 85, 378, 302, 121, 107, 364, 346,
356, 212, 278, 213, 65, 382, 288, 207, 113, 175,
99, 296, 374, 368, 199, 260, 185, 336, 331, 161,
270, 264, 250, 240, 75, 350, 151, 60, 89, 321,
156, 274, 360, 326, 70, 282, 167, 146, 352, 81,
91, 389, 266, 245, 177, 235, 190, 256, 204, 342,
128, 118, 303, 104, 379, 182, 114, 375, 200, 96,
293, 172, 214, 365, 279, 86, 289, 351, 347, 357,
261, 186, 176, 271, 90, 100, 147, 322, 275, 361,
71, 332, 61, 265, 157, 246, 236
};
const int16 sort_2305[461] =
{
0, 4, 6, 145, 247, 352, 454, 7, 5, 3,
47, 48, 49, 50, 51, 254, 255, 256, 257, 258,
146, 248, 353, 455, 151, 253, 358, 460, 148, 250,
355, 457, 149, 251, 356, 458, 152, 359, 150, 252,
357, 459, 147, 249, 354, 456, 52, 2, 1, 153,
360, 259, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
260, 31, 154, 361, 9, 33, 11, 155, 362, 54,
261, 28, 27, 156, 363, 34, 35, 29, 46, 32,
30, 55, 262, 37, 36, 39, 38, 40, 157, 364,
41, 42, 43, 44, 45, 56, 158, 263, 365, 181,
192, 170, 79, 57, 399, 90, 159, 297, 377, 366,
275, 68, 183, 388, 286, 194, 299, 92 , 70, 182,
401, 172, 59, 91, 58, 400, 368, 161, 81, 160,
264, 171, 80, 389, 390, 378, 379, 193, 298, 69,
266, 265, 367, 277, 288, 276, 287, 184, 60, 195,
82, 93, 71, 369, 402, 173, 162, 444, 300, 391,
98, 76, 278, 61, 267, 374, 135, 411, 167, 102,
380, 200, 87, 178, 65, 94, 204, 124, 72, 342,
189, 305, 381, 396, 433, 301, 226, 407, 289, 237,
113, 215, 185, 128, 309, 403, 116, 320, 196, 331,
370, 422, 174, 64, 392, 83, 425, 219, 134, 188,
432, 112, 427, 139, 279, 163, 436, 208, 447, 218,
236, 229, 97, 294, 385, 230, 166, 268, 177, 443,
225, 426, 101, 272, 138, 127, 290, 117, 347, 199,
414, 95, 140, 240, 410, 395, 209, 129, 283, 346,
105, 241, 437, 86, 308, 448, 203, 345, 186, 107,
220, 415, 334, 319, 106, 313, 118, 123, 73, 207,
421, 214, 384, 373, 438, 62, 371, 341, 75, 449,
168, 323, 164, 242, 416, 324, 304, 197, 335, 404,
271, 63, 191, 325, 96, 169, 231, 280, 312, 187,
406, 84, 201, 100, 67, 382, 175, 336, 202, 330,
269, 393, 376, 383, 293, 307, 409, 179, 285, 314,
302, 372, 398, 190, 180, 89, 99, 103, 232, 78,
88, 77, 136, 387, 165, 198, 394, 125, 176, 428,
74, 375, 238, 227, 66, 273, 282, 141, 306, 412,
114, 85, 130, 348, 119, 291, 296, 386, 233, 397,
303, 405, 284, 445, 423, 221, 210, 205, 450, 108,
274, 434, 216, 343, 337, 142, 243, 321, 408, 451,
310, 292, 120, 109, 281, 439, 270, 429, 332, 295,
418, 211, 315, 222, 326, 131, 430, 244, 327, 349,
417, 316, 143, 338, 440, 234, 110, 212, 452, 245,
121, 419, 350, 223, 132, 441, 328, 413, 317, 339,
126, 104, 137, 446, 344, 239, 435, 115, 333, 206,
322, 217, 228, 424, 453, 311, 351, 111, 442, 224,
213, 122, 431, 340, 235, 246, 133, 144, 420, 329,
318
};
const int16 sort_2385[477] =
{
0, 4, 6, 145, 251, 360, 466, 7, 5, 3,
47, 48, 49, 50, 51, 262, 263, 264, 265, 266,
146, 252, 361, 467, 151, 257, 366, 472, 148, 254,
363, 469, 149, 255, 364, 470, 156, 371, 150, 256,
365, 471, 147, 253, 362, 468, 52, 2, 1, 157,
372, 267, 19, 21, 12, 17, 18, 20, 16, 25,
13, 10, 14, 24, 23, 22, 26, 8, 15, 53,
268, 31, 152, 153, 154, 155, 258, 259, 260, 261,
367, 368, 369, 370, 473, 474, 475, 476, 158, 373,
9, 33, 11, 159, 374, 54, 269, 28, 27, 160,
375, 34, 35, 29, 46, 32, 30, 55, 270, 37,
36, 39, 38, 40, 161, 376, 41, 42, 43, 44,
45, 56, 162, 271, 377, 185, 196, 174, 79, 57,
411, 90, 163, 305, 389, 378, 283, 68, 187, 400,
294, 198, 307, 92, 70, 186, 413, 176, 59, 91,
58, 412, 380, 165, 81, 164, 272, 175, 80, 401,
402, 390, 391, 197, 306, 69, 274, 273, 379, 285,
296, 284, 295, 188, 60, 199, 82, 93, 71, 381,
414, 177, 166, 456, 308, 403, 98, 76, 286, 61,
275, 386, 135, 423, 171, 102, 392, 204, 87, 182,
65, 94, 208, 124, 72, 350, 193, 313, 393, 408,
445, 309, 230, 419, 297, 241, 113, 219, 189, 128,
317, 415, 116, 328, 200, 339, 382, 434, 178, 64,
404, 83, 437, 223, 134, 192, 444, 112, 439, 139,
287, 167, 448, 212, 459, 222, 240, 233, 97, 302,
397, 234, 170, 276, 181, 455, 229, 438, 101, 280,
138, 127, 298, 117, 355, 203, 426, 95, 140, 244,
422, 407, 213, 129, 291, 354, 105, 245, 449, 86,
316, 460, 207, 353, 190, 107, 224, 427, 342, 327,
106, 321, 118, 123, 73, 211, 433, 218, 396, 385,
450, 62, 383, 349, 75, 461, 172, 331, 168, 246,
428, 332, 312, 201, 343, 416, 279, 63, 195, 333,
96, 173, 235, 288, 320, 191, 418, 84, 205, 100,
67, 394, 179, 344, 206, 338, 277, 405, 388, 395,
301, 315, 421, 183, 293, 322, 310, 384, 410, 194,
184, 89, 99, 103, 236, 78, 88, 77, 136, 399,
169, 202, 406, 125, 180, 440, 74, 387, 242, 231,
66, 281, 290, 141, 314, 424, 114, 85, 130, 356,
119, 299, 304, 398, 237, 409, 311, 417, 292, 457,
435, 225, 214, 209, 462, 108, 282, 446, 220, 351,
345, 142, 247, 329, 420, 463, 318, 300, 120, 109,
289, 451, 278, 441, 340, 303, 430, 215, 323, 226,
334, 131, 442, 248, 335, 357, 429, 324, 143, 346,
452, 238, 110, 216, 464, 249, 121, 431, 358, 227,
132, 453, 336, 425, 325, 347, 126, 104, 137, 458,
352, 243, 447, 115, 341, 210, 330, 221, 232, 436,
465, 319, 359, 111, 454, 228, 217, 122, 443, 348,
239, 250, 133, 144, 432, 337, 326
};
const int16 sort_SID[35] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34
};
/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
void mime_unsorting(uint8 unsorted_bits[],
int16 sorted_bits_into_int16[],
int16 * frame_type,
int16 * mode,
uint8 quality,
RX_State_wb *st)
{
int16 i;
int16 j;
uint8 temp = 0;
uint8 *unsorted_bits_ptr = (uint8*)unsorted_bits;
/* pointer table for bit sorting tables */
const int16 *AmrWbSortingTables[16] =
{
sort_660, sort_885, sort_1265, sort_1425,
sort_1585, sort_1825, sort_1985, sort_2305,
sort_2385, sort_SID, NULL, NULL,
NULL, NULL, NULL, NULL
};
const int16 * pt_AmrWbSortingTables = AmrWbSortingTables[*mode];
/* clear compressed speech bit buffer */
pv_memset(sorted_bits_into_int16,
0,
unpacked_size[*mode]*sizeof(*sorted_bits_into_int16));
/* unpack and unsort speech or SID bits */
for (i = unpacked_size[*mode] >> 3; i != 0; i--)
{
temp = *(unsorted_bits_ptr++);
for (j = 2; j != 0; j--)
{
switch (temp & 0xf0)
{
case 0xf0:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0xe0:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
break;
case 0xd0:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0xc0:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables += 2;
break;
case 0xb0:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0xa0:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
break;
case 0x90:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables += 2;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0x80:
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables += 3;
break;
case 0x70:
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0x60:
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
break;
case 0x50:
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0x40:
pt_AmrWbSortingTables++;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables += 2;
break;
case 0x30:
pt_AmrWbSortingTables += 2;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
case 0x20:
pt_AmrWbSortingTables += 2;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
pt_AmrWbSortingTables++;
break;
case 0x10:
pt_AmrWbSortingTables += 3;
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
break;
default:
pt_AmrWbSortingTables += 4;
break;
}
temp <<= 4;
}
}
if (unpacked_size[*mode] % 4)
{
temp <<= 1;
if (temp & 0x80)
{
sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
}
}
/* set frame type */
switch (*mode)
{
case MODE_7k:
case MODE_9k:
case MODE_12k:
case MODE_14k:
case MODE_16k:
case MODE_18k:
case MODE_20k:
case MODE_23k:
case MODE_24k:
if (quality)
{
*frame_type = RX_SPEECH_GOOD;
}
else
{
*frame_type = RX_SPEECH_BAD;
}
break;
case MRSID:
if (quality)
{
if (temp & 0x80)
{
*frame_type = RX_SID_UPDATE;
}
else
{
*frame_type = RX_SID_FIRST;
}
}
else
{
*frame_type = RX_SID_BAD;
}
/* set mode index */
*mode = st->prev_mode;
break;
case 14: /* SPEECH_LOST */
*frame_type = RX_SPEECH_LOST;
*mode = st->prev_mode;
break;
case 15: /* NO_DATA */
*frame_type = RX_NO_DATA;
*mode = st->prev_mode;
break;
default: /* replace frame with unused mode index by NO_DATA frame */
*frame_type = RX_NO_DATA;
*mode = st->prev_mode;
break;
}
st->prev_mode = *mode;
}
| 41.293151 | 89 | 0.484242 | dAck2cC2 |
e1995200a41c73feb893397859bf6a95b2ea9864 | 2,821 | cpp | C++ | raycastergl/src/opengl/buffer.cpp | DanielAcedo/raycastergl | 412bf8b6b2e8996bcdc9cb4112258cc24527b22a | [
"MIT"
] | 4 | 2020-06-07T13:00:30.000Z | 2021-10-18T20:50:21.000Z | raycastergl/src/opengl/buffer.cpp | DanielAcedo/raycastergl | 412bf8b6b2e8996bcdc9cb4112258cc24527b22a | [
"MIT"
] | null | null | null | raycastergl/src/opengl/buffer.cpp | DanielAcedo/raycastergl | 412bf8b6b2e8996bcdc9cb4112258cc24527b22a | [
"MIT"
] | 2 | 2020-06-27T16:15:20.000Z | 2020-09-01T06:48:14.000Z | #include <opengl/buffer.hpp>
#include <fstream>
#include <glad/glad.h>
#include <opengl/check-error.hpp>
constexpr int usageToGlUsage(Buffer::Usage usage) {
switch(usage) {
case Buffer::StreamDraw: return GL_STREAM_DRAW;
case Buffer::StreamRead: return GL_STREAM_READ;
case Buffer::StreamCopy: return GL_STREAM_COPY;
case Buffer::StaticDraw: return GL_STATIC_DRAW;
case Buffer::StaticRead: return GL_STATIC_READ;
case Buffer::StaticCopy: return GL_STATIC_COPY;
case Buffer::DynamicDraw: return GL_DYNAMIC_DRAW;
case Buffer::DynamicRead: return GL_DYNAMIC_READ;
case Buffer::DynamicCopy: return GL_DYNAMIC_COPY;
default: return GL_STREAM_COPY;
}
}
constexpr int typeToGlType(Buffer::Type type) {
switch(type) {
case Buffer::ArrayBuffer: return GL_ARRAY_BUFFER;
case Buffer::ElementArrayBuffer: return GL_ELEMENT_ARRAY_BUFFER;
case Buffer::ShaderStorageBuffer: return GL_SHADER_STORAGE_BUFFER;
default: return GL_ARRAY_BUFFER;
}
}
Buffer::~Buffer() {
if(buffer) {
glDeleteBuffers(1, &buffer);
buffer = 0;
}
if(data) {
free(data);
data = nullptr;
}
}
void Buffer::build() {
auto type = typeToGlType(this->type);
auto usage = usageToGlUsage(this->usage);
checkGlError(glGenBuffers(1, &buffer));
checkGlError(glBindBuffer(type, buffer));
checkGlError(glBufferData(type, bufferSize, data, usage));
}
void Buffer::bind() {
if(!buffer) {
build();
}
checkGlError(glBindBuffer(typeToGlType(type), buffer));
}
void Buffer::bindBase(uint32_t index) {
if(!buffer) {
build();
}
checkGlError(glBindBufferBase(typeToGlType(type), index, buffer));
}
void Buffer::setData(const void* data, size_t size) {
if(bufferSize < size || !this->data) {
this->data = realloc(this->data, size);
}
auto type = typeToGlType(this->type);
auto usage = usageToGlUsage(this->usage);
memcpy(this->data, data, size);
bufferSize = size;
checkGlError(glBufferData(type, bufferSize, data, usage));
}
void Buffer::mapBuffer(const std::function<void(const void* const)>& func) {
bind();
auto type = typeToGlType(this->type);
GLvoid* p = glMapBuffer(type, GL_READ_ONLY);
func(p);
glUnmapBuffer(type);
}
void Buffer::mapWritableBuffer(const std::function<void(void*)>& func) {
bind();
auto type = typeToGlType(this->type);
GLvoid* p = glMapBuffer(type, GL_READ_WRITE);
func(p);
glUnmapBuffer(type);
}
void Buffer::_writeContentsToFile(const char* fileName) {
mapBuffer([this, fileName] (const void* const ptr) {
std::ofstream ff("yes.bin");
ff.write((const char*) ptr, this->bufferSize);
ff.close();
});
}
| 27.656863 | 76 | 0.658632 | DanielAcedo |
e1a08f272c70065ddbe48cda94d555c2cb83ee76 | 4,168 | cpp | C++ | samples/cpp/monitoring/monitoring_reg/src/monitoring_reg.cpp | FlorianReimold/ecal | e21e52c14f58e1cae38e3867940bf0292f5ccb9a | [
"Apache-2.0"
] | null | null | null | samples/cpp/monitoring/monitoring_reg/src/monitoring_reg.cpp | FlorianReimold/ecal | e21e52c14f58e1cae38e3867940bf0292f5ccb9a | [
"Apache-2.0"
] | null | null | null | samples/cpp/monitoring/monitoring_reg/src/monitoring_reg.cpp | FlorianReimold/ecal | e21e52c14f58e1cae38e3867940bf0292f5ccb9a | [
"Apache-2.0"
] | null | null | null | /* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental 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.
*
* ========================= eCAL LICENSE =================================
*/
#include <ecal/ecal.h>
#include <iostream>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4100 4127 4146 4505 4800 4189 4592) // disable proto warnings
#endif
#include "ecal/pb/ecal.pb.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
void OnProcessRegistration(const char* sample_, int sample_size_)
{
eCAL::pb::Sample sample;
if (sample.ParseFromArray(sample_, sample_size_))
{
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << "Process Registration" << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << sample.DebugString();
std::cout << std::endl;
}
}
void OnServiceRegistration(const char* sample_, int sample_size_)
{
eCAL::pb::Sample sample;
if (sample.ParseFromArray(sample_, sample_size_))
{
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << "Service Registration" << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << sample.DebugString();
std::cout << std::endl;
}
}
void OnSubscriberRegistration(const char* sample_, int sample_size_)
{
eCAL::pb::Sample sample;
if (sample.ParseFromArray(sample_, sample_size_))
{
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << "Subscriber Registration" << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << sample.DebugString();
std::cout << std::endl;
}
}
void OnPublisherRegistration(const char* sample_, int sample_size_)
{
eCAL::pb::Sample sample;
if (sample.ParseFromArray(sample_, sample_size_))
{
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << "Publisher Registration" << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << sample.DebugString();
std::cout << std::endl;
}
}
int main(int argc, char **argv)
{
// initialize eCAL API
eCAL::Initialize(argc, argv, "monitoring registrations", eCAL::Init::None);
// set process state
eCAL::Process::SetState(proc_sev_healthy, proc_sev_level1, "I feel good !");
// add process register callback function
eCAL::Process::AddRegistrationCallback(reg_event_process, std::bind(OnProcessRegistration, std::placeholders::_1, std::placeholders::_2));
// add service register callback function
eCAL::Process::AddRegistrationCallback(reg_event_service, std::bind(OnServiceRegistration, std::placeholders::_1, std::placeholders::_2));
// add subscriber register callback function
eCAL::Process::AddRegistrationCallback(reg_event_subscriber, std::bind(OnSubscriberRegistration, std::placeholders::_1, std::placeholders::_2));
// add publisher register callback function
eCAL::Process::AddRegistrationCallback(reg_event_publisher, std::bind(OnPublisherRegistration, std::placeholders::_1, std::placeholders::_2));
while(eCAL::Ok())
{
// sleep 100 ms
eCAL::Process::SleepMS(100);
}
// finalize eCAL API
eCAL::Finalize();
return(0);
}
| 34.733333 | 146 | 0.584693 | FlorianReimold |
e1a2c5aaa65f9c17263bfe8ba6a8f79237b2b78c | 3,198 | cpp | C++ | study/cyan/ACLB.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | study/cyan/ACLB.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | study/cyan/ACLB.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | //#ifdef _DEBUG
//#include "../../../library/src/debug_template.hpp"
//#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
//#else
//#define DMP(...) ((void)0)
//#endif
//
//#include <cassert>
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <iomanip>
//#include <vector>
//#include <set>
//#include <map>
//#include <unordered_map>
//#include <queue>
//#include <numeric>
//#include <algorithm>
//#include <bitset>
//#include <functional>
//
//using namespace std;
//using lint = long long;
//constexpr int MOD = 1000000007, INF = 1010101010;
//constexpr lint LINF = 1LL << 60;
//
//struct init {
// init() {
// cin.tie(nullptr); ios::sync_with_stdio(false);
// cout << fixed << setprecision(10);
// }
//} init_;
//
//template <typename T>
//struct SegmentTree {
// using F = function<T(T, T)>;
// int n;
// F f;
// T ti;
// vector<T> dat;
//
// SegmentTree(F f, T ti) :f(f), ti(ti) {}
//
// void init(int n_) {
// n = 1;
// while (n < n_) n <<= 1;
// dat.assign(n << 1, ti);
// }
//
// void build(const vector<T>& v) {
// int n_ = v.size();
// init(n_);
// for (int i = 0; i < n_; i++) dat[n + i] = v[i];
// for (int i = n - 1; i; i--)
// dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]);
// }
//
// void set_val(int k, T x) {
// dat[k += n] = x;
// while (k >>= 1)
// dat[k] = f(dat[(k << 1) | 0], dat[(k << 1) | 1]);
// }
//
// T query(int a, int b) {
// if (a >= b) return ti;
// T vl = ti, vr = ti;
// for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) {
// if (l & 1) vl = f(vl, dat[l++]);
// if (r & 1) vr = f(dat[--r], vr);
// }
// return f(vl, vr);
// }
//
// template<typename C>
// int find(int st, C& check, T& acc, int k, int l, int r) {
// if (l + 1 == r) {
// acc = f(acc, dat[k]);
// return check(acc) ? k - n : -1;
// }
// int m = (l + r) >> 1;
// if (m <= st) return find(st, check, acc, (k << 1) | 1, m, r);
// if (st <= l and !check(f(acc, dat[k]))) {
// acc = f(acc, dat[k]);
// return -1;
// }
// int vl = find(st, check, acc, (k << 1) | 0, l, m);
// if (~vl) return vl;
// return find(st, check, acc, (k << 1) | 1, m, r);
// }
//
// template<typename C>
// int find(int st, C& check) {
// T acc = ti;
// return find(st, check, acc, 1, 0, n);
// }
//};
//
//template<class T>
//inline bool chmax(T& a, const T b) { return a < b && (a = b, true); }
//
//int main() {
//
// int N, K;
// cin >> N >> K;
//
// vector<int> A(N);
// for (int i = 0; i < N; i++) cin >> A[i];
//
// constexpr int A_max = 333333;
// auto f = [](int a, int b) { return max(a, b); };
// SegmentTree<int> sg(f, 0);
// sg.init(A_max);
//
// int ans = 0;
// for (int i = 0; i < N; i++) {
// int L = max(A[i] - K, 0);
// int R = min(A[i] + K + 1, A_max);
// int now = sg.query(L, R) + 1;
// sg.set_val(A[i], now);
// chmax(ans, now);
// }
//
// cout << ans << "\n";
//
// return 0;
//}
| 24.984375 | 71 | 0.430894 | rajyan |
e1a5494cbf657c73e653eb7cf9d07be18a4ce751 | 1,778 | cc | C++ | 2020/PTA/Contest/13.cc | slowbear/TrainingCode | 688872b9dab784a410069b787457f8c0871648aa | [
"CC0-1.0"
] | null | null | null | 2020/PTA/Contest/13.cc | slowbear/TrainingCode | 688872b9dab784a410069b787457f8c0871648aa | [
"CC0-1.0"
] | null | null | null | 2020/PTA/Contest/13.cc | slowbear/TrainingCode | 688872b9dab784a410069b787457f8c0871648aa | [
"CC0-1.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
using Pii = pair<int, int>;
using Pll = pair<LL, LL>;
using VI = vector<int>;
using VP = vector<pair<int, int>>;
#define rep(i, a, b) for (auto i = (a); i < (b); ++i)
#define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i)
#define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i])
#define mem(x, v) memset(x, v, sizeof(x))
#define cpy(x, y) memcpy(x, y, sizeof(x))
#define SZ(V) static_cast<int>(V.size())
#define pb push_back
#define mp make_pair
constexpr int maxn = 10400000;
int fa[maxn], vis[maxn], sz[maxn];
int n, m, l, t;
inline int get_id(int x, int y, int z) { return z * n * m + x * m + y; }
int find_fa(int x) { return x == fa[x] ? x : fa[x] = find_fa(fa[x]); }
bool is_union(int x, int y) { return find_fa(x) == find_fa(y); }
void join(int u, int v) {
u = find_fa(u);
v = find_fa(v);
if (u != v) {
fa[v] = u;
sz[u] += sz[v];
}
}
int main() {
// freopen("input.in", "r", stdin);
scanf("%d%d%d%d", &n, &m, &l, &t);
rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) {
int id = get_id(i, j, k);
scanf("%d", &sz[id]);
fa[id] = id;
}
rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) {
int id = get_id(i, j, k), new_id;
if (!sz[id]) continue;
if (i + 1 < n) {
new_id = get_id(i + 1, j, k);
if (sz[new_id]) join(id, new_id);
}
if (j + 1 < m) {
new_id = get_id(i, j + 1, k);
if (sz[new_id]) join(id, new_id);
}
if (k + 1 < l) {
new_id = get_id(i, j, k + 1);
if (sz[new_id]) join(id, new_id);
}
}
LL ans = 0;
rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) {
int id = find_fa(get_id(i, j, k));
if (vis[id]) continue;
vis[id] = true;
if (sz[id] >= t) ans += sz[id];
}
printf("%lld\n", ans);
}
| 25.042254 | 72 | 0.505062 | slowbear |
e1a8c9db065a7914aee2192ed44df63707f63045 | 284 | cxx | C++ | src/resources/components_loader/fbx_lod_group_loader.cxx | Frozen-Team/3DEngine | f0b7002a1e5912b8f49377570b226b22eec662cf | [
"MIT"
] | 1 | 2015-10-09T22:33:43.000Z | 2015-10-09T22:33:43.000Z | src/resources/components_loader/fbx_lod_group_loader.cxx | Frozen-Team/FEngine | f0b7002a1e5912b8f49377570b226b22eec662cf | [
"MIT"
] | 1 | 2015-10-09T16:43:47.000Z | 2015-10-09T22:18:52.000Z | src/resources/components_loader/fbx_lod_group_loader.cxx | Frozen-Team/FEngine | f0b7002a1e5912b8f49377570b226b22eec662cf | [
"MIT"
] | null | null | null | #include "fbx_lod_group_loader.hpp"
#include <utils/f_typedefs.hpp>
namespace fengine
{
float FbxLodGroupLoader::RetrieveThreshold(int index) const
{
FbxDistance threshold;
auto result = this->GetThreshold(index, threshold);
return result ? threshold.value() : FLT_MAX;
}
}
| 21.846154 | 60 | 0.760563 | Frozen-Team |
e1ad661419da55fdae9db64d98fe71cd237068be | 4,385 | cpp | C++ | cpp_Midterm_Project/Polynomial.cpp | NgocNguyenGit/cpp-programming | 54dc1ce7b5ae8c80f790c677faea6ad2ddb29e22 | [
"MIT"
] | null | null | null | cpp_Midterm_Project/Polynomial.cpp | NgocNguyenGit/cpp-programming | 54dc1ce7b5ae8c80f790c677faea6ad2ddb29e22 | [
"MIT"
] | null | null | null | cpp_Midterm_Project/Polynomial.cpp | NgocNguyenGit/cpp-programming | 54dc1ce7b5ae8c80f790c677faea6ad2ddb29e22 | [
"MIT"
] | null | null | null | //
// Polynomial.cpp
// cpp_Midterm2
//
// Created by Nguyen Le Khanh Ngoc on 11/11/2020.
// Copyright © 2020 Nguyen Le Khanh Ngoc. All rights reserved.
//
#include "Polynomial.h"
#include <string> //string type
#include <string.h>
#include <vector> //vector
#include <ctype.h> //isalpha
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
//Constructor
Polynomial::Polynomial (string num){
//Polynomial
cout<<"p"<<num<<": ";
string f;
cin>>f;
parsePoly(f);
}
//Constructor
Polynomial::Polynomial(vector<Term> terms){
t.reserve(terms.size());
t.insert(t.end(), terms.begin(), terms.end());
}
//Parse and set string to each term
void Polynomial::parsePoly(const string str){
size_t position = 0; //point each char in string
string temp, term;
for (int i = 0; i < str.size(); i++){
//reach + or - => save to temp data on the left
if (str[i] != '+' && str[i] != '-'){
temp += str[i];
}
else{
temp += ";";
temp += str[i];
}
}
//add ; after an element
temp += ";";
//error handling e.g. ;-4xy;+2
if (temp[0] == ';'){
temp.erase(0,1);
}
while ((position = temp.find(";")) != string::npos) { //reach ; => push back the left term && erase it
term = temp.substr(0, position);
t.push_back(Term(term));
temp.erase(0, position + 1);
}
}
Polynomial Polynomial::operator* (const Polynomial& p){
vector<Term> new_terms;
for (int i = 0; i < t.size(); i++){
for (int j = 0; j < p.t.size(); j++){
new_terms.push_back(t[i] * p.t[j]);
}
}
return Polynomial(new_terms);
}
ostream& operator<< (ostream& output, const Polynomial& p){
cout<<"p1 * p2 = p3: ";
for (int i = 0; i < p.t.size(); ++i){
for (int j = 0; j < p.t[i].getElement().size(); ++j){
//first element always contains coeff
if (j == 0){
//if 1x => x
if(p.t[i].getElement()[j+1].getCoeff() == 1){ //e.g. test: p1:-3x^2-1 result = 3x^2+3x^3y+1+xy
// p2:-1-xy instead= 3x^2+3x^3y+1+1xy
if(p.t[i].getElement()[j].getCoeff() == 1){
output<<"";
} else if (p.t[i].getElement()[j].getCoeff() == -1){
output<<"-";
} else {
output<<p.t[i].getElement()[j].getCoeff();
}
} else {
output<<p.t[i].getElement()[j].getCoeff();
}
} else { //if 1x^1 => print only 1x else print e.g. x^2
if (p.t[i].getElement()[j].getExp() == 1){
output<<p.t[i].getElement()[j].getVar();
} else {
output<<p.t[i].getElement()[j].getVar()<<"^"<< p.t[i].getElement()[j].getExp();
}
}
}
if (i != p.t.size() -1){ //error handling: trailing plus otherwise -4x^2y+3+
//error handling: no add + before negative coeff e.g. -36x^2 instead +-36x^2
if (p.t[i+1].getElement()[0].getCoeff() < 0){
continue;
}
cout << "+";
}
}
return output << endl;
}
//evaluate
void Polynomial::evaluate(){
vector<char> store_var;
vector<double> store_value;
double temp;
long double sum{0.0};
for (int i = 0; i < t.size(); ++i){
for (int j = 0; j < t[i].getElement().size(); ++j){
if (isalpha (t[i].getElement()[j].getVar())){
//check if variable already print or not
if (find(store_var.begin(), store_var.end(), t[i].getElement()[j].getVar()) != store_var.end()) {
continue;
}
cout<<t[i].getElement()[j].getVar()<<": ";
cin>>temp;
store_value.push_back(temp);
store_var.push_back(t[i].getElement()[j].getVar());
//sum of terms
}
}
}
for (int i = 0; i < t.size(); ++i){
sum += t[i].evaluateTerm(store_var, store_value);
}
cout<<"Result: "<<sum<<endl;
}
| 30.880282 | 113 | 0.461345 | NgocNguyenGit |
e1adc846bdf3d52c36fcf7fd7ec9c5f3e7b03cec | 958 | cpp | C++ | d2suite/src/test/test_orl.cpp | bobye/d2suite | b5a76af2be8a35ac2194865d58fe6424394c042d | [
"Apache-2.0"
] | 1 | 2019-08-21T04:47:05.000Z | 2019-08-21T04:47:05.000Z | d2suite/src/test/test_orl.cpp | bobye/d2suite | b5a76af2be8a35ac2194865d58fe6424394c042d | [
"Apache-2.0"
] | null | null | null | d2suite/src/test/test_orl.cpp | bobye/d2suite | b5a76af2be8a35ac2194865d58fe6424394c042d | [
"Apache-2.0"
] | null | null | null | #include "../common/d2.hpp"
#include "../learn/wm3.hpp"
#include <string>
#include <sstream>
#include <time.h>
int main(int argc, char** argv) {
using namespace d2;
server::Init(argc, argv);
size_t len = 864, size=400;
Block<Elem<def::Histogram, 0> > data (size, len);
std::string filename("data/orl/orl.d2s");
data.read(filename, size);
size_t k = 40;
Block<Elem<def::Histogram, 0> > wm3 (k, 864);
for (size_t i=0; i<k; ++i) {
std::string uniform_sample = "0 864 ";
srand (i);
for (size_t i=1; i<=864; ++i) {
uniform_sample += std::to_string(rand()%100+1) + " ";
}
std::istringstream istr (uniform_sample);
wm3.append(istr);
}
WM3_SA(wm3, data, 1000, .05, 2., 20);
wm3.write("data/orl/mixture_" + std::to_string(k) + "n.txt");
std::ofstream f; f.open("data/orl/real.d2s");
for (size_t i=0; i<size; ++i)
operator<<(f, data[i]);
f.close();
server::Finalize();
return 0;
}
| 22.27907 | 63 | 0.590814 | bobye |
e1adde2c1b645b57cf885cfbaed40e1f564842da | 4,730 | tcc | C++ | libiop/algebra/utils.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/algebra/utils.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/algebra/utils.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | #include <cassert>
#include <sodium/randombytes.h>
#include <libff/common/utils.hpp>
namespace libiop {
template<typename T>
std::vector<T> all_subset_sums(const std::vector<T> &basis, const T& shift)
{
const size_t m = basis.size();
std::vector<T> result;
/* as we are I/O-bound here, reserve + emplace_back is ~2x faster
then pre-initializing with zero and then overwriting (as per
benchmark_vector_op.cpp) */
result.reserve(1ull<<m);
result.emplace_back(shift);
for (size_t i = 0; i < m; ++i)
{
const size_t l = (1ull<<i);
for (size_t j = 0; j < l; ++j)
{
result.emplace_back(result[j] + basis[i]);
}
}
return result;
}
template<typename FieldT>
std::vector<FieldT> batch_inverse(const std::vector<FieldT> &vec, const bool has_zeroes)
{
return batch_inverse_and_mul(vec, FieldT::one(), has_zeroes);
}
template<typename FieldT>
std::vector<FieldT> batch_inverse_and_mul_internal(const std::vector<FieldT> &vec, const FieldT &k)
{
/** Montgomery batch inversion trick.
* This assumes that all elements of the input are non-zero.
* It also multiplies every element by k, which can be done with one multiplication.
*/
std::vector<FieldT> R;
R.reserve(vec.size());
FieldT c = vec[0];
R.emplace_back(c);
// Set R[i] to be the product of all vec[j], where j <= 0 <= i
for (size_t i = 1; i < vec.size(); ++i)
{
c *= vec[i];
R.emplace_back(c);
}
FieldT c_inv = c.inverse() * k;
for (size_t i = vec.size()-1; i > 0; --i)
{
R[i] = R[i-1] * c_inv;
c_inv *= vec[i];
}
R[0] = c_inv;
return R;
}
template<typename FieldT>
std::vector<FieldT> batch_inverse_and_mul(const std::vector<FieldT> &vec, const FieldT &k, const bool has_zeroes)
{
/** Montgomery batch inversion trick.
* This wraps the internal batch inverse and mul to handle 0's.
* If we need more efficiency, we can make an entirely separate codepath for the case with zeroes,
* and get rid of the loop that searches for zeroes.
* We omit this optimization, as has_zeroes=false in the verifiers code path. */
if (has_zeroes)
{
std::vector<FieldT> vec_copy(vec);
std::vector<size_t> zero_locations;
FieldT zero = FieldT::zero();
for (std::size_t i = 0; i < vec.size(); i++)
{
if (vec_copy[i] == zero)
{
zero_locations.emplace_back(i);
vec_copy[i] = FieldT::one();
}
}
std::vector<FieldT> result = batch_inverse_and_mul_internal(vec_copy, k);
for (std::size_t i = 0; i < zero_locations.size(); i++)
{
result[zero_locations[i]] = zero;
}
return result;
}
else
{
return batch_inverse_and_mul_internal(vec, k);
}
}
template<typename FieldT>
void mut_batch_inverse(std::vector<FieldT> &vec)
{
/** Montgomery batch inversion trick, which mutates vec.
* This assumes that all elements of the input are non-zero.
*
* The primary advantage of mut_batch_inverse is that instead of
* heap allocating a vector of size vec.size() internally, an array
* can be stack allocated. This matters more as the size of vec grows.
*/
/* Not using std::vector in order to make this stack allocated. */
FieldT vec_copy[vec.size()];
FieldT c = vec[0];
vec_copy[0] = c;
// Set R[i] to be the product of all vec[j], where j <= 0 <= i
for (size_t i = 1; i < vec.size(); ++i)
{
vec_copy[i] = vec[i];
c *= vec[i];
vec[i] = c;
}
FieldT c_inv = c.inverse();
for (size_t i = vec.size()-1; i > 0; --i)
{
vec[i] = vec[i-1] * c_inv;
c_inv *= vec_copy[i];
}
vec[0] = c_inv;
return;
}
template<typename T>
void bitreverse_vector(std::vector<T> &a)
{
const size_t n = a.size();
const size_t logn = libff::log2(n);
assert(n == 1ull<<logn);
for (size_t k = 0; k < n; ++k)
{
const size_t rk = libff::bitreverse(k, logn);
if (k < rk)
{
std::swap(a[k], a[rk]);
}
}
}
template<typename T>
std::vector<T> random_vector(const std::size_t count)
{
std::vector<T> result(count);
randombytes_buf(result.data(), count * sizeof(T));
return result;
}
template<typename FieldT>
std::vector<FieldT> random_FieldT_vector(const std::size_t count)
{
std::vector<FieldT> result;
result.reserve(count);
for (std::size_t i = 0; i < count; i++) {
result.emplace_back(FieldT::random_element());
}
return result;
}
} // namespace libiop
| 25.430108 | 113 | 0.591543 | alexander-zw |
e1b1b6e61e6f9923adac20d196739d8053b590c1 | 15,878 | cpp | C++ | JsonDocument.cpp | JCodeARM/JSON | 1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c | [
"Unlicense"
] | null | null | null | JsonDocument.cpp | JCodeARM/JSON | 1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c | [
"Unlicense"
] | null | null | null | JsonDocument.cpp | JCodeARM/JSON | 1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c | [
"Unlicense"
] | null | null | null | //
// JsonDocument.cpp
// JSON
//
// Created by Iulian on 13.03.2013.
//
#include "JsonDocument.hpp"
#define SHOW_LIST( list ) for (auto iteratorBeing=list.begin(); iteratorBeing != list.end(); iteratorBeing++) {\
std::cout<<(*iteratorBeing)<<std::endl;}
#define SHOW_LIST_POINT( list ) for (auto iteratorBeing=list->begin(); iteratorBeing != list->end(); iteratorBeing++) {\
std::cout<<(*iteratorBeing)<<std::endl;}
enum class TokenNext{
None,
Start,
End,
};
JsonDocument::JsonDocument():lJsonRootObject(nullptr){
}
JsonDocument::~JsonDocument(){
if (lJsonRootObject != nullptr) {
delete lJsonRootObject;
lJsonRootObject=nullptr;
}
}
JsonDocument::JsonDocument(JsonDocument & ldoc){
lJsonRootObject=ldoc.lJsonRootObject;
ldoc.lJsonRootObject=nullptr;
}
JsonDocument::JsonDocument(JsonDocument && ldoc){
lJsonRootObject=ldoc.lJsonRootObject;
ldoc.lJsonRootObject=nullptr;
}
JsonObject * JsonDocument::getNodeRoot(){
if (lJsonRootObject == nullptr) {
lJsonRootObject=new JsonObject();
}
return lJsonRootObject;
}
JsonObject * JsonDocument::addObject(JsonObject * lObject,std::string &lProperty){
JsonObject *lReturn;
lReturn=new JsonObject();
std::string s("\""+lProperty+"\"");
lObject->addProperty(s, lReturn);
return lReturn;
}
JsonArray * JsonDocument::addArray(JsonObject * lObject,std::string &lProperty){
JsonArray *lReturn;
lReturn=new JsonArray();
std::string s("\""+lProperty+"\"");
lObject->addProperty(s, lReturn);
return lReturn;
}
void JsonDocument::addNumber(JsonObject * lObject,std::string &lProperty,double lValue){
std::string s("\""+lProperty+"\"");
lObject->addProperty(s, new JsonNumber(lValue));
}
void JsonDocument::addString(JsonObject * lObject,std::string &lProperty,std::string &lValue){
std::string s("\""+lProperty+"\"");
lObject->addProperty(lProperty, new JsonString(s));
}
void JsonDocument::addBoolean(JsonObject * lObject,std::string &lProperty,bool lValue){
std::string s("\""+lProperty+"\"");
lObject->addProperty(s, new JsonBoolean(lValue));
}
void JsonDocument::addNull(JsonObject * lObject,std::string &lProperty){
std::string s("\""+lProperty+"\"");
lObject->addProperty(s, new JsonNull());
}
JsonObject * JsonDocument::addObject(JsonArray * lArray){
JsonObject *lReturn;
lReturn=new JsonObject();
lArray->additem(lReturn);
return lReturn;
}
JsonArray * JsonDocument::addArray(JsonArray * lArray){
JsonArray *lReturn;
lReturn=new JsonArray();
lArray->additem(lReturn);
return lReturn;
}
void JsonDocument::addNumber(JsonArray * lArray,double lValue){
lArray->additem(new JsonNumber(lValue));
}
void JsonDocument::addString(JsonArray * lArray,std::string &lValue){
std::string s("\""+lValue+"\"");
lArray->additem(new JsonString(s));
}
void JsonDocument::addBoolean(JsonArray * lArray,bool lValue){
lArray->additem(new JsonBoolean(lValue));
}
void JsonDocument::addNull(JsonArray * lArray){
lArray->additem(new JsonNull());
}
std::vector<char> JsonDocument::getVectorJson(JsonDocumentFormat lFormat){
std::vector<char> lReturn;
switch (lFormat) {
case JsonDocumentFormat::Inndenter:{
}break;
case JsonDocumentFormat::Compact:{
}break;
default:
break;
}
return lReturn;
}
void JsonDocument::parseJson(const char* iBegin , const char* iEnd){
// BEGIN PARSS TOKEN
const char *iSearch=iBegin;
std::list<std::string_view> listToken;
while (iSearch < iEnd) {
if((*iSearch) == ':' || (*iSearch) == '{' || (*iSearch) == '}' ||
(*iSearch) == '[' || (*iSearch) == ']' || (*iSearch) == ','){
listToken.push_back(std::string_view(iSearch,1));
iSearch++;
continue;
}else if ((*iSearch) == '"'){
const char *iStart=iSearch;
iSearch++;
while (iSearch < iEnd) {
if (std::strncmp(iSearch, "\\\"", 2) == 0){
iSearch+=2;
continue;
}else if((*iSearch) == '"'){
listToken.push_back(std::string_view(iStart,(iSearch-iStart)+1));
iSearch++;
break;
}
iSearch++;
}
continue;
}else if ((std::strncmp(iSearch, "null", 4) == 0) || (std::strncmp(iSearch, "true", 4) == 0)){
listToken.push_back(std::string_view(iSearch,4));
iSearch+=4;
continue;
}else if ( std::strncmp(iSearch, "false", 5) == 0){
listToken.push_back(std::string_view(iSearch,5));
iSearch+=5;
continue;
}else if (std::isdigit(*iSearch)){
const char *iStart=iSearch;
int pointSize=0;
while (iSearch < iEnd && ((std::isdigit(*iSearch)) || (*iSearch == '.' && ++pointSize)) ) {
if (pointSize > 1) {
throw std::string("Error Token Multi Point: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
iSearch++;
}
listToken.push_back(std::string_view(iStart,(iSearch-iStart)));
continue;
}
iSearch++;
}
// END PARSS TOKEN
// BEGIN SHOW PARSS TOKEN
#ifdef SHOW_TOKEN_TERMINAL
SHOW_LIST(listToken)
#endif
// END SHOW PARSS TOKEN
// BEGIN CREATE THREE OBJECT
if (listToken.size() > 1 && listToken.front() == "{" && listToken.back() == "}" ) {
listToken.pop_back();
listToken.pop_front();
lJsonRootObject=new JsonObject();
parseObject(lJsonRootObject,&listToken);
}else{
throw std::string("Error root ");
}
// END CREATE THREE OBJECT
}
void JsonDocument::parseObject(JsonObject *lObject,std::list<std::string_view> *listStringView){
TokenNext lNextItem=TokenNext::None;
for (auto iBegin=listStringView->begin(); iBegin != listStringView->end(); iBegin++) {
auto iSearch=&(*iBegin);
if((*iSearch).length() > 1 && (*iSearch).back() == '"' && (*iSearch).front() == '"'){
iBegin++;
if ( iBegin != listStringView->end()) {
if ((*iBegin) == ":") {
iBegin++;
if(iBegin != listStringView->end()){
if ((*iBegin) == "{"){
std::list<std::string_view> sObjectList;
int tNumber=1;
for ( iBegin++; iBegin != listStringView->end(); iBegin++) {
if ((*iBegin) == "{") {
tNumber++;
}else if ((*iBegin) == "}"){
tNumber--;
if (tNumber == 0) {
break;
}
}
sObjectList.push_back(*iBegin);
}
if (tNumber == 0 ) {
std::string s(*iSearch);
JsonObject *tObject= new JsonObject();
lObject->addProperty(s, tObject);
parseObject(tObject,&sObjectList);
lNextItem=TokenNext::End;
}else{
throw std::string("Error Token {}: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else if ((*iBegin) == "["){
std::list<std::string_view> sArrayList;
int tNumber=1;
for ( iBegin++; iBegin != listStringView->end(); iBegin++) {
if ((*iBegin) == "[") {
tNumber++;
}else if ((*iBegin) == "]"){
tNumber--;
if (tNumber == 0) {
break;
}
}
sArrayList.push_back(*iBegin);
}
if (tNumber == 0 ) {
std::string s(*iSearch);
JsonArray *tArray= new JsonArray();
lObject->addProperty(s, tArray);
parseArray(tArray,&sArrayList);
lNextItem=TokenNext::End;
}else{
throw std::string("Error Token []: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else if ((*iBegin).length() > 1 && (*iBegin).front() == '"' && (*iBegin).back() == '"'){
std::string s(*iSearch);
std::string v(*iBegin);
lObject->addProperty(s, new JsonString(v));
lNextItem=TokenNext::End;
}else if ((*iBegin) == "null"){
std::string s(*iSearch);
lObject->addProperty(s, new JsonNull());
lNextItem=TokenNext::End;
}else if((*iBegin) == "true" ){
std::string s(*iSearch);
lObject->addProperty(s, new JsonBoolean(true));
lNextItem=TokenNext::End;
}else if ((*iBegin) == "false"){
std::string s(*iSearch);
lObject->addProperty(s, new JsonBoolean(false));
lNextItem=TokenNext::End;
}else if ((*iBegin).length() > 0 && std::isdigit((*iBegin).front()) ){
std::string s(*iSearch);
double d=std::atof(std::string(*iBegin).data());
lObject->addProperty(s, new JsonNumber(d));
lNextItem=TokenNext::End;
}else if ((*iBegin) == ",") {
throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
auto iteratorNextItem=iBegin;
iteratorNextItem++;
if (TokenNext::End == lNextItem && iteratorNextItem != listStringView->end() && (*iteratorNextItem) == ",") {
iBegin=iteratorNextItem;
lNextItem=TokenNext::Start;
}
}else{
throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else{
throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else{
throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else{
throw std::string("Error Token ("+std::string(*iSearch)+"): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}
if (lNextItem == TokenNext::Start) {
throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}
void JsonDocument::parseArray(JsonArray *lArray,std::list<std::string_view> *listStringView){
TokenNext lNextItem=TokenNext::None;
for (auto iBegin=listStringView->begin(); iBegin != listStringView->end(); iBegin++) {
if ((*iBegin) == "{") {
std::list<std::string_view> sObjectList;
int tNumber=1;
for ( iBegin++; iBegin != listStringView->end(); iBegin++) {
if ((*iBegin) == "{") {
tNumber++;
}else if ((*iBegin) == "}"){
tNumber--;
if (tNumber == 0) {
break;
}
}
sObjectList.push_back(*iBegin);
}
if (tNumber == 0) {
JsonObject *tObject= new JsonObject();
lArray->additem(tObject);
parseObject(tObject,&sObjectList);
lNextItem=TokenNext::End;
}else{
throw std::string("Error Token {}: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else if((*iBegin) == "["){
std::list<std::string_view> sArrayList;
int tNumber=1;
for ( iBegin++; iBegin != listStringView->end(); iBegin++) {
if ((*iBegin) == "[") {
tNumber++;
}else if ((*iBegin) == "]"){
tNumber--;
if (tNumber == 0) {
break;
}
}
sArrayList.push_back(*iBegin);
}
if (tNumber == 0) {
JsonArray *tArray= new JsonArray();
lArray->additem( tArray);
parseArray(tArray,&sArrayList);
lNextItem=TokenNext::End;
}else{
throw std::string("Error Token []: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}else if ((*iBegin).length() > 1 && (*iBegin).front() == '"' && (*iBegin).back() == '"'){
std::string s(*iBegin);
lArray->additem(new JsonString(s));
lNextItem=TokenNext::End;
}else if (std::isdigit((*iBegin).front())){
double d=std::atof(std::string(*iBegin).data());
lArray->additem(new JsonNumber(d));
lNextItem=TokenNext::End;
}else if ((*iBegin) == "true"){
lArray->additem(new JsonBoolean(true));
lNextItem=TokenNext::End;
}else if ((*iBegin) == "false"){
lArray->additem(new JsonBoolean(false));
lNextItem=TokenNext::End;
}else if ((*iBegin) == "null"){
lArray->additem(new JsonNull());
lNextItem=TokenNext::End;
}else if ((*iBegin) == ","){
throw std::string("Error Token , : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
auto iteratorNextItem=iBegin;
iteratorNextItem++;
if (TokenNext::End == lNextItem && iteratorNextItem != listStringView->end() && (*iteratorNextItem) == ",") {
iBegin=iteratorNextItem;
lNextItem=TokenNext::Start;
}
}
if (lNextItem == TokenNext::Start) {
throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__));
}
}
JsonDocument JsonDocument::fromVecotr(std::vector<char> & lArray){
JsonDocument lReturnDoc;
if(lArray.empty() == false){
const char *iBegine=lArray.data();
const char *iEnd=iBegine+lArray.size();
lReturnDoc.parseJson(iBegine, iEnd);
}
return lReturnDoc;
}
// BEGIN OPERATOR <<
JsonStream & operator <<(JsonStream & lout, JsonDocument & lin){
if (lin.lJsonRootObject) {
lout<<(*lin.lJsonRootObject);
}
return lout;
}
// END OPERATOR <<
| 37.985646 | 146 | 0.489293 | JCodeARM |
e1b76bba41d281dc935f55001e5017b07942ef84 | 21,927 | cpp | C++ | src/mongo/db/ops/update.cpp | andremussche/minimongo | 820d678f3561abb5660e27ff3204bd0e69dfe66c | [
"Apache-2.0"
] | 1 | 2017-02-13T10:29:02.000Z | 2017-02-13T10:29:02.000Z | src/mongo/db/ops/update.cpp | andremussche/minimongo | 820d678f3561abb5660e27ff3204bd0e69dfe66c | [
"Apache-2.0"
] | null | null | null | src/mongo/db/ops/update.cpp | andremussche/minimongo | 820d678f3561abb5660e27ff3204bd0e69dfe66c | [
"Apache-2.0"
] | null | null | null | //@file update.cpp
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/pch.h"
#include "mongo/db/ops/update.h"
#include <cstring> // for memcpy
#include "mongo/bson/mutable/damage_vector.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/client/dbclientinterface.h"
#include "mongo/db/clientcursor.h"
#include "mongo/db/index_set.h"
#include "mongo/db/namespace_details.h"
#include "mongo/db/ops/update_driver.h"
#include "mongo/db/pagefault.h"
#include "mongo/db/pdfile.h"
#include "mongo/db/query_optimizer.h"
#include "mongo/db/query_runner.h"
#include "mongo/db/queryutil.h"
#include "mongo/db/storage/record.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/platform/unordered_set.h"
namespace mongo {
namespace {
// TODO: Make this a function on NamespaceString, or make it cleaner.
inline void validateUpdate( const char* ns , const BSONObj& updateobj, const BSONObj& patternOrig ) {
uassert( 10155 , "cannot update reserved $ collection", strchr(ns, '$') == 0 );
if ( strstr(ns, ".system.") ) {
/* dm: it's very important that system.indexes is never updated as IndexDetails
has pointers into it */
uassert( 10156,
str::stream() << "cannot update system collection: "
<< ns << " q: " << patternOrig << " u: " << updateobj,
legalClientSystemNS( ns , true ) );
}
}
/**
* return a BSONObj with the _id field of the doc passed in. If no _id and multi, error.
*/
BSONObj makeOplogEntryQuery(const BSONObj doc, bool multi) {
BSONObjBuilder idPattern;
BSONElement id;
// NOTE: If the matching object lacks an id, we'll log
// with the original pattern. This isn't replay-safe.
// It might make sense to suppress the log instead
// if there's no id.
if ( doc.getObjectID( id ) ) {
idPattern.append( id );
return idPattern.obj();
}
else {
uassert( 10157, "multi-update requires all modified objects to have an _id" , ! multi );
return doc;
}
}
} // namespace
UpdateResult update(const UpdateRequest& request, OpDebug* opDebug) {
// Should the modifiers validate their embedded docs via okForStorage
// Only user updates should be checked. Any system or replication stuff should pass through.
// Config db docs shouldn't get checked for valid field names since the shard key can have
// a dot (".") in it.
bool shouldValidate = !(request.isFromReplication() ||
request.getNamespaceString().isConfigDB());
// TODO: Consider some sort of unification between the UpdateDriver, ModifierInterface
// and UpdateRequest structures.
UpdateDriver::Options opts;
opts.multi = request.isMulti();
opts.upsert = request.isUpsert();
opts.logOp = request.shouldUpdateOpLog();
opts.modOptions = ModifierInterface::Options( request.isFromReplication(), shouldValidate );
UpdateDriver driver( opts );
Status status = driver.parse( request.getUpdates() );
if ( !status.isOK() ) {
uasserted( 16840, status.reason() );
}
return update(request, opDebug, &driver);
}
UpdateResult update(const UpdateRequest& request, OpDebug* opDebug, UpdateDriver* driver) {
const NamespaceString& nsString = request.getNamespaceString();
validateUpdate( nsString.ns().c_str(), request.getUpdates(), request.getQuery() );
NamespaceDetails* nsDetails = nsdetails( nsString.ns() );
NamespaceDetailsTransient* nsDetailsTransient =
&NamespaceDetailsTransient::get( nsString.ns().c_str() );
// TODO: This seems a bit circuitious.
opDebug->updateobj = request.getUpdates();
driver->refreshIndexKeys( nsDetailsTransient->indexKeys() );
shared_ptr<Cursor> cursor = getOptimizedCursor(
nsString.ns(), request.getQuery(), BSONObj(), request.getQueryPlanSelectionPolicy() );
// If the update was marked with '$isolated' (a.k.a '$atomic'), we are not allowed to
// yield while evaluating the update loop below.
//
// TODO: Old code checks this repeatedly within the update loop. Is that necessary? It seems
// that once atomic should be always atomic.
const bool isolated =
cursor->ok() &&
cursor->matcher() &&
cursor->matcher()->docMatcher().atomic();
// The 'cursor' the optimizer gave us may contain query plans that generate duplicate
// diskloc's. We set up here the mechanims that will prevent us from processing those
// twice if we see them. We also set up a 'ClientCursor' so that we can support
// yielding.
//
// TODO: Is it valid to call this on a non-ok cursor?
const bool dedupHere = cursor->autoDedup();
//
// We'll start assuming we have one or more documents for this update. (Othwerwise,
// we'll fallback to upserting.)
//
// We record that this will not be an upsert, in case a mod doesn't want to be applied
// when in strict update mode.
driver->setContext( ModifierInterface::ExecInfo::UPDATE_CONTEXT );
// Let's fetch each of them and pipe them through the update expression, making sure to
// keep track of the necessary stats. Recall that we'll be pulling documents out of
// cursors and some of them do not deduplicate the entries they generate. We have
// deduping logic in here, too -- for now.
unordered_set<DiskLoc, DiskLoc::Hasher> seenLocs;
int numMatched = 0;
opDebug->nscanned = 0;
Client& client = cc();
mutablebson::Document doc;
// If we are going to be yielding, we will need a ClientCursor scoped to this loop. We
// only loop as long as the underlying cursor is OK.
for ( auto_ptr<ClientCursor> clientCursor; cursor->ok(); ) {
// If we haven't constructed a ClientCursor, and if the client allows us to throw
// page faults, and if we are referring to a location that is likely not in
// physical memory, then throw a PageFaultException. The entire operation will be
// restarted.
if ( clientCursor.get() == NULL &&
client.allowedToThrowPageFaultException() &&
!cursor->currLoc().isNull() &&
!cursor->currLoc().rec()->likelyInPhysicalMemory() ) {
// We should never throw a PFE if we have already updated items.
dassert((numMatched == 0) || (numMatched == opDebug->nupdateNoops));
throw PageFaultException( cursor->currLoc().rec() );
}
if ( !isolated && opDebug->nscanned != 0 ) {
// We are permitted to yield. To do so we need a ClientCursor, so create one
// now if we have not yet done so.
if ( !clientCursor.get() )
clientCursor.reset(
new ClientCursor( QueryOption_NoCursorTimeout, cursor, nsString.ns() ) );
// Ask the client cursor to yield. We get two bits of state back: whether or not
// we yielded, and whether or not we correctly recovered from yielding.
bool yielded = false;
const bool recovered = clientCursor->yieldSometimes(
ClientCursor::WillNeed, &yielded );
if ( !recovered ) {
// If we failed to recover from the yield, then the ClientCursor is already
// gone. Release it so we don't destroy it a second time.
clientCursor.release();
break;
}
if ( !cursor->ok() ) {
// If the cursor died while we were yielded, just get out of the update loop.
break;
}
if ( yielded ) {
// We yielded and recovered OK, and our cursor is still good. Details about
// our namespace may have changed while we were yielded, so we re-acquire
// them here. If we can't do so, escape the update loop. Otherwise, refresh
// the driver so that it knows about what is currently indexed.
nsDetails = nsdetails( nsString.ns() );
if ( !nsDetails )
break;
nsDetailsTransient = &NamespaceDetailsTransient::get( nsString.ns().c_str() );
// TODO: This copies the index keys, but it may not need to do so.
driver->refreshIndexKeys( nsDetailsTransient->indexKeys() );
}
}
// Let's fetch the next candidate object for this update.
Record* record = cursor->_current();
DiskLoc loc = cursor->currLoc();
const BSONObj oldObj = loc.obj();
// We count how many documents we scanned even though we may skip those that are
// deemed duplicated. The final 'numUpdated' and 'nscanned' numbers may differ for
// that reason.
opDebug->nscanned++;
// Skips this document if it:
// a) doesn't match the query portion of the update
// b) was deemed duplicate by the underlying cursor machinery
//
// Now, if we are going to update the document,
// c) we don't want to do so while the cursor is at it, as that may invalidate
// the cursor. So, we advance to next document, before issuing the update.
MatchDetails matchDetails;
matchDetails.requestElemMatchKey();
if ( !cursor->currentMatches( &matchDetails ) ) {
// a)
cursor->advance();
continue;
}
else if ( cursor->getsetdup( loc ) && dedupHere ) {
// b)
cursor->advance();
continue;
}
else if (!driver->isDocReplacement() && request.isMulti()) {
// c)
cursor->advance();
if ( dedupHere ) {
if ( seenLocs.count( loc ) ) {
continue;
}
}
// There are certain kind of cursors that hold multiple pointers to data
// underneath. $or cursors is one example. In a $or cursor, it may be the case
// that when we did the last advance(), we finished consuming documents from
// one of $or child and started consuming the next one. In that case, it is
// possible that the last document of the previous child is the same as the
// first document of the next (see SERVER-5198 and jstests/orp.js).
//
// So we advance the cursor here until we see a new diskloc.
//
// Note that we won't be yielding, and we may not do so for a while if we find
// a particularly duplicated sequence of loc's. That is highly unlikely,
// though. (See SERVER-5725, if curious, but "stage" based $or will make that
// ticket moot).
while( cursor->ok() && loc == cursor->currLoc() ) {
cursor->advance();
}
}
// For some (unfortunate) historical reasons, not all cursors would be valid after
// a write simply because we advanced them to a document not affected by the write.
// To protect in those cases, not only we engaged in the advance() logic above, but
// we also tell the cursor we're about to write a document that we've just seen.
// prepareToTouchEarlierIterate() requires calling later
// recoverFromTouchingEarlierIterate(), so we make a note here to do so.
bool touchPreviousDoc = request.isMulti() && cursor->ok();
if ( touchPreviousDoc ) {
if ( clientCursor.get() )
clientCursor->setDoingDeletes( true );
cursor->prepareToTouchEarlierIterate();
}
// Found a matching document
numMatched++;
// Ask the driver to apply the mods. It may be that the driver can apply those "in
// place", that is, some values of the old document just get adjusted without any
// change to the binary layout on the bson layer. It may be that a whole new
// document is needed to accomodate the new bson layout of the resulting document.
doc.reset( oldObj, mutablebson::Document::kInPlaceEnabled );
BSONObj logObj;
// If there was a matched field, obtain it.
string matchedField;
if (matchDetails.hasElemMatchKey())
matchedField = matchDetails.elemMatchKey();
Status status = driver->update( matchedField, &doc, &logObj );
if ( !status.isOK() ) {
uasserted( 16837, status.reason() );
}
// If the driver applied the mods in place, we can ask the mutable for what
// changed. We call those changes "damages". :) We use the damages to inform the
// journal what was changed, and then apply them to the original document
// ourselves. If, however, the driver applied the mods out of place, we ask it to
// generate a new, modified document for us. In that case, the file manager will
// take care of the journaling details for us.
//
// This code flow is admittedly odd. But, right now, journaling is baked in the file
// manager. And if we aren't using the file manager, we have to do jounaling
// ourselves.
bool objectWasChanged = false;
BSONObj newObj;
const char* source = NULL;
mutablebson::DamageVector damages;
bool inPlace = doc.getInPlaceUpdates(&damages, &source);
if ( inPlace && !damages.empty() && !driver->modsAffectIndices() ) {
nsDetails->paddingFits();
// All updates were in place. Apply them via durability and writing pointer.
mutablebson::DamageVector::const_iterator where = damages.begin();
const mutablebson::DamageVector::const_iterator end = damages.end();
for( ; where != end; ++where ) {
const char* sourcePtr = source + where->sourceOffset;
void* targetPtr = getDur().writingPtr(
const_cast<char*>(oldObj.objdata()) + where->targetOffset,
where->size);
std::memcpy(targetPtr, sourcePtr, where->size);
}
newObj = oldObj;
opDebug->fastmod = true;
objectWasChanged = true;
}
else {
// The updates were not in place. Apply them through the file manager.
newObj = doc.getObject();
DiskLoc newLoc = theDataFileMgr.updateRecord(nsString.ns().c_str(),
nsDetails,
nsDetailsTransient,
record,
loc,
newObj.objdata(),
newObj.objsize(),
*opDebug);
// If we've moved this object to a new location, make sure we don't apply
// that update again if our traversal picks the objecta again.
//
// We also take note that the diskloc if the updates are affecting indices.
// Chances are that we're traversing one of them and they may be multi key and
// therefore duplicate disklocs.
if ( newLoc != loc || driver->modsAffectIndices() ) {
seenLocs.insert( newLoc );
}
objectWasChanged = true;
}
// Log Obj
if ( request.shouldUpdateOpLog() ) {
if ( driver->isDocReplacement() || !logObj.isEmpty() ) {
BSONObj idQuery = driver->makeOplogEntryQuery(newObj, request.isMulti());
logOp("u", nsString.ns().c_str(), logObj , &idQuery,
NULL, request.isFromMigration(), &newObj);
}
}
// If it was noop since the document didn't change, record that.
if (!objectWasChanged)
opDebug->nupdateNoops++;
if (!request.isMulti()) {
break;
}
// If we used the cursor mechanism that prepares an earlier seen document for a
// write we need to tell such mechanisms that the write is over.
if ( touchPreviousDoc ) {
cursor->recoverFromTouchingEarlierIterate();
}
getDur().commitIfNeeded();
}
// TODO: Can this be simplified?
if ((numMatched > 0) || (numMatched == 0 && !request.isUpsert()) ) {
opDebug->nupdated = numMatched;
return UpdateResult( numMatched > 0 /* updated existing object(s) */,
!driver->isDocReplacement() /* $mod or obj replacement */,
numMatched /* # of docments update, even no-ops */,
BSONObj() );
}
//
// We haven't found any existing document so an insert is done
// (upsert is true).
//
opDebug->upsert = true;
// Since this is an insert (no docs found and upsert:true), we will be logging it
// as an insert in the oplog. We don't need the driver's help to build the
// oplog record, then. We also set the context of the update driver to the INSERT_CONTEXT.
// Some mods may only work in that context (e.g. $setOnInsert).
driver->setLogOp( false );
driver->setContext( ModifierInterface::ExecInfo::INSERT_CONTEXT );
BSONObj baseObj;
// Reset the document we will be writing to
doc.reset( baseObj, mutablebson::Document::kInPlaceDisabled );
if ( request.getQuery().hasElement("_id") ) {
uassertStatusOK(doc.root().appendElement(request.getQuery().getField("_id")));
}
// If this is a $mod base update, we need to generate a document by examining the
// query and the mods. Otherwise, we can use the object replacement sent by the user
// update command that was parsed by the driver before.
// In the following block we handle the query part, and then do the regular mods after.
if ( *request.getUpdates().firstElementFieldName() == '$' ) {
uassertStatusOK(UpdateDriver::createFromQuery(request.getQuery(), doc));
opDebug->fastmodinsert = true;
}
// Apply the update modifications and then log the update as an insert manually.
Status status = driver->update( StringData(), &doc, NULL /* no oplog record */);
if ( !status.isOK() ) {
uasserted( 16836, status.reason() );
}
BSONObj newObj = doc.getObject();
theDataFileMgr.insertWithObjMod( nsString.ns().c_str(), newObj, false, request.isGod() );
if ( request.shouldUpdateOpLog() ) {
logOp( "i", nsString.ns().c_str(), newObj,
NULL, NULL, request.isFromMigration(), &newObj );
}
opDebug->nupdated = 1;
return UpdateResult( false /* updated a non existing document */,
!driver->isDocReplacement() /* $mod or obj replacement? */,
1 /* count of updated documents */,
newObj /* object that was upserted */ );
}
BSONObj applyUpdateOperators( const BSONObj& from, const BSONObj& operators ) {
UpdateDriver::Options opts;
opts.multi = false;
opts.upsert = false;
UpdateDriver driver( opts );
Status status = driver.parse( operators );
if ( !status.isOK() ) {
uasserted( 16838, status.reason() );
}
mutablebson::Document doc( from, mutablebson::Document::kInPlaceDisabled );
status = driver.update( StringData(), &doc, NULL /* not oplogging */ );
if ( !status.isOK() ) {
uasserted( 16839, status.reason() );
}
return doc.getObject();
}
} // namespace mongo
| 45.968553 | 109 | 0.562548 | andremussche |
e1b9c4231bd55e728417210379b51b13c59f9aed | 465 | cpp | C++ | estl/test/defer_test.cpp | Eospp/Eospp | bc231908aaf34dfc2f790a259487253a4151be16 | [
"MIT"
] | 18 | 2022-01-21T18:19:37.000Z | 2022-03-15T05:26:32.000Z | estl/test/defer_test.cpp | Eospp/Eospp | bc231908aaf34dfc2f790a259487253a4151be16 | [
"MIT"
] | null | null | null | estl/test/defer_test.cpp | Eospp/Eospp | bc231908aaf34dfc2f790a259487253a4151be16 | [
"MIT"
] | 3 | 2022-01-22T14:24:04.000Z | 2022-02-23T10:19:11.000Z | #include <gtest/gtest.h>
#include <defer.hpp>
TEST(DEFER_TEST,BAST_TEST)
{
bool flag = false;
{
defer_scope [&flag]
{
flag = true;
};
}
EXPECT_TRUE(flag);
flag = false;
{
defer_scope [&flag]
{
flag = true;
};
}
EXPECT_TRUE(flag);
flag = false;
{
defer_lamda
{
flag = true;
};
}
EXPECT_TRUE(flag);
} | 12.916667 | 27 | 0.423656 | Eospp |
e1bb870a8ef713c862ca4637063f875a9c7ed0f1 | 897 | cc | C++ | src/nn_acc/CombWrite.cc | leorezende93/gem5 | 8b6f40c90c58a589f230e27ae4a240ba792840a9 | [
"BSD-3-Clause"
] | 1 | 2019-06-26T14:32:39.000Z | 2019-06-26T14:32:39.000Z | src/nn_acc/CombWrite.cc | leorezende93/gem5 | 8b6f40c90c58a589f230e27ae4a240ba792840a9 | [
"BSD-3-Clause"
] | null | null | null | src/nn_acc/CombWrite.cc | leorezende93/gem5 | 8b6f40c90c58a589f230e27ae4a240ba792840a9 | [
"BSD-3-Clause"
] | 2 | 2019-06-26T14:33:42.000Z | 2019-10-02T02:09:23.000Z |
#include "nn_acc/CombWrite.hh"
#include "debug/CombWrite.hh"
CombWrite::CombWrite(CombWriteParams *params) :
CombBase(params),
n_of_iterations(params->data.size()),
_writeEvent([this]{ writeData(); }, name() + ".event")
{
for (int i = 0; i < params->data.size(); i++) {
_writeDataVector.push_back(params->data[i]);
}
}
CombWrite::~CombWrite() {
}
void CombWrite::startup() {
if(!_writeEvent.scheduled() && n_of_iterations > 0) {
schedule(_writeEvent, curTick());
}
}
CombWrite* CombWriteParams::create() {
return new CombWrite(this);
}
void CombWrite::writeData(){
n_of_iterations--;
DPRINTF(CombWrite, "Master %s writing %d\n", _master[0].name(), _writeDataVector[n_of_iterations]);
_master[0].newData(_writeDataVector[n_of_iterations]);
if(n_of_iterations > 0) {
schedule(_writeEvent, curTick() + _latency[0]);
}
}
| 23.605263 | 101 | 0.654404 | leorezende93 |
e1c07c5359b23b757bdd414a27ae76a23c864f28 | 685 | hpp | C++ | examples/simple/src/MagicItem.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 63 | 2019-08-30T11:53:47.000Z | 2021-05-19T06:17:47.000Z | examples/simple/src/MagicItem.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 96 | 2019-09-16T05:03:31.000Z | 2020-10-14T14:33:50.000Z | examples/simple/src/MagicItem.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 27 | 2019-09-25T10:12:37.000Z | 2020-05-06T02:59:44.000Z | #pragma once
#include <vector>
#include <string>
// like `trait`
struct
MagicItem {
virtual void has_enough_mana(const char* spellname) const noexcept = 0;
/// \note same for all types
// @gen(inject_to_all)
//S interface_data;
};
template<typename T1>
struct
ParentTemplated_1 {
virtual void has_P1(T1 name1) const noexcept = 0;
};
template<typename T1>
struct
ParentTemplated_2 {
virtual void has_P2(T1 name1) const noexcept = 0;
};
// like `trait`
template<typename T1, typename T2>
struct
MagicTemplated {
virtual void has_T(const T1& name1, const T2& name2) const noexcept = 0;
/// \note same for all types
// @gen(inject_to_all)
//S interface_data;
};
| 18.026316 | 74 | 0.710949 | mohibqureshi |
e1c25902040a3b76343d34dadd5d30c95e9f78a0 | 813 | cpp | C++ | lib/expression.cpp | julienlopez/DifferentialGeometry2 | f720ac4f2966a347ab69eb4df1350fb271b63ed6 | [
"MIT"
] | null | null | null | lib/expression.cpp | julienlopez/DifferentialGeometry2 | f720ac4f2966a347ab69eb4df1350fb271b63ed6 | [
"MIT"
] | 1 | 2021-01-31T14:34:39.000Z | 2021-01-31T14:34:39.000Z | lib/expression.cpp | julienlopez/DifferentialGeometry2 | f720ac4f2966a347ab69eb4df1350fb271b63ed6 | [
"MIT"
] | null | null | null | #include "expression.hpp"
#include "comparison.hpp"
bool operator==(const Constant& c1, const Constant& c2)
{
return c1.name == c2.name;
}
bool operator==(const Value& v1, const Value& v2)
{
return v1.value == v2.value;
}
bool operator==(const Variable& v1, const Variable& v2)
{
return v1.name == v2.name;
}
bool operator==(const Sum& s1, const Sum& s2)
{
return std::equal(begin(s1.operands), end(s1.operands), begin(s2.operands), end(s2.operands));
}
bool operator==(const Product& s1, const Product& s2)
{
return std::equal(begin(s1.operands), end(s1.operands), begin(s2.operands), end(s2.operands));
}
bool operator==(const Cos& c1, const Cos& c2)
{
return areEqual(c1.expr, c2.expr);
}
bool operator==(const Sin& s1, const Sin& s2)
{
return areEqual(s1.expr, s2.expr);
}
| 20.846154 | 98 | 0.669127 | julienlopez |
e1ca41216b08cfbd94905a4887abe5db86569af4 | 334 | hpp | C++ | src/ast/expr_ast.hpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | null | null | null | src/ast/expr_ast.hpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | 3 | 2021-07-24T23:06:37.000Z | 2021-08-21T03:24:58.000Z | src/ast/expr_ast.hpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | null | null | null | #ifndef EXPRAST_H
#define EXPRAST_H
#include <memory>
#include <string>
#include <vector>
#include "llvm/IR/Value.h"
#include "../code_gen_context.hpp"
/// ExprAST - Base class for all expression nodes.
class ExprAST
{
public:
virtual ~ExprAST() = default;
virtual llvm::Value *codegen(CodeGenContext &) = 0;
};
#endif | 15.904762 | 55 | 0.697605 | sethitow |
e1d0ef4bf77d0d0634e08785d22c90eb8cba720c | 1,491 | cc | C++ | tests/libtests/friction/data/FrictionModelData.cc | cehanagan/pylith | cf5c1c34040460a82f79b6eb54df894ed1b1ee93 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/friction/data/FrictionModelData.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/friction/data/FrictionModelData.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University at Buffalo
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2021 University of California, Davis
//
// See LICENSE.md for license information.
//
// ======================================================================
//
#include "FrictionModelData.hh"
// ----------------------------------------------------------------------
// Constructor
pylith::friction::FrictionModelData::FrictionModelData(void) :
numLocs(0),
numProperties(0),
numStateVars(0),
numDBProperties(0),
numDBStateVars(0),
numPropsVertex(0),
numVarsVertex(0),
numPropertyValues(0),
numStateVarValues(0),
dbPropertyValues(0),
dbStateVarValues(0),
dt(0.0),
dbProperties(0),
dbStateVars(0),
properties(0),
stateVars(0),
propertiesNondim(0),
stateVarsNondim(0),
friction(0),
frictionDeriv(0),
slip(0),
slipRate(0),
normalTraction(0),
stateVarsUpdated(0),
setLengthScale(0),
setTimeScale(0),
setPressureScale(0),
setDensityScale(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
// Destructor
pylith::friction::FrictionModelData::~FrictionModelData(void)
{ // destructor
} // destructor
// End of file
| 24.048387 | 73 | 0.56271 | cehanagan |
e1d1d4ac8fd09177ce45c72413a2342d012587d4 | 3,524 | hpp | C++ | src/concepts.hpp | Aertalon/optimizer | 32afad1dc5c1640cd2869a7575f43584ad6390bd | [
"MIT"
] | 1 | 2022-01-27T16:57:10.000Z | 2022-01-27T16:57:10.000Z | src/concepts.hpp | Aertalon/optimizer | 32afad1dc5c1640cd2869a7575f43584ad6390bd | [
"MIT"
] | 27 | 2022-01-27T17:46:56.000Z | 2022-02-15T22:37:43.000Z | src/concepts.hpp | Aertalon/optimizer | 32afad1dc5c1640cd2869a7575f43584ad6390bd | [
"MIT"
] | 1 | 2022-02-05T09:36:56.000Z | 2022-02-05T09:36:56.000Z | #pragma once
#include <concepts>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace opt {
// clang-format off
template <class T, class U = T, class R = T>
concept Addable =
requires (T a, U b) { { a + b } -> std::same_as<R>; };
template <class T, class U = T, class R = T>
concept Subtractible =
requires (T a, U b) { { a - b } -> std::same_as<R>; };
template <class T, class U = T, class R = T>
concept Multipliable =
requires (T a, U b) { { a * b } -> std::same_as<R>; };
template <class T, class U = T, class R = T>
concept Divisible =
requires (T a, U b) { { a / b } -> std::same_as<R>; };
template <class T>
concept Negatable =
requires (T a) { { -a } -> std::same_as<T>; };
template <class T, class U = T>
concept CompoundAddable =
requires (T& a, U b) { { a += b } -> std::same_as<T&>; };
template <class T, class U = T>
concept CompoundSubtractible =
requires (T& a, U b) { { a -= b } -> std::same_as<T&>; };
template <class T, class U = T>
concept CompoundMultipliable =
requires (T& a, U b) { { a *= b } -> std::same_as<T&>; };
template <class T, class U = T>
concept CompoundDivisible =
requires (T& a, U b) { { a /= b } -> std::same_as<T&>; };
template <class T>
concept Arithmetic =
std::regular<T> &&
Addable<T> &&
Subtractible<T> &&
Multipliable<T> &&
Divisible<T> &&
Negatable<T> &&
CompoundAddable<T> &&
CompoundSubtractible<T> &&
CompoundMultipliable<T> &&
CompoundDivisible<T> &&
requires(T a) {
T{0}; // additive identity
T{1}; // multiplicative identity
};
namespace detail {
template <class T>
concept is_lvalue_ref = std::is_lvalue_reference_v<T>;
template <class T>
concept is_const_lvalue_ref =
std::is_lvalue_reference_v<T> &&
std::is_const_v<std::remove_reference_t<T>>;
} // namespace detail
template <class T, class U = std::size_t>
concept Indexable =
requires(T& a, const T& b, U n) {
{ a[n] } -> detail::is_lvalue_ref;
{ b[n] } -> detail::is_const_lvalue_ref;
};
template <class T>
concept TupleSizable =
requires {
{ std::tuple_size<T>::value } -> std::same_as<const std::size_t&>;
};
template <Indexable T>
using scalar_t = std::remove_cvref_t<decltype(std::declval<T&>()[0])>;
template <class T, class U = scalar_t<T>>
concept Vector =
Arithmetic<U> &&
std::regular<T> &&
TupleSizable<T> &&
Indexable<T> &&
Addable<T> &&
Subtractible<T> &&
Negatable<T> &&
Multipliable<U, const T&, T>;
template <class T>
concept Diffable =
requires (T a, T b) { a - b; };
template <Diffable T>
using distance_t =
std::remove_cvref_t<decltype(std::declval<const T&>() - std::declval<const T&>())>;
template <class T, class U = distance_t<T>>
concept Point =
Vector<U> &&
std::regular<T> &&
TupleSizable<T> &&
(std::tuple_size<T>::value == std::tuple_size<U>::value) &&
Indexable<T> &&
Addable<const T&, const U&, T> &&
Addable<const U&, const T&, T> &&
Subtractible<const T&, const T&, U> &&
Subtractible<const T&, const U&, T>;
template <Arithmetic, std::size_t>
struct point;
namespace impl {
template <Arithmetic>
struct dual;
}
// TODO replace total ordering requirement with partial ordering
template <class T, class P>
concept Cost =
Point<P> &&
std::regular_invocable<const T&, const P&> &&
std::regular_invocable<const T&,
const opt::point<impl::dual<scalar_t<P>>, std::tuple_size<P>::value>&> &&
std::totally_ordered<std::invoke_result_t<const T&, const P&>>;
// clang-format on
} // namespace opt
| 24.643357 | 98 | 0.630533 | Aertalon |
e1d2c21af6c478b9b48be555acbc7f568826d3c3 | 3,316 | cpp | C++ | PlayerInfo/Dolby/DolbyOutput.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 7 | 2020-03-24T15:26:23.000Z | 2021-12-21T21:42:38.000Z | PlayerInfo/Dolby/DolbyOutput.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 224 | 2020-03-05T17:40:39.000Z | 2022-03-23T13:18:56.000Z | PlayerInfo/Dolby/DolbyOutput.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 52 | 2020-03-05T17:24:05.000Z | 2022-03-31T02:13:40.000Z | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 Metrological
*
* 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 "../../Module.h"
#include "Dolby.h"
namespace WPEFramework
{
namespace Plugin
{
class DolbyOutputImplementation : public Exchange::Dolby::IOutput
{
public:
uint32_t Register(Exchange::Dolby::IOutput::INotification* notification) override
{
_adminLock.Lock();
// Make sure a sink is not registered multiple times.
ASSERT(std::find(_observers.begin(), _observers.end(), notification) == _observers.end());
_observers.push_back(notification);
notification->AddRef();
_adminLock.Unlock();
return (Core::ERROR_NONE);
}
uint32_t Unregister(Exchange::Dolby::IOutput::INotification* notification) override
{
_adminLock.Lock();
std::list<Exchange::Dolby::IOutput::INotification*>::iterator index(std::find(_observers.begin(), _observers.end(), notification));
// Make sure you do not unregister something you did not register !!!
ASSERT(index != _observers.end());
if (index != _observers.end()) {
(*index)->Release();
_observers.erase(index);
}
_adminLock.Unlock();
return (Core::ERROR_NONE);
}
uint32_t AtmosMetadata(bool& supported) const override
{
return (Core::ERROR_UNAVAILABLE);
}
uint32_t SoundMode(Exchange::Dolby::IOutput::SoundModes& mode) const override
{
return (Core::ERROR_UNAVAILABLE);
}
uint32_t EnableAtmosOutput(const bool& enable) override
{
return (Core::ERROR_UNAVAILABLE);
}
uint32_t Mode(const Exchange::Dolby::IOutput::Type& mode) override
{
return set_audio_output_type(mode);
}
uint32_t Mode(Exchange::Dolby::IOutput::Type& mode) const override
{
return get_audio_output_type(&mode);
}
BEGIN_INTERFACE_MAP(DolbyOutputImplementation)
INTERFACE_ENTRY(Exchange::Dolby::IOutput)
END_INTERFACE_MAP
private:
std::list<Exchange::Dolby::IOutput::INotification*> _observers;
mutable Core::CriticalSection _adminLock;
};
SERVICE_REGISTRATION(DolbyOutputImplementation, 1, 0);
} // namespace Plugin
} // namespace WPEFramework
| 32.509804 | 147 | 0.59228 | Michal-Bugno |
e1d5168d3aa19f1f78a5dd2ca476f5e488922a01 | 2,154 | cpp | C++ | OpenRPG/Components/SoundComponent.cpp | OpenRPGs/OpenRPG | 0baed49c1d7e6f871457c441aa0209ec4280265a | [
"MIT"
] | 28 | 2019-08-09T04:07:04.000Z | 2022-01-16T05:56:22.000Z | OpenRPG/Components/SoundComponent.cpp | OpenRPGs/OpenRPG | 0baed49c1d7e6f871457c441aa0209ec4280265a | [
"MIT"
] | 29 | 2019-08-09T04:02:59.000Z | 2019-09-16T05:01:33.000Z | OpenRPG/Components/SoundComponent.cpp | OpenRPGs/OpenRPG | 0baed49c1d7e6f871457c441aa0209ec4280265a | [
"MIT"
] | 18 | 2019-08-09T02:42:09.000Z | 2022-01-16T06:03:32.000Z | #include "stdafx.h"
#include "SoundComponent.h"
bool SoundComponent::isSame(sf::SoundBuffer& buffer) {
return &buffer == this->sound->getBuffer();
}
bool SoundComponent::Loaded() {
return this->sound != NULL;
}
#pragma region Play, Pause, Stop
SoundComponent* SoundComponent::play() {
if (this->sound == NULL)
return this;
this->sound->play();
return this;
}
SoundComponent* SoundComponent::pause() {
if (this->sound == NULL)
return this;
this->sound->pause();
return this;
}
SoundComponent* SoundComponent::stop() {
if (this->sound == NULL)
return this;
this->sound->stop();
return this;
}
#pragma endregion
bool SoundComponent::isPlaying() {
if (this->sound == NULL)
return false;
return this->sound->getStatus() == sf::Sound::Status::Playing;
}
#pragma region Volume
SoundComponent* SoundComponent::setVolume(float volume) {
if (this->sound == NULL)
return this;
this->sound->setVolume(volume);
return this;
}
float SoundComponent::getVolume() {
if (this->sound == NULL)
return -1;
return this->sound->getVolume();
}
#pragma endregion
#pragma region Offset
SoundComponent* SoundComponent::setOffset(int msec) {
if (this->sound == NULL)
return this;
this->sound->setPlayingOffset(sf::milliseconds(msec));
return this;
}
int SoundComponent::getOffset() {
if (this->sound == NULL)
return -1;
return this->sound->getPlayingOffset().asMilliseconds();
}
#pragma endregion
#pragma region Loop
SoundComponent* SoundComponent::setLoop(bool loop) {
if (this->sound == NULL)
return this;
this->sound->setLoop(loop);
return this;
}
bool SoundComponent::getLoop() {
if (this->sound == NULL)
return false;
return this->sound->getLoop();
}
#pragma endregion
SoundComponent::SoundComponent(sf::SoundBuffer& buffer) {
this->sound = new sf::Sound(buffer);
}
SoundComponent::~SoundComponent() {
if (this->sound != NULL) {
delete this->sound;
this->sound = NULL;
}
}
SoundComponent* SoundComponent::reset(sf::SoundBuffer& buffer) {
if (this->sound == NULL)
return this;
this->sound->stop();
this->sound->setBuffer(buffer);
this->sound->setPlayingOffset(sf::milliseconds(0));
return this;
}
| 19.944444 | 64 | 0.697307 | OpenRPGs |
e1d85a375708100cbe46b34ba007e78a9792128a | 877 | hpp | C++ | HiLo/Game.hpp | JankoDedic/Hi-Lo | b9d73b7a50deb76b6282c5541d496335d749a0f5 | [
"MIT"
] | 1 | 2019-09-18T01:32:23.000Z | 2019-09-18T01:32:23.000Z | HiLo/Game.hpp | JankoDedic/Hi-Lo | b9d73b7a50deb76b6282c5541d496335d749a0f5 | [
"MIT"
] | null | null | null | HiLo/Game.hpp | JankoDedic/Hi-Lo | b9d73b7a50deb76b6282c5541d496335d749a0f5 | [
"MIT"
] | null | null | null | #pragma once
#include "CreditsView.hpp"
#include "GameScene.hpp"
#include "MenuSceneView.hpp"
namespace HiLo {
class Game
: public Observer<MenuSceneView>
, public Observer<GameScene>
, public Observer<CreditsView> {
public:
auto receiveEvent(MenuSceneView*, MenuSceneView::Event const&) noexcept
-> void override;
auto receiveEvent(GameScene*, GameScene::Event const&) noexcept -> void
override;
auto receiveEvent(CreditsView*, CreditsView::Event const&) noexcept
-> void override;
Game() noexcept;
auto handleEvent(SDL_Event const&) noexcept -> void;
auto draw() const noexcept -> void;
private:
enum class Scene {
Menu, Game, Credits
};
Scene mActiveScene{Scene::Menu};
MenuSceneView mMenuSceneView;
GameScene mGameScene;
CreditsView mCreditsView;
};
} // namespace HiLo
| 21.390244 | 75 | 0.686431 | JankoDedic |
e1d96168d8b9d6714174e84c3b866df100f59f73 | 1,044 | cpp | C++ | src/mettle/run_test_files.cpp | jimporter/mettle | c65aa75b04a08b550b3572f4c080c68e26ad86fa | [
"BSD-3-Clause"
] | 82 | 2015-01-05T10:06:44.000Z | 2022-03-07T01:41:28.000Z | src/mettle/run_test_files.cpp | JohnGalbraith/mettle | 38b70fe1dc0f30e98b768a37108196328182b5f4 | [
"BSD-3-Clause"
] | 44 | 2015-01-08T08:40:54.000Z | 2021-10-29T23:28:56.000Z | src/mettle/run_test_files.cpp | jimporter/mettle | c65aa75b04a08b550b3572f4c080c68e26ad86fa | [
"BSD-3-Clause"
] | 13 | 2015-06-23T07:41:54.000Z | 2020-02-14T15:35:07.000Z | #include "run_test_files.hpp"
#include "log_pipe.hpp"
#ifndef _WIN32
# include "posix/run_test_file.hpp"
namespace platform = mettle::posix;
#else
# include "windows/run_test_file.hpp"
namespace platform = mettle::windows;
#endif
namespace mettle {
void run_test_files(
const std::vector<test_command> &commands, log::file_logger &logger,
const std::vector<std::string> &args
) {
using namespace platform;
logger.started_run();
detail::file_uid_maker uid;
for(const auto &command : commands) {
test_file file = {command, uid.make_file_uid()};
logger.started_file(file);
std::vector<std::string> final_args = command.args();
final_args.insert(final_args.end(), args.begin(), args.end());
auto result = run_test_file(std::move(final_args),
log::pipe(logger, file.id));
if(result.passed)
logger.ended_file(file);
else
logger.failed_file(file, result.message);
}
logger.ended_run();
}
} // namespace mettle
| 24.857143 | 72 | 0.65613 | jimporter |
e1d9f6248ede03dddee6e14ead9b6d6f3fa8e193 | 3,989 | cc | C++ | tests/unit/termination/test_termination_action_callable.extended.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 26 | 2019-11-26T08:36:15.000Z | 2022-02-15T17:13:21.000Z | tests/unit/termination/test_termination_action_callable.extended.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | tests/unit/termination/test_termination_action_callable.extended.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 12 | 2019-09-08T00:03:05.000Z | 2022-02-23T21:28:35.000Z | /*
//@HEADER
// *****************************************************************************
//
// test_termination_action_callable.extended.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * 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 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.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#include "test_termination_action_common.h"
#if !defined INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H
#define INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H
namespace vt { namespace tests { namespace unit { namespace channel {
// set channel counting ranks
vt::NodeType root = vt::uninitialized_destination;
vt::NodeType node = vt::uninitialized_destination;
vt::NodeType all = vt::uninitialized_destination;
std::unordered_map<vt::EpochType,Data> data;
bool ok = false;
}}}} /* end namespace vt::tests::unit::channel */
namespace vt { namespace tests { namespace unit {
static bool finished[2] = {false, false};
static int num = 0;
// no need for a parameterized fixture
struct TestTermCallable : action::SimpleFixture {
void verify(int cur) {
int const nxt = (cur + 1) % 2;
EXPECT_FALSE(finished[cur]);
EXPECT_TRUE(not finished[nxt] or num == 1);
finished[cur] = true;
num++;
}
};
TEST_F(TestTermCallable, test_add_action_unique) /*NOLINT*/{
finished[0] = finished[1] = false;
num = 0;
vt::theCollective()->barrier();
// create an epoch and a related termination flag
auto epoch = ::vt::theTerm()->makeEpochCollective();
// assign an arbitrary action to be triggered at
// the end of the epoch and toggle the previous flag.
::vt::theTerm()->addActionEpoch(epoch, [=]{
vt_debug_print(
normal, term,
"current epoch:{:x} finished\n",
epoch
);
verify(0);
});
// assign a callable to be triggered after
// the action submitted for the given epoch.
::vt::theTerm()->addActionUnique(epoch, [=]{
vt_debug_print(
normal, term,
"trigger callable for epoch:{:x}\n",
epoch
);
verify(1);
});
if (channel::node == channel::root) {
action::compute(epoch);
}
::vt::theTerm()->finishedEpoch(epoch);
}
}}} // namespace vt::tests::unit::action
#endif /*INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H*/
| 33.521008 | 81 | 0.686388 | rbuch |
e1db765306c8fd4c768e4e067f6a786bb72a6504 | 6,932 | cxx | C++ | Testing/Code/Libraries/Old/TestStringMsg_General.cxx | NifTK/NiftyLink | b8b794afb682ffcdcf5181661fcf167989369a5d | [
"BSD-3-Clause"
] | 5 | 2015-05-10T14:09:34.000Z | 2021-02-23T03:35:51.000Z | Testing/Code/Libraries/Old/TestStringMsg_General.cxx | NifTK/NiftyLink | b8b794afb682ffcdcf5181661fcf167989369a5d | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/Libraries/Old/TestStringMsg_General.cxx | NifTK/NiftyLink | b8b794afb682ffcdcf5181661fcf167989369a5d | [
"BSD-3-Clause"
] | 1 | 2021-02-23T03:35:52.000Z | 2021-02-23T03:35:52.000Z | /*=============================================================================
NiftyLink: A software library to facilitate communication over OpenIGTLink.
Copyright (c) University College London (UCL). 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 in the top level directory for details.
=============================================================================*/
#include "stdlib.h"
#include <QDebug>
#include <QSettings>
#include <QDateTime>
#include "TestStringMsg_General.h"
#include <cmath>
TestStringMsg_General::TestStringMsg_General(void)
{
m_TestCounter = 0;
m_SuccessCounter = 0;
}
TestStringMsg_General::~TestStringMsg_General(void)
{
std::cerr << "Test class destructor";
}
void TestStringMsg_General::SetupTest()
{
//Nothing to do right now
}
void TestStringMsg_General::PerformTest()
{
//Create image message and initialize with test data
std::cout << ++m_TestCounter << ". Creating string message..";
NiftyLinkStringMessage::Pointer stringMsg;
stringMsg.reset();
stringMsg = (NiftyLinkStringMessage::Pointer(new NiftyLinkStringMessage()));
if (stringMsg.operator != (NULL))
{
std::cout << " OK\n";
m_SuccessCounter++;
}
else
{
std::cout << " FAILED\n";
}
//***********************************************
std::cout << ++m_TestCounter << ". Initializing with test data..";
stringMsg->InitializeWithTestData();
if (stringMsg->GetString() == QString("This is a test string"))
{
std::cout << " OK\n";
m_SuccessCounter++;
}
else
{
std::cout << " FAILED\n";
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting string..";
stringMsg->SetString("This is a random string which meant to crash the NiftyLink lib");
if (stringMsg->GetString() != QString("This is a random string which meant to crash the NiftyLink lib"))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting encoding..";
stringMsg->SetEncoding(3);
if (stringMsg->GetEncoding() != 3)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting timestamp and sender ID..";
stringMsg->Update(GetLocalHostAddress());
if (stringMsg->GetHostName().isEmpty() || stringMsg->GetTimeCreated().IsNull())
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting message type tag..";
stringMsg->ChangeMessageType("Something");
if (stringMsg->GetMessageType() != QString("Something"))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting port number..";
stringMsg->SetPort(100);
if (stringMsg->GetPort() != 100)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting receive timestamp..";
igtl::TimeStamp::Pointer tsr = igtl::TimeStamp::New();
igtl::TimeStamp::Pointer tss = igtl::TimeStamp::New();
tsr->Update();
stringMsg->SetTimeReceived(tsr);
tss = stringMsg->GetTimeReceived();
if (tsr->GetTimeInNanoSeconds() != tss->GetTimeInNanoSeconds())
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Checking create timestamp and id..";
igtl::TimeStamp::Pointer tsc = igtl::TimeStamp::New();
igtlUint64 id = 0;
tsc = stringMsg->GetTimeCreated();
id = stringMsg->GetId();
if (tsr->GetTimeInNanoSeconds() < tsc->GetTimeInNanoSeconds() || id <= 0)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Checking Update function and hostname..";
stringMsg->Update("Something");
QString hname = stringMsg->GetHostName();
stringMsg->ChangeHostName("Anything");
QString hname2 = stringMsg->GetHostName();
if (hname2 != QString("Anything") || hname != QString("Something"))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Checking message pointer get / set..";
igtl::MessageBase::Pointer mp = igtl::MessageBase::New();
igtl::MessageBase::Pointer mp3;
stringMsg->SetMessagePointer(mp);
stringMsg->GetMessagePointer(mp3);
if (mp != mp3)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Set resolution settings..";
NiftyLinkMessage::Pointer sttString;
sttString.reset();
NiftyLinkStringMessage::Create_STT(sttString);
sttString->SetResolution(100);
igtlUint64 res = 0;
sttString->GetResolution(res);
if (res != 100)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Deleting messages..";
stringMsg.reset();
stringMsg.operator = (NULL);
sttString.reset();
sttString.operator = (NULL);
if (sttString.operator != (NULL) || stringMsg.operator != (NULL))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
QuitTest();
}
void TestStringMsg_General::QuitTest()
{
emit Done();
if (m_TestCounter > m_SuccessCounter)
{
std::cout << "\n\n\n";
std::cout << "****************************************************\n";
std::cout << "**************** TESTING FINISHED: *****************\n";
std::cout << "***************** " << (m_TestCounter - m_SuccessCounter) << " TEST(S) FAILED *****************\n";
std::cout << "****************************************************\n";
exit(-1);
}
else
{
std::cout << "\n\n\n";
std::cout << "****************************************************\n";
std::cout << "**************** TESTING FINISHED: *****************\n";
std::cout << "********* ALL TESTS COMPLETED SUCCESSFULLY *********\n";
std::cout << "****************************************************\n";
exit(0);
}
}
| 25.207273 | 117 | 0.515436 | NifTK |
e1e44441baa81a3b81111f8dafa04a4ce0840b82 | 18 | cpp | C++ | tools/datadic_template_tail.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 15 | 2016-01-28T16:54:57.000Z | 2021-04-16T08:28:21.000Z | tools/datadic_template_tail.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | null | null | null | tools/datadic_template_tail.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 3 | 2016-07-16T05:22:11.000Z | 2020-04-03T08:59:26.000Z |
}
}
}
#endif
| 1.8 | 6 | 0.277778 | mariusherzog |
e1e586520cdaecdacf771e0c7269c75e3eaad61c | 3,940 | cpp | C++ | src/MetricsUploader/CaptureMetric.cpp | hrkrx/orbit | 47621f2ea6e5bba055861e1111addcb1d913a440 | [
"BSD-2-Clause"
] | 2 | 2020-07-31T08:18:58.000Z | 2021-12-26T06:43:07.000Z | src/MetricsUploader/CaptureMetric.cpp | hrkrx/orbit | 47621f2ea6e5bba055861e1111addcb1d913a440 | [
"BSD-2-Clause"
] | null | null | null | src/MetricsUploader/CaptureMetric.cpp | hrkrx/orbit | 47621f2ea6e5bba055861e1111addcb1d913a440 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2021 The Orbit 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 "MetricsUploader/CaptureMetric.h"
#include <chrono>
#include <cstdint>
#include <filesystem>
#include "OrbitBase/File.h"
#include "OrbitBase/Logging.h"
#include "orbit_log_event.pb.h"
namespace orbit_metrics_uploader {
CaptureMetric::CaptureMetric(MetricsUploader* uploader, const CaptureStartData& start_data)
: uploader_(uploader), start_(std::chrono::steady_clock::now()) {
CHECK(uploader_ != nullptr);
capture_data_.set_number_of_instrumented_functions(start_data.number_of_instrumented_functions);
capture_data_.set_number_of_frame_tracks(start_data.number_of_frame_tracks);
capture_data_.set_thread_states(start_data.thread_states);
capture_data_.set_memory_information_sampling_period_ms(
start_data.memory_information_sampling_period_ms);
capture_data_.set_lib_orbit_vulkan_layer(start_data.lib_orbit_vulkan_layer);
capture_data_.set_local_marker_depth_per_command_buffer(
start_data.local_marker_depth_per_command_buffer);
capture_data_.set_max_local_marker_depth_per_command_buffer(
start_data.max_local_marker_depth_per_command_buffer);
}
void CaptureMetric::SetCaptureCompleteData(const CaptureCompleteData& complete_data) {
capture_data_.set_number_of_instrumented_function_timers(
complete_data.number_of_instrumented_function_timers);
capture_data_.set_number_of_gpu_activity_timers(complete_data.number_of_gpu_activity_timers);
capture_data_.set_number_of_vulkan_layer_gpu_command_buffer_timers(
complete_data.number_of_vulkan_layer_gpu_command_buffer_timers);
capture_data_.set_number_of_vulkan_layer_gpu_debug_marker_timers(
complete_data.number_of_vulkan_layer_gpu_debug_marker_timers);
capture_data_.set_number_of_manual_start_timers(complete_data.number_of_manual_start_timers);
capture_data_.set_number_of_manual_stop_timers(complete_data.number_of_manual_stop_timers);
capture_data_.set_number_of_manual_start_async_timers(
complete_data.number_of_manual_start_async_timers);
capture_data_.set_number_of_manual_stop_async_timers(
complete_data.number_of_manual_stop_async_timers);
capture_data_.set_number_of_manual_tracked_value_timers(
complete_data.number_of_manual_tracked_value_timers);
file_path_ = complete_data.file_path;
}
bool CaptureMetric::SendCaptureFailed() {
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_);
capture_data_.set_duration_in_milliseconds(duration.count());
status_code_ = OrbitLogEvent_StatusCode_INTERNAL_ERROR;
return uploader_->SendCaptureEvent(capture_data_, status_code_);
}
bool CaptureMetric::SendCaptureCancelled() {
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_);
capture_data_.set_duration_in_milliseconds(duration.count());
status_code_ = OrbitLogEvent_StatusCode_CANCELLED;
return uploader_->SendCaptureEvent(capture_data_, status_code_);
}
bool CaptureMetric::SendCaptureSucceeded(std::chrono::milliseconds duration_in_milliseconds) {
capture_data_.set_duration_in_milliseconds(duration_in_milliseconds.count());
status_code_ = OrbitLogEvent_StatusCode_SUCCESS;
if (file_path_.empty()) {
ERROR("Unable to determine capture file size for metrics. File path is empty");
} else {
ErrorMessageOr<uint64_t> file_size = orbit_base::FileSize(file_path_);
if (file_size.has_error()) {
ERROR("Unable to determine capture file size for metrics. File: \"%s\"; error: %s",
file_path_.string(), file_size.error().message());
} else {
capture_data_.set_file_size(file_size.value());
}
}
return uploader_->SendCaptureEvent(capture_data_, status_code_);
}
} // namespace orbit_metrics_uploader | 45.813953 | 98 | 0.816497 | hrkrx |
e1e669e49acbe07063387bad419876c82e6f925c | 1,354 | hpp | C++ | include/kobuki_core/modules/sound.hpp | kobuki-base/kobuki_core | 5fb88169d010c3a23f24ff0ba7e9cb45b46b24e8 | [
"BSD-3-Clause"
] | 10 | 2020-06-01T05:05:27.000Z | 2022-01-18T13:19:58.000Z | include/kobuki_core/modules/sound.hpp | clalancette/kobuki_core | e5bef97d3c1db24441508673e08c67be599faa84 | [
"BSD-3-Clause"
] | 28 | 2020-01-10T14:42:54.000Z | 2021-07-28T08:01:44.000Z | include/kobuki_core/modules/sound.hpp | clalancette/kobuki_core | e5bef97d3c1db24441508673e08c67be599faa84 | [
"BSD-3-Clause"
] | 8 | 2020-02-04T09:59:18.000Z | 2021-08-29T01:59:38.000Z | /**
* @file /kobuki_core/include/kobuki_core/modules/sound.hpp
*
* @brief Flags and id's for commanding sound sequences.
*
* License: BSD
* https://raw.githubusercontent.com/kobuki-base/kobuki_core/license/LICENSE
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef KOBUKI_CORE_SOUND_HPP_
#define KOBUKI_CORE_SOUND_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace kobuki {
/*****************************************************************************
** Enums
*****************************************************************************/
enum SoundSequences
{
On = 0x0, /**< Turn on **/
Off = 0x1, /**< Turn off **/
Recharge = 0x2, /**< Recharging starting **/
Button = 0x3, /**< Button pressed **/
Error = 0x4, /**< Error sound **/
CleaningStart = 0x5, /**< Cleaning started **/
CleaningEnd = 0x6, /**< Cleaning ended **/
};
} // namespace kobuki
#endif /* KOBUKI_CORE_SOUND_HPP_ */
| 30.772727 | 78 | 0.350812 | kobuki-base |
e1e6ace46bd157efc2be7f99b06c0770221c0e2b | 8,282 | hh | C++ | grasp/run_trials.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 70 | 2018-10-17T17:37:22.000Z | 2022-02-28T15:19:47.000Z | grasp/run_trials.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 3 | 2020-12-08T13:02:17.000Z | 2022-02-22T11:59:00.000Z | grasp/run_trials.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 17 | 2018-10-29T04:09:45.000Z | 2022-03-19T11:34:55.000Z | /*!
\file grasp/run_trials.hh
\brief Performs grasp trials
Run full dynamic simulated grasp trials in Gazebo
\author João Borrego : jsbruglie
*/
#ifndef _RUN_TRIALS_HH_
#define _RUN_TRIALS_HH_
// Gazebo
#include <gazebo/gazebo_client.hh>
#include <gazebo/gazebo_config.h>
#include <gazebo/transport/transport.hh>
#include <gazebo/msgs/msgs.hh>
// I/O streams
#include <iostream>
// Threads
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
// Open YAML config files
#include "yaml-cpp/yaml.h"
// Custom messages
#include "MessageTypes.hh"
// Grasp representation
#include "Grasp.hh"
// Rest pose utils
#include "RestPose.hh"
// Interface for hand plugin
#include "Interface.hh"
// Tools
#include "object_utils.hh"
// Debug streams
#include "debug.hh"
// Randomiser class
#include "Randomiser.hh"
// GAP
// Custom messages
#include "dr_request.pb.h"
// Domain randomization plugin interface
#include "DRInterface.hh"
/// Config dictionary
typedef std::map<std::string,std::string> Config;
// Topics
/// Topic monitored by hand plugin for incoming requests
#define HAND_REQ_TOPIC "~/hand"
/// Topic for hand plugin responses
#define HAND_RES_TOPIC "~/hand/response"
/// Topic monitored by target plugin for incoming requests
#define TARGET_REQ_TOPIC "~/grasp/target"
/// Topic for target plugin responses
#define TARGET_RES_TOPIC "~/grasp/target/response"
/// Topic monitored by contacts plugin for incoming requests
#define CONTACT_REQ_TOPIC "~/grasp/contact"
/// Topic for contacts plugin responses
#define CONTACT_RES_TOPIC "~/grasp/contact/response"
/// Topic monitored by camera plugin for incoming requests
#define CAMERA_REQ_TOPIC "~/grasp/rgbd"
/// Topic for camera plugin responses
#define CAMERA_RES_TOPIC "~/grasp/rgbd/response"
/// Topic for Gazebo factory utility
#define FACTORY_TOPIC "~/factory"
/// Topic for generic Gazebo requests
#define REQUEST_TOPIC "~/request"
// Type enums
// Target Plugin
/// Get pose request
#define REQ_GET_POSE grasp::msgs::TargetRequest::GET_POSE
/// Set pose request
#define REQ_SET_POSE grasp::msgs::TargetRequest::SET_POSE
/// Update rest pose request
#define REQ_REST_POSE grasp::msgs::TargetRequest::GET_REST_POSE
/// Reset request
#define REQ_RESET grasp::msgs::TargetRequest::RESET
/// Current pose response
#define RES_POSE grasp::msgs::TargetResponse::POSE
/// Updated rest pose response
#define RES_REST_POSE grasp::msgs::TargetResponse::REST_POSE
// Camera plugin
/// Request to capture frame
#define REQ_CAPTURE grasp::msgs::CameraRequest::CAPTURE
// Hand plugin
/// Position control
#define POSITION grasp::msgs::Target::POSITION
/// Velocity control
#define VELOCITY grasp::msgs::Target::VELOCITY
/// Invalid grasp flag
#define INVALID_GRASP -1.0
// Message type definitions
/// Declaration for hand message type
typedef grasp::msgs::Hand HandMsg;
/// Shared pointer declaration for hand message type
typedef const boost::shared_ptr<const grasp::msgs::Hand>
HandMsgPtr;
/// Declaration for request message type
typedef grasp::msgs::TargetRequest TargetRequest;
/// Shared pointer declaration for request message type
typedef const boost::shared_ptr<const grasp::msgs::TargetRequest>
TargetRequestPtr;
/// Declaration for response message type
typedef grasp::msgs::TargetResponse TargetResponse;
/// Shared pointer declaration for response message type
typedef const boost::shared_ptr<const grasp::msgs::TargetResponse>
TargetResponsePtr;
/// Declaration for request aux message type
typedef grasp::msgs::CollisionRequest CollisionRequest;
/// Declaration for request message type
typedef grasp::msgs::ContactRequest ContactRequest;
/// Shared pointer declaration for request message type
typedef const boost::shared_ptr<const grasp::msgs::ContactRequest>
ContactRequestPtr;
/// Declaration for response message type
typedef grasp::msgs::ContactResponse ContactResponse;
/// Shared pointer declaration for response message type
typedef const boost::shared_ptr<const grasp::msgs::ContactResponse>
ContactResponsePtr;
/// Declaration for request message type
typedef grasp::msgs::CameraRequest CameraRequest;
/// Shared pointer declaration for request message type
typedef const boost::shared_ptr<const grasp::msgs::CameraRequest>
CameraRequestPtr;
/// Declaration for response message type
typedef grasp::msgs::CameraResponse CameraResponse;
/// Shared pointer declaration for response message type
typedef const boost::shared_ptr<const grasp::msgs::CameraResponse>
CameraResponsePtr;
//
// Argument parsing and setup
//
/// \brief Obtains usage string
/// \param argv_0 Name of the executable
/// \return String with command-line usage
const std::string getUsage(const char* argv_0);
/// \brief Parses command-line arguments
/// \param argc Argument count
/// \param argv Arguments
/// \param config Configuration YAML node
void parseArgs(
int argc,
char** argv,
Config & config);
/// \brief Sets up gazebo communication pubs/subs
/// \param node Gazebo communication node pointer
/// \param pubs Resulting map of publishers
/// \param subs Resulting map of subscribers
void setupCommunications(
gazebo::transport::NodePtr & node,
std::map<std::string, gazebo::transport::PublisherPtr> & pubs,
std::map<std::string, gazebo::transport::SubscriberPtr> & subs);
//
// File I/O
//
/// \brief Obtain list of models' names in dataset yml
/// \param targets Output list of model names
/// \param file_name Input dataset config yml
void obtainTargets(std::vector<std::string> & targets,
const std::string & file_name);
/// \brief Obtain list of grasps in yml files
/// \param grasp_cfg_dir Directory for grasp files
/// \param robot Target robot
/// \param object_name Target object name
/// \param grasps Output imported grasps
/// \returns Whether import was successful
bool importGrasps(const std::string & grasp_cfg_dir,
const std::string & robot,
const std::string & object_name,
std::vector<Grasp> & grasps);
/// \brief Export set of metrics to file
/// \param trials_out_dir Output directory
/// \param robot Target robot name
/// \param object_name Target object name
/// \param grasps Set of grasps to export to file
void exportGraspMetrics(const std::string & trials_out_dir,
const std::string & robot,
const std::string & object_name,
const std::vector<Grasp> & grasps);
//
// Gazebo plugin interaction
//
/// \brief Sets hand pose
/// \param pub Publisher to hand's topic
/// \param pose New hand pose
void setPose(gazebo::transport::PublisherPtr pub,
ignition::math::Pose3d pose,
double timeout=-1);
/// \brief Requests collisions in the world
/// \param pub Publisher to contact topic
/// \param target The target object name
/// \param hand The hand model name
void checkHandCollisions(gazebo::transport::PublisherPtr pub,
const std::string & hand,
std::vector<std::string> & targets);
/// \brief Closes manipulator fingers
/// \param pub Publisher to hand topic
/// \param timeout Timeout in seconds
/// \warning Applies force directly
void closeFingers(gazebo::transport::PublisherPtr pub,
double timeout=-1);
/// \brief Lifts robotic manipulator along positive z axis
/// \param pub Publisher to hand topic
/// \param timeout Timeout in seconds
void liftHand(gazebo::transport::PublisherPtr pub,
double timeout=-1);
/// \brief Resets target object to rest pose
/// \param pub Publisher to target's topic
void resetTarget(gazebo::transport::PublisherPtr pub);
/// \brief Attempts to grasp object
/// \param grasp The grasp configuration
/// \param pubs Map of publishers
/// \param model_name Target object model name
/// \return Grasp outcome metric
double tryGrasp(
Grasp & grasp,
Interface & interface,
std::map<std::string, gazebo::transport::PublisherPtr> & pubs,
const std::string & model_name);
// Synchronisation
/// \brief Waits for condition variable
/// \param timeout Timeout value in milliseconds
void waitForTrigger(int timeout=-1);
// Callback functions
/// TODO
void onHandResponse(HandMsgPtr & _msg);
/// TODO
void onTargetResponse(TargetResponsePtr & _msg);
/// TODO
void onContactResponse(ContactResponsePtr & _msg);
#endif
| 30.226277 | 68 | 0.746921 | el-cangrejo |
e1e6c3c90222d21e2cd1183d7dbcbe9a2f00091f | 504 | cpp | C++ | applications/image-viewer/main.cpp | harsh-kakasaniya55/skift | 79ccaf5398cfb7921599105607ad6688ece452d8 | [
"MIT"
] | 2 | 2021-08-14T16:03:48.000Z | 2021-11-09T10:29:36.000Z | applications/image-viewer/main.cpp | harsh-kakasaniya55/skift | 79ccaf5398cfb7921599105607ad6688ece452d8 | [
"MIT"
] | null | null | null | applications/image-viewer/main.cpp | harsh-kakasaniya55/skift | 79ccaf5398cfb7921599105607ad6688ece452d8 | [
"MIT"
] | 2 | 2020-10-13T14:25:30.000Z | 2020-10-13T14:39:40.000Z | #include <libwidget/Application.h>
#include <libwidget/Widgets.h>
int main(int argc, char **argv)
{
if (argc == 1)
return -1;
if (application_initialize(argc, argv) != SUCCESS)
return -1;
Window *window = new Window(WINDOW_RESIZABLE);
window->icon(Icon::get("image"));
window->title("Image Viewer");
window->size(Vec2i(700, 500));
new Image(window->root(), Bitmap::load_from_or_placeholder(argv[1]));
window->show();
return application_run();
}
| 21 | 73 | 0.634921 | harsh-kakasaniya55 |
e1ebe397a5498ffb928acb3bcdcba8ff0e5b1ec0 | 435 | cpp | C++ | src/logic/wire_get_inputs.cpp | nanolith/homesim | 693cd77c9ecd0fb8bbaf1848609a63eb56fa4b86 | [
"MIT"
] | null | null | null | src/logic/wire_get_inputs.cpp | nanolith/homesim | 693cd77c9ecd0fb8bbaf1848609a63eb56fa4b86 | [
"MIT"
] | null | null | null | src/logic/wire_get_inputs.cpp | nanolith/homesim | 693cd77c9ecd0fb8bbaf1848609a63eb56fa4b86 | [
"MIT"
] | null | null | null | /**
* \file logic/wire_get_inputs.cpp
*
* \brief Get the number of input connections on this wire.
*
* \copyright Copyright 2020 Justin Handville. All rights reserved.
*/
#include <homesim/wire.h>
using namespace homesim;
using namespace std;
/**
* \brief Get the number of input connections associated with this wire.
*
* \brief return the number of inputs.
*/
int homesim::wire::get_inputs() const
{
return inputs;
}
| 19.772727 | 72 | 0.710345 | nanolith |
e1f7492f415d27eb623bdbd87f7ec7406853a1ad | 2,747 | hpp | C++ | OcularEditor/include/Widgets/Standard/LineEdit.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 8 | 2017-01-27T01:06:06.000Z | 2020-11-05T20:23:19.000Z | OcularEditor/include/Widgets/Standard/LineEdit.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 39 | 2016-06-03T02:00:36.000Z | 2017-03-19T17:47:39.000Z | OcularEditor/include/Widgets/Standard/LineEdit.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 4 | 2019-05-22T09:13:36.000Z | 2020-12-01T03:17:45.000Z | /**
* Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef __H__OCULAR_EDITOR_LINE_EDIT__H__
#define __H__OCULAR_EDITOR_LINE_EDIT__H__
#include <QtWidgets/qlineedit.h>
//------------------------------------------------------------------------------------------
/**
* \addtogroup Ocular
* @{
*/
namespace Ocular
{
/**
* \addtogroup Editor
* @{
*/
namespace Editor
{
enum class LineType
{
String = 0,
Int8,
UInt8,
Int16,
UInt16,
Int32,
UInt32,
Float,
Double
};
/**
* \class LineEdit
*
* Helper class that automatically handles input mask, etc. setup based
* on the specified LineType.
*/
class LineEdit : public QLineEdit
{
Q_OBJECT
public:
LineEdit(LineType type, QWidget* parent = nullptr);
virtual ~LineEdit();
/**
* \param[in] reset If TRUE, then the edited flag is reset back to FALSE.
* \return TRUE if the user has modifed this edit (return key was pressed).
*/
bool wasEdited(bool reset = true);
/**
*
*/
void setInvalid(bool invalid);
/**
*
*/
int32_t asInt() const;
/**
*
*/
uint32_t asUint() const;
/**
*
*/
float asFloat() const;
template<typename T>
T as() const { return OcularString->fromString<T>(text().toStdString()); }
protected:
private slots:
void contentsChanged(QString const& text);
void userEdited(QString const& text);
private:
LineType m_Type;
bool m_WasEdited;
};
}
/**
* @} End of Doxygen Groups
*/
}
/**
* @} End of Doxygen Groups
*/
//------------------------------------------------------------------------------------------
#endif | 23.478632 | 92 | 0.488533 | ssell |
e1fa970b57e33dfee8949461c014256eba122678 | 7,196 | cc | C++ | server.cc | ctiller/ced-1 | 8aa0bb3431988c7f13a0e5a40f378e8e9fa0066b | [
"Apache-2.0"
] | null | null | null | server.cc | ctiller/ced-1 | 8aa0bb3431988c7f13a0e5a40f378e8e9fa0066b | [
"Apache-2.0"
] | null | null | null | server.cc | ctiller/ced-1 | 8aa0bb3431988c7f13a0e5a40f378e8e9fa0066b | [
"Apache-2.0"
] | 1 | 2021-11-29T13:02:11.000Z | 2021-11-29T13:02:11.000Z | // Copyright 2017 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "server.h"
#include <grpc++/security/server_credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <map>
#include "absl/synchronization/mutex.h"
#include "application.h"
#include "buffer.h"
#include "log.h"
#include "proto/project_service.grpc.pb.h"
#include "run.h"
#include "src_hash.h"
class ProjectServer : public Application, public ProjectService::Service {
public:
ProjectServer(int argc, char** argv)
: project_(PathFromArgs(argc, argv), false),
active_requests_(0),
last_activity_(absl::Now()),
quit_requested_(false) {
if (PathFromArgs(argc, argv) !=
project_.aspect<ProjectRoot>()->LocalAddressPath()) {
throw std::runtime_error(absl::StrCat(
"Project path misalignment: ", PathFromArgs(argc, argv).string(), " ",
project_.aspect<ProjectRoot>()->LocalAddressPath().string()));
}
server_ =
grpc::ServerBuilder()
.RegisterService(this)
.AddListeningPort(project_.aspect<ProjectRoot>()->LocalAddress(),
grpc::InsecureServerCredentials())
.BuildAndStart();
Log() << "Created server " << server_.get() << " @ "
<< project_.aspect<ProjectRoot>()->LocalAddress();
}
int Run() override {
auto done = [this]() {
mu_.AssertHeld();
return active_requests_ == 0 &&
(quit_requested_ ||
(absl::Now() - last_activity_ > absl::Hours(1)));
};
{
absl::MutexLock lock(&mu_);
while (!mu_.AwaitWithTimeout(absl::Condition(&done),
absl::Duration(absl::Minutes(1))))
;
}
server_->Shutdown();
return 0;
}
grpc::Status ConnectionHello(grpc::ServerContext* context,
const ConnectionHelloRequest* req,
ConnectionHelloResponse* rsp) override {
rsp->set_src_hash(ced_src_hash);
return grpc::Status::OK;
}
grpc::Status Quit(grpc::ServerContext* context, const Empty* req,
Empty* rsp) override {
absl::MutexLock lock(&mu_);
quit_requested_ = true;
return grpc::Status::OK;
}
grpc::Status Edit(
grpc::ServerContext* context,
grpc::ServerReaderWriter<EditMessage, EditMessage>* stream) override {
ScopedRequest scoped_request(this);
EditMessage msg;
if (!stream->Read(&msg)) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"Stream closed with no greeting");
}
if (msg.type_case() != EditMessage::kClientHello) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"First message from client must be ClientHello");
}
Buffer* buffer = GetBuffer(msg.client_hello().buffer_name());
if (!buffer) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"Unable to access requested buffer");
}
Site site;
auto listener = buffer->Listen(
[stream, &site](const AnnotatedString& initial) {
EditMessage out;
auto body = out.mutable_server_hello();
body->set_site_id(site.site_id());
*body->mutable_current_state() = initial.AsProto();
stream->Write(out);
},
[stream](const CommandSet* commands) {
EditMessage out;
*out.mutable_commands() = *commands;
stream->Write(out);
});
while (stream->Read(&msg)) {
if (msg.type_case() != EditMessage::kCommands) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"Expected commands after greetings");
}
buffer->PushChanges(&msg.commands(), true);
}
CommandSet cleanup_commands;
buffer->ContentSnapshot().MakeDeleteAttributesBySite(&cleanup_commands,
site);
buffer->PushChanges(&msg.commands(), false);
return grpc::Status::OK;
}
private:
Project project_;
std::unique_ptr<grpc::Server> server_;
absl::Mutex mu_;
int active_requests_ GUARDED_BY(mu_);
absl::Time last_activity_ GUARDED_BY(mu_);
std::map<boost::filesystem::path, std::unique_ptr<Buffer>> buffers_
GUARDED_BY(mu_);
bool quit_requested_ GUARDED_BY(mu_);
static bool IsChildOf(boost::filesystem::path needle,
boost::filesystem::path haystack) {
needle = boost::filesystem::absolute(needle);
haystack = boost::filesystem::absolute(haystack);
if (haystack.filename() == ".") {
haystack.remove_filename();
}
if (!needle.has_filename()) return false;
needle.remove_filename();
std::string needle_str = needle.string();
std::string haystack_str = haystack.string();
if (needle_str.length() > haystack_str.length()) return false;
return std::equal(haystack_str.begin(), haystack_str.end(),
needle_str.begin());
}
Buffer* GetBuffer(boost::filesystem::path path) {
path = boost::filesystem::absolute(path);
if (!IsChildOf(path, project_.aspect<ProjectRoot>()->Path())) {
Log() << "Attempt to access outside of project sandbox: " << path
<< " in project root " << project_.aspect<ProjectRoot>()->Path();
return nullptr;
}
absl::MutexLock lock(&mu_);
auto it = buffers_.find(path);
if (it != buffers_.end()) {
return it->second.get();
}
return buffers_
.emplace(
path,
Buffer::Builder().SetFilename(path).SetProject(&project_).Make())
.first->second.get();
}
class ScopedRequest {
public:
explicit ScopedRequest(ProjectServer* p) : p_(p) {
absl::MutexLock lock(&p_->mu_);
p_->active_requests_++;
p_->last_activity_ = absl::Now();
}
~ScopedRequest() {
absl::MutexLock lock(&p_->mu_);
p_->active_requests_--;
p_->last_activity_ = absl::Now();
}
private:
ProjectServer* const p_;
};
static boost::filesystem::path PathFromArgs(int argc, char** argv) {
if (argc != 2) throw std::runtime_error("Expected path");
return argv[1];
}
};
REGISTER_APPLICATION(ProjectServer);
void SpawnServer(const boost::filesystem::path& ced_bin,
const Project& project) {
run_daemon(
ced_bin,
{
"-mode",
"ProjectServer",
"-logfile",
(project.aspect<ProjectRoot>()->LocalAddressPath().parent_path() /
absl::StrCat(".cedlog.server.", ced_src_hash))
.string(),
project.aspect<ProjectRoot>()->LocalAddressPath().string(),
});
}
| 33.16129 | 80 | 0.61159 | ctiller |
e1fbbb0c416b02c0f612fd77c7f33b56e69190bc | 1,723 | cpp | C++ | src/Translater/PassManager.cpp | elite-lang/Elite | f65998863bb13c247c27c781b0cdb4cfc6ba8ae3 | [
"MIT"
] | 48 | 2015-12-28T01:42:57.000Z | 2022-03-11T02:59:17.000Z | src/Translater/PassManager.cpp | elite-lang/Elite | f65998863bb13c247c27c781b0cdb4cfc6ba8ae3 | [
"MIT"
] | 17 | 2015-12-16T07:43:52.000Z | 2016-04-17T12:30:48.000Z | src/Translater/PassManager.cpp | elite-lang/Elite | f65998863bb13c247c27c781b0cdb4cfc6ba8ae3 | [
"MIT"
] | 14 | 2015-12-22T06:54:14.000Z | 2020-12-02T06:39:45.000Z |
#include "Elite/Translater/PassManager.h"
#include "Elite/CodeGen/ICodeGenContext.h"
PassManager::PassManager () {
}
PassManager::~PassManager () {
}
void PassManager::NewPassList(const string& name, const vector<Pass*>& vec) {
NewPassList(name, list<Pass*>(vec.begin(), vec.end()));
}
void PassManager::NewPassList(const string& name, const list<Pass*>& lst) {
pass_lists[name] = lst;
}
list<Pass*>* PassManager::getPassList(const string& name) {
auto idx = pass_lists.find(name);
if (idx != pass_lists.end()) return &(idx->second);
return NULL;
}
void PassManager::RunPassList(const string& name, Node* node, ICodeGenContext* ctx) {
auto idx = pass_lists.find(name);
if (idx != pass_lists.end()) {
for (auto i : idx->second) {
// 设置i为活动pass
ctx->setNowPass(i);
ctx->MacroMake(node);
}
}
}
void PassManager::RunPassListWithSet(const string& name, set<Node*>& nodes, ICodeGenContext* ctx) {
auto idx = pass_lists.find(name);
if (idx != pass_lists.end()) {
for (auto i : idx->second) {
// 设置i为活动pass
ctx->setNowPass(i);
for (auto node : nodes)
ctx->MacroMake(node);
}
}
}
extern const FuncReg macro_funcs[];
extern const FuncReg macro_classes[];
extern const FuncReg macro_prescan[];
extern const FuncReg macro_pretype[];
extern const FuncReg macro_defmacro[];
void PassManager::LoadDefaultLists() {
list<Pass*> prescan = { new Pass(macro_defmacro), new Pass(macro_prescan), new Pass(macro_pretype) };
list<Pass*> main = { new Pass(macro_funcs, macro_classes) };
NewPassList("prescan", prescan);
NewPassList("main", main);
}
| 24.971014 | 105 | 0.641323 | elite-lang |
e1fdf3d085af806f32cd1bd4beaa15f487a45f64 | 2,975 | cpp | C++ | src/process_start.cpp | ValentinSidorov/DeLorean_Team | 921eb12d96d202c4c19fded3cf190abcbd075af0 | [
"MIT"
] | null | null | null | src/process_start.cpp | ValentinSidorov/DeLorean_Team | 921eb12d96d202c4c19fded3cf190abcbd075af0 | [
"MIT"
] | 20 | 2022-01-29T13:13:09.000Z | 2022-02-23T09:52:55.000Z | src/process_start.cpp | ValentinSidorov/DeLorean_Team | 921eb12d96d202c4c19fded3cf190abcbd075af0 | [
"MIT"
] | 1 | 2022-02-01T20:43:35.000Z | 2022-02-01T20:43:35.000Z | #include "process_start.h"
pid_t start_process(set_prog_start &program) {
pid_t process_pid;
// create new process
process_pid = fork();
if (process_pid == -1) {
// error of creation process
LOG("Error in process_start. Function fork(), couldn't do fork, for "
"program_name: " +
program.name,
ERROR);
return 0;
} else if (process_pid != 0) {
// parent process
// return child pid
return process_pid;
} else {
// child process
// number of process arguments(first - program name, last - NULL)
int argc = program.cmd_arguments.size() + 2;
// pointer to process arguments
char **argv = new char *[argc];
// first argument - program name
int word_length = 0;
word_length = program.name.length() + 1;
argv[0] = new char[word_length];
// copy program name to arguments array
strncpy(argv[0], program.name.c_str(), word_length);
// copy all arguments to arguments array
for (int i = 1; i < argc - 1; i++) {
word_length = program.cmd_arguments[i - 1].length() + 1;
argv[i] = new char[word_length];
strncpy(argv[i], program.cmd_arguments[i - 1].c_str(), word_length);
}
// last arguments - NULL
argv[argc - 1] = nullptr;
// check if we need to redirect programm's stdout
if (program.stdout_config_file.size() != 0) {
// change file mode depending of stdout_mode config
char file_mode = 0;
if (program.stdout_config_truncate) {
// true - truncate
file_mode = 'w';
} else {
// false - append
file_mode = 'a';
}
// open a log file
if (!freopen(program.stdout_config_file.c_str(), &file_mode, stdout)) {
// it doesn't open
// close stdout
fclose(stdout);
LOG("Error in process_start. Function freopen(), couldn't open stdout "
"config "
"file: " +
program.stdout_config_file,
ERROR);
}
}
// change run program status
program.pid = getpid();
// start new process(change current process to new)
if (execv(program.executable_path.c_str(), argv) == -1) {
// error occurred, program isn't executed
//!!! stdout stream doesn't work here(redirected to file)
// change run program status
program.pid = 0;
// delete argv array
for (int i = 0; i < argc; i++) {
delete[] argv[i];
}
delete[] argv;
argv = nullptr;
// add error info
std::string error_message("Error in proscess_start. Function execv()\n");
error_message += "Couldn't start program: " + program.name + "\n";
error_message +=
"Executable path = " + program.executable_path + "\nError info: ";
error_message.append(strerror(errno));
LOG(error_message, ERROR);
exit(1);
}
// these line is never reached(things below just for cppchecker)
delete[] argv;
return -1;
}
} | 33.806818 | 79 | 0.594286 | ValentinSidorov |
c006290aa4aef27a1aea1ab0b9a1e1cd5939ffed | 827 | cpp | C++ | old_solutions/maximising_xor.cpp | DSC-JSS-NOIDA/competitive | aa8807db24df389e52ba66dd0c5847e60237930b | [
"Apache-2.0"
] | null | null | null | old_solutions/maximising_xor.cpp | DSC-JSS-NOIDA/competitive | aa8807db24df389e52ba66dd0c5847e60237930b | [
"Apache-2.0"
] | null | null | null | old_solutions/maximising_xor.cpp | DSC-JSS-NOIDA/competitive | aa8807db24df389e52ba66dd0c5847e60237930b | [
"Apache-2.0"
] | 7 | 2018-10-25T12:13:25.000Z | 2020-10-01T18:09:05.000Z | #include <bits/stdc++.h>
using namespace std;
// Complete the maximizingXor function below.
int maximizingXor(int l, int r) {
// get xor of limits
int LXR = L ^ R;
// loop to get msb position of L^R
int msbPos = 0;
while (LXR)
{
msbPos++;
LXR >>= 1;
}
// construct result by adding 1,
// msbPos times
int maxXOR = 0;
int two = 1;
while (msbPos--)
{
maxXOR += two;
two <<= 1;
}
return maxXOR;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int l;
cin >> l;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int r;
cin >> r;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int result = maximizingXor(l, r);
fout << result << "\n";
fout.close();
return 0;
}
| 15.603774 | 56 | 0.523579 | DSC-JSS-NOIDA |
c008cb026c37e421c9857f545fa8321eb5b33ec0 | 6,641 | cxx | C++ | Rendering/OpenGL2/vtkToneMappingPass.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkToneMappingPass.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkToneMappingPass.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkToneMappingPass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkToneMappingPass.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLFramebufferObject.h"
#include "vtkOpenGLQuadHelper.h"
#include "vtkOpenGLRenderUtilities.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLState.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkShaderProgram.h"
#include "vtkTextureObject.h"
vtkStandardNewMacro(vtkToneMappingPass);
// ----------------------------------------------------------------------------
vtkToneMappingPass::~vtkToneMappingPass()
{
if (this->FrameBufferObject)
{
vtkErrorMacro("FrameBufferObject should have been deleted in ReleaseGraphicsResources().");
}
if (this->ColorTexture)
{
vtkErrorMacro("ColorTexture should have been deleted in ReleaseGraphicsResources().");
}
if (this->QuadHelper)
{
vtkErrorMacro("QuadHelper should have been deleted in ReleaseGraphicsResources().");
}
}
// ----------------------------------------------------------------------------
void vtkToneMappingPass::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "FrameBufferObject:";
if(this->FrameBufferObject!=nullptr)
{
this->FrameBufferObject->PrintSelf(os,indent);
}
else
{
os << "(none)" <<endl;
}
os << indent << "ColorTexture:";
if(this->ColorTexture!=nullptr)
{
this->ColorTexture->PrintSelf(os,indent);
}
else
{
os << "(none)" <<endl;
}
}
// ----------------------------------------------------------------------------
void vtkToneMappingPass::Render(const vtkRenderState* s)
{
vtkOpenGLClearErrorMacro();
this->NumberOfRenderedProps = 0;
vtkRenderer* r = s->GetRenderer();
vtkOpenGLRenderWindow* renWin = static_cast<vtkOpenGLRenderWindow*>(r->GetRenderWindow());
vtkOpenGLState* ostate = renWin->GetState();
vtkOpenGLState::ScopedglEnableDisable bsaver(ostate, GL_BLEND);
vtkOpenGLState::ScopedglEnableDisable dsaver(ostate, GL_DEPTH_TEST);
if (this->DelegatePass == nullptr)
{
vtkWarningMacro("no delegate in vtkToneMappingPass.");
return;
}
// create FBO and texture
int x, y, w, h;
r->GetTiledSizeAndOrigin(&w, &h, &x, &y);
if (this->ColorTexture == nullptr)
{
this->ColorTexture = vtkTextureObject::New();
this->ColorTexture->SetContext(renWin);
this->ColorTexture->SetMinificationFilter(vtkTextureObject::Linear);
this->ColorTexture->SetMagnificationFilter(vtkTextureObject::Linear);
this->ColorTexture->Allocate2D(w, h, 4, VTK_FLOAT);
}
this->ColorTexture->Resize(w, h);
if (this->FrameBufferObject == nullptr)
{
this->FrameBufferObject = vtkOpenGLFramebufferObject::New();
this->FrameBufferObject->SetContext(renWin);
}
renWin->GetState()->PushFramebufferBindings();
this->RenderDelegate(s, w, h, w, h, this->FrameBufferObject, this->ColorTexture);
renWin->GetState()->PopFramebufferBindings();
if (this->QuadHelper &&
static_cast<unsigned int>(this->ToneMappingType) != this->QuadHelper->ShaderChangeValue)
{
delete this->QuadHelper;
this->QuadHelper = nullptr;
}
if (!this->QuadHelper)
{
std::string FSSource = vtkOpenGLRenderUtilities::GetFullScreenQuadFragmentShaderTemplate();
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Decl",
"uniform sampler2D source;\n"
"//VTK::FSQ::Decl");
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"vec4 pixel = texture2D(source, texCoord);\n"
" float Y = 0.2126 * pixel.r + 0.7152 * pixel.g + 0.0722 * pixel.b;\n"
" //VTK::FSQ::Impl");
switch (this->ToneMappingType)
{
case Clamp:
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"float scale = min(Y, 1.0) / Y;\n"
" //VTK::FSQ::Impl");
break;
case Reinhard:
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"float scale = 1.0 / (Y + 1.0);\n"
" //VTK::FSQ::Impl");
break;
case Exponential:
vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Decl", "uniform float exposure;\n");
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"float scale = (1.0 - exp(-Y*exposure)) / Y;\n"
" //VTK::FSQ::Impl");
break;
}
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"gl_FragData[0] = vec4(pixel.rgb * scale, pixel.a);");
this->QuadHelper = new vtkOpenGLQuadHelper(renWin,
vtkOpenGLRenderUtilities::GetFullScreenQuadVertexShader().c_str(),
FSSource.c_str(),
"");
this->QuadHelper->ShaderChangeValue = this->ToneMappingType;
}
else
{
renWin->GetShaderCache()->ReadyShaderProgram(this->QuadHelper->Program);
}
if (!this->QuadHelper->Program || !this->QuadHelper->Program->GetCompiled())
{
vtkErrorMacro("Couldn't build the shader program.");
return;
}
this->ColorTexture->Activate();
this->QuadHelper->Program->SetUniformi("source", this->ColorTexture->GetTextureUnit());
if (this->ToneMappingType == Exponential)
{
this->QuadHelper->Program->SetUniformf("exposure", this->Exposure);
}
ostate->vtkglDisable(GL_BLEND);
ostate->vtkglDisable(GL_DEPTH_TEST);
ostate->vtkglViewport(x, y, w, h);
ostate->vtkglScissor(x, y, w, h);
this->QuadHelper->Render();
this->ColorTexture->Deactivate();
vtkOpenGLCheckErrorMacro("failed after Render");
}
// ----------------------------------------------------------------------------
void vtkToneMappingPass::ReleaseGraphicsResources(vtkWindow* w)
{
this->Superclass::ReleaseGraphicsResources(w);
if (this->QuadHelper)
{
delete this->QuadHelper;
this->QuadHelper = nullptr;
}
if (this->FrameBufferObject)
{
this->FrameBufferObject->Delete();
this->FrameBufferObject = nullptr;
}
if (this->ColorTexture)
{
this->ColorTexture->Delete();
this->ColorTexture = nullptr;
}
}
| 29.127193 | 96 | 0.630778 | fluentgcc |
c00c44b3e79aee6709158d4e5a40ec54b0ace1fc | 401 | hh | C++ | PacDisplay/PacDispCyl.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDisplay/PacDispCyl.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDisplay/PacDispCyl.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | #ifndef PacDispCyl_HH
#define PacDispCyl_HH
#include <stdio.h>
#include <Rtypes.h>
#define STRINGSIZE 100
struct PacDispCyl {
virtual ~PacDispCyl() {;}
Double_t radius,thickness,lowZ,hiZ;
Int_t imat;
PacDispCyl():radius(-1.0),thickness(-1.0),lowZ(-1.0),hiZ(1.0){}
static const char* rootnames() {
return "radius/D:thick/D:lowZ/D:hiZ/D:imat/I";
}
ClassDef(PacDispCyl,1)
};
#endif
| 19.095238 | 65 | 0.690773 | brownd1978 |
84fed91bc7e65bdaacb76e5e3d29b1e08aa706d0 | 3,592 | cpp | C++ | GitCommit.cpp | simoc/wyag | e94edb6e9ef2aa650d88b59c428a667ef7fe3d59 | [
"MIT"
] | null | null | null | GitCommit.cpp | simoc/wyag | e94edb6e9ef2aa650d88b59c428a667ef7fe3d59 | [
"MIT"
] | null | null | null | GitCommit.cpp | simoc/wyag | e94edb6e9ef2aa650d88b59c428a667ef7fe3d59 | [
"MIT"
] | null | null | null | #include <algorithm>
#include "GitCommit.h"
GitCommit::GitCommit(GitRepository *repo) :
GitObject(repo, "commit")
{
}
GitCommit::GitCommit(GitRepository *repo, const std::string &fmt) :
GitObject(repo, fmt)
{
}
std::vector<unsigned char>
GitCommit::serialize()
{
return kvlm_serialize();
}
void
GitCommit::deserialize(const std::vector<unsigned char> &data)
{
m_dct.clear();
kvlm_parse(data, 0, m_dct);
}
std::vector<std::string>
GitCommit::get_value(const std::string &key)
{
auto it = m_dct.find(key);
if (it == m_dct.end())
return std::vector<std::string>();
return it->second;
}
std::string
GitCommit::replace_all(const std::string &s,
const std::string &before, const std::string &after)
{
std::string s2 = s;
size_t idx = s2.find(before);
while (idx != std::string::npos)
{
s2.replace(idx, before.size(), after);
idx = s2.find(before, idx + after.size());
}
return s2;
}
void
GitCommit::kvlm_parse(const std::vector<unsigned char> &raw, size_t start,
std::map<std::string, std::vector<std::string> > &dct)
{
// We search for the next space and the next newline.
int spc = -1;
int nl = -1;
const char space = ' ';
const char newline = '\n';
auto it1 = std::find(raw.begin() + start, raw.end(), space);
if (it1 != raw.end())
{
spc = it1 - raw.begin();
}
auto it2 = std::find(raw.begin() + start, raw.end(), newline);
if (it2 != raw.end())
{
nl = it2 - raw.begin();
}
// If space appears before newline, we have a keyword.
// Base case
// =========
// If newline appears first (or there's no space at all, in which
// case find returns -1), we assume a blank line. A blank line
// means the remainder of the data is the message.
if ((spc < 0) || (nl < spc))
{
std::string value;
value.append(raw.begin() + start + 1, raw.end());
std::vector values{value};
dct.insert({std::string(), values});
return;
}
// Recursive case
// ==============
// we read a key-value pair and recurse for the next.
std::string key;
key.append(raw.begin() + start, raw.begin() + spc);
// Find the end of the value. Continuation lines begin with a
// space, so we loop until we find a '\n' not followed by a space.
size_t ending = start;
while (true)
{
auto it3 = std::find(raw.begin() + ending + 1,
raw.end(), newline);
if (it3 == raw.end())
break;
ending = it3 - raw.begin();
if (*(it3 + 1) != space)
{
break;
}
}
// Grab the value
// Also, drop the leading space on continuation lines
std::string value;
value.append(raw.begin() + spc + 1, raw.begin() + ending);
value = replace_all(value, "\n ", "\n");
// Don't overwrite existing data contents
auto it4 = dct.find(key);
if (it4 != dct.end())
{
it4->second.push_back(value);
}
else
{
std::vector values{value};
dct.insert({key, values});
}
kvlm_parse(raw, ending + 1, dct);
}
std::vector<unsigned char>
GitCommit::kvlm_serialize()
{
std::vector<unsigned char> ret;
std::vector<std::string> message;
for (auto it = m_dct.begin(); it != m_dct.end(); it++)
{
std::string key = it->first;
if (key.empty())
{
// Skip the message itself
message = it->second;
continue;
}
std::vector<std::string> val = it->second;
for (const std::string &v : val)
{
for (const char &c : key)
{
ret.push_back(c);
}
ret.push_back(' ');
std::string v2 = replace_all(v, "\n", "\n ");
for (const char &c : v2)
{
ret.push_back(c);
}
}
}
// Append message
ret.push_back('\n');
for (const std::string &v : message)
{
for (const char &c : v)
{
ret.push_back(c);
}
}
return ret;
}
| 20.525714 | 74 | 0.618875 | simoc |
84feeddd9fc64f33ff581e2c95eadc893772466f | 6,128 | cpp | C++ | src/Extensions/Sampler/SamplerPanel.cpp | Freaxed/xrs-haiku | 74617bc5740fc15b165686a14894d4382096fad3 | [
"BSD-3-Clause"
] | 1 | 2022-03-25T15:40:45.000Z | 2022-03-25T15:40:45.000Z | src/Extensions/Sampler/SamplerPanel.cpp | Freaxed/xrs-haiku | 74617bc5740fc15b165686a14894d4382096fad3 | [
"BSD-3-Clause"
] | null | null | null | src/Extensions/Sampler/SamplerPanel.cpp | Freaxed/xrs-haiku | 74617bc5740fc15b165686a14894d4382096fad3 | [
"BSD-3-Clause"
] | null | null | null | /*
*
* Copyright 2006-2022, Andrea Anzani.
* Distributed under the terms of the MIT License.
*
* Authors:
* Andrea Anzani <andrea.anzani@gmail.com>
*/
#include "SamplerPanel.h"
#include "Sample.h"
#include "SamplerTrackBoost.h"
#include "GlobalDef.h"
#include "GfxMsg.h"
#include "SamplerTrack.h"
#include "Xed_Utils.h"
#include "sampler_locale.h"
#include "XDigit.h"
#include "XHost.h"
#define REMOVE 'remv'
#define REMOVEALL 'rema'
#define LOADEXT 'loae'
#define REL_MSG 'note'
#define REV_ON 'reo'
#define PIT_ON 'pio'
#define BOOST_ON 'boo'
#define MOD 'mod'
#define LOOP_ON 'loop'
SamplerPanel::SamplerPanel(SamplerTrackBoost* sb):
PlugPanel(), sampTrack(NULL), booster(sb)
{
BBox *sam_box= new BBox(BRect(10,150+17,171,210+17) ,"toolbar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP,
B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP, B_FANCY_BORDER);
BBox *sampler= new BBox(BRect(8,18,172,50) ,"toolbar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP,
B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP, B_FANCY_BORDER);
menu=new BMenu(" ");
menu->AddItem(booster->getMenu());
menu->AddItem(new BMenuItem(T_SAMPLER_LOAD,new BMessage(LOADEXT)));
menu->AddItem(new BMenuItem(T_SAMPLER_REMOVE,new BMessage(REMOVE)));
menu->AddItem(new BMenuItem(T_SAMPLER_REMOVE_ALL,new BMessage(REMOVEALL)));
BRect r(sampler->Bounds());
r.InsetBy(4,4);
field=new BMenuField(r,""," ",menu);
pit_box= new BBox(BRect(8,70-13,172,102-13), "");
r=(pit_box->Bounds());
r.InsetBy(4,4);
r.right-=50;
r.top+=2;
pit_box->AddChild(pit_ck=new BCheckBox(r,"",T_SAMPLER_STRECH,new BMessage(PIT_ON)));
pit_ck->SetValue(0);
pit_ck->SetFontSize(12);
pit_box->AddChild(shift=new XDigit(BRect(120,5,120+36,5+21), VID_EMPTY, "sampler_shift_xdigit", new BMessage(MOD),1,32));
r=(pit_box->Frame());
r.OffsetBy(0,38);
AddChild(pit_box);
pit_box= new BBox(r, "2");
r=(pit_box->Bounds());
r.InsetBy(4,4);
r.right-=50;
r.top+=2;
pit_box->AddChild(boost_ck=new BCheckBox(r,"",T_SAMPLER_BOOST,new BMessage(BOOST_ON)));
boost_ck->SetValue(0);
boost_ck->SetFontSize(12);
pit_box->AddChild(depth=new XDigit(BRect(120,5,120+36,5+21), VID_EMPTY, "sampler_boost", new BMessage(REL_MSG),1,4));
r=(pit_box->Frame());
r.OffsetBy(0,38);
AddChild(pit_box);
pit_box= new BBox(r, "3");
r=(pit_box->Bounds());
r.InsetBy(4,4);
r.right -= 75;
r.top += 2;
pit_box->AddChild(rev = new BCheckBox(r,"rev_check",T_SAMPLER_REVERSE,new BMessage(TRACK_REV)));
rev->SetValue(0);
rev->SetFontSize(12);
rev->ResizeToPreferred();
r.OffsetBy(r.Width(), 0);
pit_box->AddChild(loop_ck = new BCheckBox(r,"loop_check","Loop", new BMessage(LOOP_ON)));
loop_ck->SetValue(0);
loop_ck->SetFontSize(12);
loop_ck->ResizeToPreferred();
AddChild(pit_box);
sw=new SampleView(BRect(1,1,159,58), XUtils::GetBitmap(18));
sam_box->AddChild(sw);
sampler->AddChild(field);
AddChild(sampler);
AddChild(sam_box);
my_sample=NULL;
rev->SetValue(false);
menu->Superitem()->SetLabel(T_SAMPLER_NOSELECTED);
}
void
SamplerPanel::ResetToTrack(Track* trk)
{
//qui magari un bel check dell'ID ??
PlugPanel::ResetToTrack(trk);
SetTrack((SamplerTrack*)trk);
}
void
SamplerPanel::AttachedToWindow()
{
PlugPanel::AttachedToWindow();
depth->SetTarget(this);
shift->SetTarget((BView*)this);
pit_ck->SetTarget(this);
rev->SetTarget(this);
menu->SetTargetForItems(this);
boost_ck->SetTarget(this);
loop_ck->SetTarget(this);
field->SetDivider(0);
}
void
SamplerPanel::SetTrack(SamplerTrack *tr)
{
if(!Window()) return;
sampTrack = tr;
if(Window()->Lock()){
if(tr == NULL || tr->getSample() == NULL)
{
sw->Init(NULL, false, false);
shift->UpdateValue(16, true);
pit_ck->SetValue(false);
boost_ck->SetValue(false);
loop_ck->SetValue(false);
menu->Superitem()->SetLabel(T_SAMPLER_NOSELECTED);
depth->UpdateValue(1, true);
}
else
{
SetTitle(tr->getName());
my_sample=tr->getSample();
sw->Init(my_sample, tr->isReversed(), 1.0f);
menu->Superitem()->SetLabel(my_sample->GetName());
shift->UpdateValue(tr->getResample(), true);
pit_ck->SetValue(tr->isResampleEnable());
boost_ck->SetValue(tr->isBoostEnable());
loop_ck->SetValue(tr->IsLoopEnable());
rev->SetValue(tr->isReversed());
depth->UpdateValue((int32)tr->amp, true);
sw->SetBoost(tr->amp);
}
Window()->Unlock();
}
}
void
SamplerPanel::MessageReceived(BMessage* message)
{
switch(message->what)
{
case LOOP_ON:
if(sampTrack == NULL) return;
sampTrack->SetLoopEnable((bool)loop_ck->Value());
break;
case BOOST_ON:
if(sampTrack==NULL) return;
sampTrack->setBoostEnable((bool)boost_ck->Value());
if(!boost_ck->Value())
{
sampTrack->amp=1.0;
sw->SetBoost(sampTrack->amp);
return;
}
//else continue (without break!)
case REL_MSG:
if(sampTrack==NULL) return;
if(!sampTrack->isBoostEnable()) return;
sampTrack->amp=(float)depth->GetValue();
sw->SetBoost(sampTrack->amp);
break;
case TRACK_SAMP_EXT:
booster->ChangeSample(message->FindInt16("sample"));//ok
break;
case MOD:
if(sampTrack==NULL) return;
XHost::Get()->SendMessage(X_LockSem,NULL);
sampTrack->setResample(shift->GetValue());
XHost::Get()->SendMessage(X_UnLockSem,NULL);
break;
case PIT_ON:
if(sampTrack==NULL) return;
XHost::Get()->SendMessage(X_LockSem,NULL);
sampTrack->setResampleEnable((bool)pit_ck->Value());
XHost::Get()->SendMessage(X_UnLockSem,NULL);
break;
case TRACK_REV:
if(sampTrack==NULL) return;
sampTrack->setReversed(rev->Value());
sw->SetReversed(rev->Value());
break;
case LOADEXT:
booster->LoadSample();
break;
case REMOVEALL:
booster->RemoveAll();
break;
case REMOVE:
booster->RemoveSample(((SamplerTrack*)sampTrack)->getSample());
break;
case B_REFS_RECEIVED: //ok
{
entry_ref ref;
if(message->FindRef("refs",&ref)==B_OK)
{
booster->RefReceived(ref,sampTrack);
booster->RefreshSelected();
}
}
break;
default:
PlugPanel::MessageReceived(message);
break;
}
}
| 23.212121 | 122 | 0.678362 | Freaxed |
17087a984bfb322409d3626a78449479d9737aef | 1,328 | cpp | C++ | test/unit/DeviceConfigParserTest.cpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 8 | 2019-06-10T19:44:48.000Z | 2021-06-10T23:03:24.000Z | test/unit/DeviceConfigParserTest.cpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 10 | 2019-05-15T21:01:54.000Z | 2021-01-16T23:08:53.000Z | test/unit/DeviceConfigParserTest.cpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 2 | 2021-09-17T08:20:07.000Z | 2022-03-29T01:17:07.000Z | #include "../main/catch.hpp"
#include "config/device/DeviceConfigParser.hpp"
#include <typeinfo>
#include <iostream>
#include <string.h>
using namespace std;
TEST_CASE("DeviceConfigParser")
{
DeviceConfigParser parser;
SECTION("should parse semicolon-separated-values to DeviceConfig") {
// given:
// version;id;name;type_int;port;wire_color_int;debounce
const char* line = "1.0;103;test device name;2;16;4;100;45";
// when
DeviceConfig* device = parser.parse(line);
// then
REQUIRE(device != nullptr);
REQUIRE(device->getId() == 103);
REQUIRE(strcmp(device->getName(), "test device name") == 0);
REQUIRE(device->getDeviceType() == DeviceType::DIGITAL_OUTPUT);
REQUIRE(device->getPortNumber() == 16);
REQUIRE(device->getWireColor() == WireColor::BLUE);
REQUIRE(device->getDebounceMs() == 100);
REQUIRE(device->getPjonId() == 45);
}
SECTION("should return null if version is not supported (1.0 for now)") {
// given:
// version;id;name;type_int;port;wire_color_int;debounce
const char* line = "2.0;103;test device name;2;16;4;100;44";
// when
DeviceConfig* device = parser.parse(line);
// then
REQUIRE(device == nullptr);
}
} | 30.883721 | 77 | 0.61747 | aetas |
17090b5cda62448df1a289b222a3d91e1f151305 | 3,740 | cpp | C++ | mod/xlib/xlib.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 45 | 2018-08-24T12:57:38.000Z | 2021-11-12T11:21:49.000Z | mod/xlib/xlib.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | null | null | null | mod/xlib/xlib.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 4 | 2019-09-16T02:48:42.000Z | 2020-07-10T03:50:31.000Z | #include <L/src/engine/Engine.h>
#include <L/src/rendering/Renderer.h>
#include <L/src/system/System.h>
#include <L/src/system/Window.h>
#include <L/src/text/String.h>
#include "xlib.h"
static class XWindow* instance(nullptr);
L::Symbol xlib_window_type("xlib");
class XWindow : public L::Window {
protected:
::Display* _xdisplay;
::Window _xwindow;
public:
XWindow() {
L::String tmp;
L::System::call("xdpyinfo | grep 'dimensions:' | grep -o '[[:digit:]]\\+'", tmp);
L::Array<L::String> res(tmp.explode('\n'));
if(res.size() >= 2) {
_screen_width = L::ston<10, uint32_t>(res[0]);
_screen_height = L::ston<10, uint32_t>(res[1]);
}
}
void update() {
L_SCOPE_MARKER("Window update");
XEvent xev;
XWindowAttributes gwa;
while(opened() && XPending(_xdisplay)) {
XNextEvent(_xdisplay, &xev);
Window::Event e {};
switch(xev.type) {
case Expose:
XGetWindowAttributes(_xdisplay, _xwindow, &gwa);
if(_width != uint32_t(gwa.width) || _height != uint32_t(gwa.height)) {
e.type = Event::Type::Resize;
_width = e.coords.x = gwa.width;
_height = e.coords.y = gwa.height;
}
break;
case MotionNotify:
_cursor_x = xev.xmotion.x;
_cursor_y = xev.xmotion.y;
break;
case ClientMessage: // It's the close operation
close();
break;
}
if(e.type!=Event::Type::None) {
_events.push(e);
}
}
}
void open(const char* title, uint32_t width, uint32_t height, uint32_t flags) override {
L_SCOPE_MARKER("XWindow::open");
if(opened()) {
L::error("xlib: Trying to reopen window");
}
_width = width;
_height = height;
_flags = flags;
if((_xdisplay = XOpenDisplay(nullptr)) == nullptr) {
L::error("Cannot open X server display.");
}
{ // Create window
::Window root = DefaultRootWindow(_xdisplay);
int scr = DefaultScreen(_xdisplay);
int depth = DefaultDepth(_xdisplay, scr);
Visual* visual = DefaultVisual(_xdisplay, scr);
XSetWindowAttributes swa {};
swa.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
_xwindow = XCreateWindow(_xdisplay, root, 0, 0, width, height, 0, depth, InputOutput, visual, CWColormap | CWEventMask, &swa);
}
{ // Activate window close events
Atom wm_delete_window(XInternAtom(_xdisplay, "WM_DELETE_WINDOW", 0));
XSetWMProtocols(_xdisplay, _xwindow, &wm_delete_window, 1);
}
XMapWindow(_xdisplay, _xwindow);
XStoreName(_xdisplay, _xwindow, title);
if(flags & nocursor) {
const char pixmap_data(0);
Pixmap pixmap(XCreateBitmapFromData(_xdisplay, _xwindow, &pixmap_data, 1, 1));
XColor color;
Cursor cursor(XCreatePixmapCursor(_xdisplay, pixmap, pixmap, &color, &color, 0, 0));
XDefineCursor(_xdisplay, _xwindow, cursor);
}
_opened = true;
XlibWindowData window_data;
window_data.type = xlib_window_type;
window_data.display = _xdisplay;
window_data.window = _xwindow;
L::Renderer::get()->init(&window_data);
}
void close() override {
L_ASSERT(_opened);
XDestroyWindow(_xdisplay, _xwindow);
XCloseDisplay(_xdisplay);
_opened = false;
}
void title(const char*) override {
L::warning("Setting window title is unsupported for X windows");
}
void resize(uint32_t, uint32_t) override {
L::warning("Resizing window is unsupported for X windows");
}
};
void xlib_module_init() {
instance = L::Memory::new_type<XWindow>();
L::Engine::add_parallel_update([]() {
instance->update();
});
}
| 29.92 | 132 | 0.632353 | Lyatus |
170ae6ad1523f514c387578f4e59dad41166fc9f | 5,620 | cpp | C++ | SpaceShooter/src/Game/Entities/EShipControllable.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/Entities/EShipControllable.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/Entities/EShipControllable.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | #include "../../Engine/Input/InputEvent.h"
#include "../../Engine/Input/InputManager.h"
#include "../Components/CWeapon.h"
#include "../../Engine/Math.h"
#include "../UI/WLifebar.h"
#include "../Components/HeadersComponents.h"
#include "../../Engine/Audio/Audiosource.h"
#include "../../Engine/Input/Controller.h"
#include "EShipControllable.h"
Ptr<EShipControllable> EShipControllable::Create()
{
Ptr<EShipControllable> p = new EShipControllable();
p->mThis = p.UpCast<Entity>();
return p;
}
Ptr<EShipControllable> EShipControllable::Create(const Transform2D& Tranform2D, float MaxLinearAcceleration, float MaxAngularAcceleration, float LinearInertiaSec, float AngularInertiaSec)
{
Ptr<EShipControllable> p = new EShipControllable(Tranform2D, MaxLinearAcceleration, MaxAngularAcceleration, LinearInertiaSec, AngularInertiaSec);
p->mThis = p.UpCast<Entity>();
return p;
}
EShipControllable::EShipControllable(const Transform2D& Tranform2D, float MaxLinearAcceleration, float MaxAngularAcceleration, float LinearInertiaSec, float AngularInertiaSec)
{
mType = EntityType::ENTITY_SHIPCONTROLLABLE;
SetTransform(Tranform2D);
SetTickMovement(true);
SetMaxLinearAcc(MaxLinearAcceleration);
SetMaxAngularAcc(MaxAngularAcceleration);
SetLinearInertia(LinearInertiaSec);
SetAngularInertia(AngularInertiaSec);
mInputActivated = true;
ActivateMovementController();
}
void EShipControllable::Init()
{
EShip::Init();
// All the inputs events that a controllable ship should observe
std::vector<InputEvent::TEvent> EventsToObserve;
EventsToObserve.push_back(InputEvent::EVENT_KEY_UP_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_UP_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_RIGHT_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_RIGHT_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_LEFT_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_LEFT_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_SPACE_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_SPACE_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_TAB_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_TAB_RELEASED);
// Pass these events to the InputMananger
IInputManagerObserver::Instance()->AddObserver((mThis.DownCast<EShipControllable>()).UpCast<IIMObserver>(), EventsToObserve);
}
void EShipControllable::Update(float elapsed)
{
EShip::Update(elapsed);
}
void EShipControllable::Render()
{
EShip::Render();
}
void EShipControllable::ManageEvent(const InputEvent& Event)
{
// How to manage the input event
if (mInputActivated)
{
InputEvent::TEvent TypeEvent = Event.GetTEvent();
switch (TypeEvent)
{
case InputEvent::EVENT_NONE:
{
break;
}
case InputEvent::EVENT_MOUSE_RIGHT_CLICK:
{
break;
}
case InputEvent::EVENT_MOUSE_LEFT_CLICK:
{
break;
}
case InputEvent::EVENT_KEY_SPACE_PRESSED:
{
if (IsPrimaryWeaponActive())
{
GetPrimaryWeaponComp()->Fire(GetProjectileSpawnPos(), GetRotation());
SetPrimaryWeaponActive(false);
}
break;
}
case InputEvent::EVENT_KEY_SPACE_RELEASED:
{
SetPrimaryWeaponActive(true);
break;
}
case InputEvent::EVENT_KEY_TAB_PRESSED:
{
if (IsSecondaryWeaponActive())
{
GetSecondaryWeaponComp()->Fire(GetProjectileSpawnPos(), GetRotation());
SetSecondaryWeaponActive(false);
}
break;
}
case InputEvent::EVENT_KEY_TAB_RELEASED:
{
SetSecondaryWeaponActive(true);
break;
}
case InputEvent::EVENT_KEY_UP_PRESSED:
{
if(IsMovementControllerActivated())
{
DeactivateLinearInertia();
SetLinearSteering(vec2(GetForwardVector().x * GetMaxLinearAcc(), GetForwardVector().y* GetMaxLinearAcc()));
}
break;
}
case InputEvent::EVENT_KEY_UP_RELEASED:
{
if (IsMovementControllerActivated())
{
ActivateLinearInertia();
}
break;
}
case InputEvent::EVENT_KEY_DOWN_PRESSED:
{
break;
}
case InputEvent::EVENT_KEY_RIGHT_PRESSED:
{
if (IsMovementControllerActivated())
{
DeactivateAngularInertia();
SetAngularSteering(-GetMaxAngularAcc());
SetTurnDirection(-1);
}
break;
}
case InputEvent::EVENT_KEY_RIGHT_RELEASED:
{
if (IsMovementControllerActivated())
{
ActivateAngularInertia();
}
break;
}
case InputEvent::EVENT_KEY_LEFT_PRESSED:
{
if (IsMovementControllerActivated())
{
DeactivateAngularInertia();
SetAngularSteering(GetMaxAngularAcc());
SetTurnDirection(1);
}
break;
}
case InputEvent::EVENT_KEY_LEFT_RELEASED:
{
if (IsMovementControllerActivated())
{
ActivateAngularInertia();
}
break;
}
default:
break;
}
}
} | 31.222222 | 187 | 0.625089 | tomasmartinsantos |
170dbe21f8030fd7cf7f65fe085eded46ed9565b | 330 | cpp | C++ | Code full house/buoi20 nguyen dinh trung duc/newbie/prob C.cpp | ducyb2001/CbyTrungDuc | 0e93394dce600876a098b90ae969575bac3788e1 | [
"Apache-2.0"
] | null | null | null | Code full house/buoi20 nguyen dinh trung duc/newbie/prob C.cpp | ducyb2001/CbyTrungDuc | 0e93394dce600876a098b90ae969575bac3788e1 | [
"Apache-2.0"
] | null | null | null | Code full house/buoi20 nguyen dinh trung duc/newbie/prob C.cpp | ducyb2001/CbyTrungDuc | 0e93394dce600876a098b90ae969575bac3788e1 | [
"Apache-2.0"
] | null | null | null | /*problem C*/
#include<stdio.h>
#include<string.h>
int main(){
int n;
scanf("%d",&n);
int a[n];
int sum=0;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
float tbc=(float)sum/n;
int kq=0;
for(int i=0;i<n;i++){
if(a[i]>tbc){
kq+=a[i];
}
}
if(kq==0){
printf("-1");
return 0;
}
printf("%d",kq);
}
| 12.222222 | 24 | 0.490909 | ducyb2001 |
170e458b5971a4e0bb7b0a3db6b5436c1aa66c5c | 702 | hpp | C++ | src/renderer/pipelines/events/BIND.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 2 | 2021-03-18T16:25:04.000Z | 2021-11-13T00:29:27.000Z | src/renderer/pipelines/events/BIND.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | null | null | null | src/renderer/pipelines/events/BIND.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 1 | 2021-11-13T00:29:30.000Z | 2021-11-13T00:29:30.000Z | /**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#ifndef ZEN_RENDERER_PIPELINES_EVENTS_BIND_HPP
#define ZEN_RENDERER_PIPELINES_EVENTS_BIND_HPP
#include <string>
namespace Zen {
namespace Events {
/**
* The Pipeline Bind Event.
*
* This event is dispatched by a Pipeline when it is bound by the PipelineManager.
*
* @since 0.0.0
*
* @param pipeline Pointer to the pipeline that was bound.
* @param currentShader Pointer to the shader that was set as being current.
*/
const std::string PIPELINE_BIND = "pipelinebind";
} // namespace Events
} // namespace Zen
#endif
| 21.9375 | 82 | 0.730769 | hexoctal |
171167a943cfbfe20cfdc4ddf432f82a95d7d6a9 | 140 | cpp | C++ | darknet-master/build/modules/imgproc/color_hsv.sse4_1.cpp | mcyy23633/ship_YOLOv4 | 2eb53e578546fce663a2f3fa153481ce4f82c588 | [
"MIT"
] | null | null | null | darknet-master/build/modules/imgproc/color_hsv.sse4_1.cpp | mcyy23633/ship_YOLOv4 | 2eb53e578546fce663a2f3fa153481ce4f82c588 | [
"MIT"
] | null | null | null | darknet-master/build/modules/imgproc/color_hsv.sse4_1.cpp | mcyy23633/ship_YOLOv4 | 2eb53e578546fce663a2f3fa153481ce4f82c588 | [
"MIT"
] | null | null | null |
#include "C:/opencv/opencv-4.5.1/modules/imgproc/src/precomp.hpp"
#include "C:/opencv/opencv-4.5.1/modules/imgproc/src/color_hsv.simd.hpp"
| 35 | 72 | 0.757143 | mcyy23633 |
1718aea0480f5a310eed75e199d928d4e108e9a3 | 1,212 | cpp | C++ | AdvancedDataStructures/rp_heap_testing_ec504/rp_heap_testbench.cpp | pdvnny/DataStructures-Algorithms | 9c1adbb77126011274129715c1ba589317d4479c | [
"Apache-2.0"
] | null | null | null | AdvancedDataStructures/rp_heap_testing_ec504/rp_heap_testbench.cpp | pdvnny/DataStructures-Algorithms | 9c1adbb77126011274129715c1ba589317d4479c | [
"Apache-2.0"
] | null | null | null | AdvancedDataStructures/rp_heap_testing_ec504/rp_heap_testbench.cpp | pdvnny/DataStructures-Algorithms | 9c1adbb77126011274129715c1ba589317d4479c | [
"Apache-2.0"
] | null | null | null | /**********************************************
Parker Dunn (pgdunn@bu.edu)
EC 504 Final Project
Testbench for my first version of rp_heap.h
***********************************************/
#include <iostream>
#include "rp_heap.h"
using namespace std;
int main() {
rp_heap* myHeap = new rp_heap();
int size = 10;
int heap_extract;
/// creating a bunch of things to push
int elements[size][2];
for (int i = 1; i < (size+1); i++) {
elements[i-1][0] = i; // KEY
elements[i-1][1] = i*10; // DATA
}
for (int j = 0; j < size; j++)
myHeap->push(elements[j][1], elements[j][0]);
cout << "\nThe size of myHeap is " << myHeap->size() << "\n" << endl;
cout << "\nExtracting 4 Nodes now..." << endl;
for (int j = 0; j < 4; j++) {
heap_extract = myHeap->extract_min();
cout << "Extraction #" << (j+1) << ": " << heap_extract << endl;
}
cout << "\nTime to decrease some keys..." << endl;
myHeap->decreaseKey(10, 5);
myHeap->decreaseKey(9, 8);
cout << "\n";
for (int j = 4; j < size; j++) {
heap_extract = myHeap->extract_min();
cout << "Extraction #" << (j+1) << ": " << heap_extract << endl;
}
return 0;
} | 20.896552 | 73 | 0.499175 | pdvnny |
17192f89651302fb794b091406686f43367251a8 | 4,124 | cpp | C++ | src/+cv/fisheyeStereoCalibrate.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 571 | 2015-01-04T06:23:19.000Z | 2022-03-31T07:37:19.000Z | src/+cv/fisheyeStereoCalibrate.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 362 | 2015-01-06T14:20:46.000Z | 2022-01-20T08:10:46.000Z | src/+cv/fisheyeStereoCalibrate.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 300 | 2015-01-20T03:21:27.000Z | 2022-03-31T07:36:37.000Z | /**
* @file fisheyeStereoCalibrate.cpp
* @brief mex interface for cv::fisheye::stereoCalibrate
* @ingroup calib3d
* @author Amro
* @date 2017
*/
#include "mexopencv.hpp"
#include "opencv2/calib3d.hpp"
using namespace std;
using namespace cv;
namespace {
/** Create a new MxArray from stereo calibration results.
* @param K1 First camera matrix.
* @param D1 Distortion coefficients of first camera.
* @param K2 Second camera matrix.
* @param D2 Distortion coefficients of second camera.
* @param R Rotation matrix between the cameras coordinate systems.
* @param T Translation vector between the cameras coordinate systems.
* @param rms Re-projection error.
* @return output MxArray struct object.
*/
MxArray toStruct(const Mat& K1, const Mat& D1, const Mat& K2, const Mat& D2,
const Mat& R, const Mat& T, double rms)
{
const char* fieldnames[] = {"cameraMatrix1", "distCoeffs1",
"cameraMatrix2", "distCoeffs2", "R", "T", "reprojErr"};
MxArray s = MxArray::Struct(fieldnames, 7);
s.set("cameraMatrix1", K1);
s.set("distCoeffs1", D1);
s.set("cameraMatrix2", K2);
s.set("distCoeffs2", D2);
s.set("R", R);
s.set("T", T);
s.set("reprojErr", rms);
return s;
}
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
// Option processing
Mat K1, D1, K2, D2;
int flags = cv::CALIB_FIX_INTRINSIC;
TermCriteria criteria(TermCriteria::COUNT+TermCriteria::EPS, 100, DBL_EPSILON);
for (int i=4; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "CameraMatrix1")
K1 = rhs[i+1].toMat(CV_64F);
else if (key == "DistCoeffs1")
D1 = rhs[i+1].toMat(CV_64F);
else if (key == "CameraMatrix2")
K2 = rhs[i+1].toMat(CV_64F);
else if (key == "DistCoeffs2")
D2 = rhs[i+1].toMat(CV_64F);
else if (key == "UseIntrinsicGuess")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_USE_INTRINSIC_GUESS);
else if (key == "RecomputeExtrinsic")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC);
else if (key == "CheckCond")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_CHECK_COND);
else if (key == "FixSkew")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_SKEW);
else if (key == "FixK1")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K1);
else if (key == "FixK2")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K2);
else if (key == "FixK3")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K3);
else if (key == "FixK4")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K4);
else if (key == "FixIntrinsic")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_INTRINSIC);
else if (key == "Criteria")
criteria = rhs[i+1].toTermCriteria();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
// Process
vector<vector<Point3d> > objectPoints(MxArrayToVectorVectorPoint3<double>(rhs[0]));
vector<vector<Point2d> > imagePoints1(MxArrayToVectorVectorPoint<double>(rhs[1]));
vector<vector<Point2d> > imagePoints2(MxArrayToVectorVectorPoint<double>(rhs[2]));
Size imageSize(rhs[3].toSize());
Mat R, T;
double rms = fisheye::stereoCalibrate(objectPoints, imagePoints1, imagePoints2,
K1, D1, K2, D2, imageSize, R, T, flags, criteria);
plhs[0] = toStruct(K1, D1, K2, D2, R, T, rms);
}
| 39.27619 | 90 | 0.626819 | 1123852253 |
171bf164f43b1e782f78ad5548fe47fd9cb27cdb | 11,359 | cpp | C++ | src/turtlecoin-crypto-js.cpp | CASH2-js/cash2-crypto | 1b1386253d5c032ac5a0d619481bff7931c979e9 | [
"BSD-3-Clause"
] | null | null | null | src/turtlecoin-crypto-js.cpp | CASH2-js/cash2-crypto | 1b1386253d5c032ac5a0d619481bff7931c979e9 | [
"BSD-3-Clause"
] | null | null | null | src/turtlecoin-crypto-js.cpp | CASH2-js/cash2-crypto | 1b1386253d5c032ac5a0d619481bff7931c979e9 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2018-2020, The TurtleCoin Developers
//
// Please see the included LICENSE file for more information.
#include <emscripten/bind.h>
#include <stdio.h>
#include <stdlib.h>
#include <turtlecoin-crypto.h>
using namespace emscripten;
struct Keys
{
std::string publicKey;
std::string secretKey;
};
struct PreparedSignatures
{
std::vector<std::string> signatures;
std::string key;
};
/* Most of the redefintions below are the result of the methods returning a bool instead
of the value we need or issues with method signatures having a uint64_t */
std::string cn_soft_shell_slow_hash_v0(const std::string data, const int height)
{
return Core::Cryptography::cn_soft_shell_slow_hash_v0(data, height);
}
std::string cn_soft_shell_slow_hash_v1(const std::string data, const int height)
{
return Core::Cryptography::cn_soft_shell_slow_hash_v1(data, height);
}
std::string cn_soft_shell_slow_hash_v2(const std::string data, const int height)
{
return Core::Cryptography::cn_soft_shell_slow_hash_v2(data, height);
}
std::vector<std::string> generateRingSignatures(
const std::string prefixHash,
const std::string keyImage,
const std::vector<std::string> publicKeys,
const std::string transactionSecretKey,
const int realOutputIndex)
{
std::vector<std::string> signatures;
bool success = Core::Cryptography::generateRingSignatures(
prefixHash, keyImage, publicKeys, transactionSecretKey, realOutputIndex, signatures);
return signatures;
}
PreparedSignatures prepareRingSignatures(
const std::string prefixHash,
const std::string keyImage,
const std::vector<std::string> publicKeys,
const int realOutputIndex)
{
std::vector<std::string> signatures;
std::string k;
bool success =
Core::Cryptography::prepareRingSignatures(prefixHash, keyImage, publicKeys, realOutputIndex, signatures, k);
PreparedSignatures result;
result.signatures = signatures;
result.key = k;
return result;
}
PreparedSignatures prepareRingSignaturesK(
const std::string prefixHash,
const std::string keyImage,
const std::vector<std::string> publicKeys,
const int realOutputIndex,
const std::string k)
{
std::vector<std::string> signatures;
bool success =
Core::Cryptography::prepareRingSignatures(prefixHash, keyImage, publicKeys, realOutputIndex, k, signatures);
PreparedSignatures result;
result.signatures = signatures;
result.key = k;
return result;
}
Keys generateViewKeysFromPrivateSpendKey(const std::string secretKey)
{
std::string viewSecretKey;
std::string viewPublicKey;
Core::Cryptography::generateViewKeysFromPrivateSpendKey(secretKey, viewSecretKey, viewPublicKey);
Keys keys;
keys.publicKey = viewPublicKey;
keys.secretKey = viewSecretKey;
return keys;
}
Keys generateKeys()
{
std::string secretKey;
std::string publicKey;
Core::Cryptography::generateKeys(secretKey, publicKey);
Keys keys;
keys.publicKey = publicKey;
keys.secretKey = secretKey;
return keys;
}
Keys generateDeterministicSubwalletKeys(const std::string basePrivateKey, const size_t walletIndex)
{
std::string newPrivateKey;
std::string newPublicKey;
Keys keys;
Core::Cryptography::generateDeterministicSubwalletKeys(basePrivateKey, walletIndex, keys.secretKey, keys.publicKey);
return keys;
}
std::string secretKeyToPublicKey(const std::string secretKey)
{
std::string publicKey;
bool success = Core::Cryptography::secretKeyToPublicKey(secretKey, publicKey);
return publicKey;
}
std::string generateKeyDerivation(const std::string publicKey, const std::string secretKey)
{
std::string derivation;
bool success = Core::Cryptography::generateKeyDerivation(publicKey, secretKey, derivation);
return derivation;
}
std::string generateKeyDerivationScalar(const std::string publicKey, const std::string secretKey, size_t outputIndex)
{
return Core::Cryptography::generateKeyDerivationScalar(publicKey, secretKey, outputIndex);
}
std::string derivationToScalar(const std::string derivation, size_t outputIndex)
{
return Core::Cryptography::derivationToScalar(derivation, outputIndex);
}
std::string derivePublicKey(const std::string derivation, const size_t outputIndex, const std::string publicKey)
{
std::string derivedKey;
bool success = Core::Cryptography::derivePublicKey(derivation, outputIndex, publicKey, derivedKey);
return derivedKey;
}
std::string scalarDerivePublicKey(const std::string derivationScalar, const std::string publicKey)
{
std::string derivedKey;
bool success = Core::Cryptography::derivePublicKey(derivationScalar, publicKey, derivedKey);
return derivedKey;
}
std::string deriveSecretKey(const std::string derivation, const size_t outputIndex, const std::string secretKey)
{
return Core::Cryptography::deriveSecretKey(derivation, outputIndex, secretKey);
}
std::string scalarDeriveSecretKey(const std::string derivationScalar, const std::string secretKey)
{
return Core::Cryptography::deriveSecretKey(derivationScalar, secretKey);
}
std::string underivePublicKey(const std::string derivation, const size_t outputIndex, const std::string derivedKey)
{
std::string publicKey;
bool success = Core::Cryptography::underivePublicKey(derivation, outputIndex, derivedKey, publicKey);
return publicKey;
}
std::vector<std::string> completeRingSignatures(
const std::string transactionSecretKey,
const int realOutputIndex,
const std::string k,
const std::vector<std::string> signatures)
{
std::vector<std::string> completeSignatures;
for (auto sig : signatures)
{
completeSignatures.push_back(sig);
}
bool success =
Core::Cryptography::completeRingSignatures(transactionSecretKey, realOutputIndex, k, completeSignatures);
return completeSignatures;
}
std::vector<std::string> restoreRingSignatures(
const std::string derivation,
const size_t output_index,
const std::vector<std::string> partialSigningKeys,
const int realOutput,
const std::string k,
const std::vector<std::string> signatures)
{
std::vector<std::string> completeSignatures;
for (auto sig : signatures)
{
completeSignatures.push_back(sig);
}
bool success = Core::Cryptography::restoreRingSignatures(
derivation, output_index, partialSigningKeys, realOutput, k, completeSignatures);
return completeSignatures;
}
EMSCRIPTEN_BINDINGS(signatures)
{
function("cn_fast_hash", &Core::Cryptography::cn_fast_hash);
function("cn_slow_hash_v0", &Core::Cryptography::cn_slow_hash_v0);
function("cn_slow_hash_v1", &Core::Cryptography::cn_slow_hash_v1);
function("cn_slow_hash_v2", &Core::Cryptography::cn_slow_hash_v2);
function("cn_lite_slow_hash_v0", &Core::Cryptography::cn_lite_slow_hash_v0);
function("cn_lite_slow_hash_v1", &Core::Cryptography::cn_lite_slow_hash_v1);
function("cn_lite_slow_hash_v2", &Core::Cryptography::cn_lite_slow_hash_v2);
function("cn_dark_slow_hash_v0", &Core::Cryptography::cn_dark_slow_hash_v0);
function("cn_dark_slow_hash_v1", &Core::Cryptography::cn_dark_slow_hash_v1);
function("cn_dark_slow_hash_v2", &Core::Cryptography::cn_dark_slow_hash_v2);
function("cn_dark_lite_slow_hash_v0", &Core::Cryptography::cn_dark_lite_slow_hash_v0);
function("cn_dark_lite_slow_hash_v1", &Core::Cryptography::cn_dark_lite_slow_hash_v1);
function("cn_dark_lite_slow_hash_v2", &Core::Cryptography::cn_dark_lite_slow_hash_v2);
function("cn_turtle_slow_hash_v0", &Core::Cryptography::cn_turtle_slow_hash_v0);
function("cn_turtle_slow_hash_v1", &Core::Cryptography::cn_turtle_slow_hash_v1);
function("cn_turtle_slow_hash_v2", &Core::Cryptography::cn_turtle_slow_hash_v2);
function("cn_turtle_lite_slow_hash_v0", &Core::Cryptography::cn_turtle_lite_slow_hash_v0);
function("cn_turtle_lite_slow_hash_v1", &Core::Cryptography::cn_turtle_lite_slow_hash_v1);
function("cn_turtle_lite_slow_hash_v2", &Core::Cryptography::cn_turtle_lite_slow_hash_v2);
function("cn_soft_shell_slow_hash_v0", &cn_soft_shell_slow_hash_v0);
function("cn_soft_shell_slow_hash_v1", &cn_soft_shell_slow_hash_v1);
function("cn_soft_shell_slow_hash_v2", &cn_soft_shell_slow_hash_v2);
function("chukwa_slow_hash", &Core::Cryptography::chukwa_slow_hash);
function("tree_depth", &Core::Cryptography::tree_depth);
function("tree_hash", &Core::Cryptography::tree_hash);
function("tree_branch", &Core::Cryptography::tree_branch);
function("tree_hash_from_branch", &Core::Cryptography::tree_hash_from_branch);
function("generateRingSignatures", &generateRingSignatures);
function("prepareRingSignatures", &prepareRingSignatures);
function("prepareRingSignaturesK", &prepareRingSignaturesK);
function("completeRingSignatures", &completeRingSignatures);
function("checkRingSignature", &Core::Cryptography::checkRingSignature);
function(
"generatePrivateViewKeyFromPrivateSpendKey", &Core::Cryptography::generatePrivateViewKeyFromPrivateSpendKey);
function("generateViewKeysFromPrivateSpendKey", &generateViewKeysFromPrivateSpendKey);
function("generateKeys", &generateKeys);
function("generateDeterministicSubwalletKeys", &generateDeterministicSubwalletKeys);
function("checkKey", &Core::Cryptography::checkKey);
function("secretKeyToPublicKey", &secretKeyToPublicKey);
function("generateKeyDerivation", &generateKeyDerivation);
function("generateKeyDerivationScalar", &generateKeyDerivationScalar);
function("derivationToScalar", &derivationToScalar);
function("derivePublicKey", &derivePublicKey);
function("deriveSecretKey", &deriveSecretKey);
function("scalarDerivePublicKey", &scalarDerivePublicKey);
function("scalarDeriveSecretKey", &scalarDeriveSecretKey);
function("underivePublicKey", &underivePublicKey);
function("generateSignature", &Core::Cryptography::generateSignature);
function("checkSignature", &Core::Cryptography::checkSignature);
function("generateKeyImage", &Core::Cryptography::generateKeyImage);
function("scalarmultKey", &Core::Cryptography::scalarmultKey);
function("hashToEllipticCurve", &Core::Cryptography::hashToEllipticCurve);
function("scReduce32", &Core::Cryptography::scReduce32);
function("hashToScalar", &Core::Cryptography::hashToScalar);
/* Multisig Methods */
function("calculateMultisigPrivateKeys", &Core::Cryptography::calculateMultisigPrivateKeys);
function("calculateSharedPrivateKey", &Core::Cryptography::calculateSharedPrivateKey);
function("calculateSharedPublicKey", &Core::Cryptography::calculateSharedPublicKey);
function("generatePartialSigningKey", &Core::Cryptography::generatePartialSigningKey);
function("restoreKeyImage", &Core::Cryptography::restoreKeyImage);
function("restoreRingSignatures", &restoreRingSignatures);
register_vector<std::string>("VectorString");
value_object<Keys>("Keys").field("secretKey", &Keys::secretKey).field("publicKey", &Keys::publicKey);
value_object<PreparedSignatures>("Keys")
.field("signatures", &PreparedSignatures::signatures)
.field("key", &PreparedSignatures::key);
}
| 33.907463 | 120 | 0.758341 | CASH2-js |
17240c96ec8014dce5c349c2c2097b70997aa4e5 | 2,465 | cpp | C++ | vpnor/test/create_read_window_size.cpp | ibm-openbmc/hiomapd | 8cef63e3a3652b25f6a310800c1e0bf09aeed4c6 | [
"Apache-2.0"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | vpnor/test/create_read_window_size.cpp | ibm-openbmc/hiomapd | 8cef63e3a3652b25f6a310800c1e0bf09aeed4c6 | [
"Apache-2.0"
] | 17 | 2018-09-20T02:29:41.000Z | 2019-04-05T04:43:11.000Z | vpnor/test/create_read_window_size.cpp | ibm-openbmc/hiomapd | 8cef63e3a3652b25f6a310800c1e0bf09aeed4c6 | [
"Apache-2.0"
] | 9 | 2017-02-14T03:05:09.000Z | 2019-01-07T20:39:42.000Z | // SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2018 IBM Corp.
#include "config.h"
extern "C" {
#include "test/mbox.h"
#include "test/system.h"
}
#include "vpnor/test/tmpd.hpp"
#include <cassert>
#include <experimental/filesystem>
#include "vpnor/backend.h"
static const auto BLOCK_SIZE = 4096;
static const auto ERASE_SIZE = BLOCK_SIZE;
static const auto WINDOW_SIZE = 2 * BLOCK_SIZE;
static const auto MEM_SIZE = WINDOW_SIZE;
static const auto N_WINDOWS = 1;
static const auto PNOR_SIZE = 4 * BLOCK_SIZE;
const std::string toc[] = {
"partition01=ONE,00001000,00002000,80,ECC,READONLY",
"partition02=TWO,00002000,00004000,80,ECC,READONLY",
};
static const uint8_t get_info[] = {0x02, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
static const uint8_t request_one[] = {0x04, 0x01, 0x01, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
static const uint8_t response_one[] = {0x04, 0x01, 0xfe, 0xff, 0x01,
0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01};
static const uint8_t request_two[] = {0x04, 0x02, 0x02, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
static const uint8_t response_two[] = {0x04, 0x02, 0xfe, 0xff, 0x02,
0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01};
namespace test = openpower::virtual_pnor::test;
int main()
{
struct mbox_context* ctx;
system_set_reserved_size(MEM_SIZE);
system_set_mtd_sizes(PNOR_SIZE, ERASE_SIZE);
ctx = mbox_create_frontend_context(N_WINDOWS, WINDOW_SIZE);
test::VpnorRoot root(&ctx->backend, toc, BLOCK_SIZE);
int rc = mbox_command_dispatch(ctx, get_info, sizeof(get_info));
assert(rc == 1);
rc = mbox_command_dispatch(ctx, request_one, sizeof(request_one));
assert(rc == 1);
rc = mbox_cmp(ctx, response_one, sizeof(response_one));
assert(rc == 0);
rc = mbox_command_dispatch(ctx, request_two, sizeof(request_two));
assert(rc == 1);
rc = mbox_cmp(ctx, response_two, sizeof(response_two));
assert(rc == 0);
return rc;
}
| 31.202532 | 73 | 0.593509 | ibm-openbmc |
172628daaa456b00c9286a0db48929d1559a021f | 958 | hpp | C++ | include/ygp/rng.hpp | qaqwqaqwq-0/YGP | 928d53aff1c8ca1327b0cf7ad6e6836d44c3447f | [
"MIT"
] | 5 | 2020-12-07T08:58:24.000Z | 2021-03-22T08:21:16.000Z | include/ygp/rng.hpp | qaqwqaqwq-0/YGP | 928d53aff1c8ca1327b0cf7ad6e6836d44c3447f | [
"MIT"
] | null | null | null | include/ygp/rng.hpp | qaqwqaqwq-0/YGP | 928d53aff1c8ca1327b0cf7ad6e6836d44c3447f | [
"MIT"
] | 2 | 2021-01-26T07:45:52.000Z | 2021-02-14T15:54:54.000Z | #ifndef _YGP_RNG_HPP_
#define _YGP_RNG_HPP_
#include"configure.hpp"
#include<cstdint>
BEGIN_NAMESPACE_YGP
template<typename _Tp>
class rng/*range*/
{
public:
using t=_Tp;
struct iterator
{
t tc,td;
iterator(t B,t D):tc{B},td{D}{}
t operator++(){return tc+=td;}
t operator--(){return tc-=td;}
const t& operator*()const{return tc;}
bool operator==(const iterator& an)const{return tc==an.tc;}
bool operator!=(const iterator& an)const{return tc!=an.tc;}
};
t b,e,d;
explicit rng(t E)
{
b=0,e=E,d=1;
}
explicit rng(t B,t E,t D=1):b{B},e{E},d{D}{}
iterator begin()const
{
return iterator{b,d};
}
iterator end()const
{
return iterator{e,d};
}
};
/*Usage: for(auto i:rng(begin,end))//[begin,end)*/
END_NAMESPACE_YGP
#endif | 25.210526 | 71 | 0.515658 | qaqwqaqwq-0 |
172aba938345b6741eb65fd95c87a4fcacf42f84 | 1,913 | cpp | C++ | src/device/controllerNvidia.cpp | ISilence/delirium_cl | d54499af2556511eb47ae90b2420788ca914d314 | [
"MIT"
] | 2 | 2017-06-02T08:08:47.000Z | 2017-08-24T06:43:40.000Z | src/device/controllerNvidia.cpp | ISilence/delirium_cl | d54499af2556511eb47ae90b2420788ca914d314 | [
"MIT"
] | 9 | 2016-11-17T18:46:30.000Z | 2017-05-13T20:16:50.000Z | src/device/controllerNvidia.cpp | ISilence/delirium_cl | d54499af2556511eb47ae90b2420788ca914d314 | [
"MIT"
] | null | null | null | #if !defined(DLM_CL_SKIP_VENDOR_NVIDIA)
#include "dlm/env/macro.h"
DLM_CMODULE_START
#include "cl/cl_ext_nvidia.h"
DLM_CMODULE_END
#include "dlm/cl/device.hpp"
#include "dlm/cl/controllers.hpp"
using namespace dlmcl;
static void getPCITopology(DeviceInfo &info, cl_device_id device) noexcept
{
// undocumented Nvidia API
#define CL_DEVICE_PCI_BUS_ID_NV 0x4008
#define CL_DEVICE_PCI_SLOT_ID_NV 0x4009
cl_int bus = -1;
cl_int slot = -1;
cl_int err = clGetDeviceInfo (device, CL_DEVICE_PCI_BUS_ID_NV, sizeof(bus), &bus, NULL);
if (err != CL_SUCCESS)
return;
err = clGetDeviceInfo(device, CL_DEVICE_PCI_SLOT_ID_NV, sizeof(slot), &slot, NULL);
if (err != CL_SUCCESS)
return;
info.topology.bus = bus;
info.topology.dev = (slot >> 3) & 0xff;
info.topology.fn = slot & 0x7;
}
static void getMemoryArchitecture(DeviceInfo &info, cl_device_id device) noexcept
{
cl_bool isSMA;
const cl_int err = clGetDeviceInfo(device, CL_DEVICE_INTEGRATED_MEMORY_NV, sizeof(isSMA), &isSMA, NULL);
if (err == CL_SUCCESS)
info.memory.isSMA = (isSMA != 0);
}
static void getMemoryCaps(DeviceInfo &info, cl_device_id device) noexcept
{
cl_uint warp;
const cl_int err = clGetDeviceInfo(device, CL_DEVICE_WARP_SIZE_NV, sizeof(warp), &warp, NULL);
if (err == CL_SUCCESS)
info.compute.warp = warp;
}
DeviceInfo NvidiaController::getInfo(cl_device_id device) noexcept
{
DeviceInfo info = GenericController::getInfo(device);
getPCITopology(info, device);
getMemoryArchitecture(info, device);
getMemoryCaps(info, device);
return info;
}
const char* NvidiaController::getCompilationOptions(cl_device_id device, enum OPTIMIZATION_LEVEL level) noexcept
{
static const char opts[] = "-cl-fast-relaxed-math -cl-no-signed-zeros -cl-mad-enable -D DLM_NVIDIA";
return opts;
}
#endif // DLM_CL_SKIP_VENDOR_NVIDIA
| 28.984848 | 112 | 0.721903 | ISilence |
172edd1de0d19cdafc6ec5825400f61a8e4f2035 | 2,268 | cpp | C++ | MMVII/src/RamImages/cIm2d.cpp | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 8 | 2019-05-08T21:43:53.000Z | 2021-07-27T20:01:46.000Z | MMVII/src/RamImages/cIm2d.cpp | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 2 | 2019-05-24T17:11:33.000Z | 2019-06-30T17:55:28.000Z | MMVII/src/RamImages/cIm2d.cpp | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 2 | 2020-08-01T00:27:16.000Z | 2022-02-04T10:24:54.000Z | #include "include/MMVII_all.h"
namespace MMVII
{
/* ========================== */
/* cDataIm2D */
/* ========================== */
template <class Type> cDataIm2D<Type>::cDataIm2D(const cPt2di & aP0,const cPt2di & aP1,Type * aRawDataLin,eModeInitImage aModeInit) :
cDataTypedIm<Type,2> (aP0,aP1,aRawDataLin,aModeInit)
{
mRawData2D = cMemManager::Alloc<tVal*>(cRectObj<2>::Sz().y()) -Y0();
for (int aY=Y0() ; aY<Y1() ; aY++)
mRawData2D[aY] = tBI::mRawDataLin + (aY-Y0()) * SzX() - X0();
}
template <class Type> cDataIm2D<Type>::~cDataIm2D()
{
cMemManager::Free(mRawData2D+Y0());
}
template <class Type> int cDataIm2D<Type>::VI_GetV(const cPt2di& aP) const
{
return GetV(aP);
}
template <class Type> double cDataIm2D<Type>::VD_GetV(const cPt2di& aP) const
{
return GetV(aP);
}
template <class Type> void cDataIm2D<Type>::VI_SetV(const cPt2di& aP,const int & aV)
{
SetVTrunc(aP,aV);
}
template <class Type> void cDataIm2D<Type>::VD_SetV(const cPt2di& aP,const double & aV)
{
SetVTrunc(aP,aV);
}
/* ========================== */
/* cIm2D */
/* ========================== */
template <class Type> cIm2D<Type>::cIm2D(const cPt2di & aP0,const cPt2di & aP1,Type * aRawDataLin,eModeInitImage aModeInit) :
mSPtr(new cDataIm2D<Type>(aP0,aP1,aRawDataLin,aModeInit)),
mPIm (mSPtr.get())
{
}
template <class Type> cIm2D<Type>::cIm2D(const cPt2di & aSz,Type * aRawDataLin,eModeInitImage aModeInit) :
cIm2D<Type> (cPt2di(0,0),aSz,aRawDataLin,aModeInit)
{
}
template <class Type> cIm2D<Type> cIm2D<Type>::FromFile(const std::string & aName)
{
cDataFileIm2D aFileIm = cDataFileIm2D::Create(aName);
cIm2D<Type> aRes(aFileIm.Sz());
aRes.Read(aFileIm,cPt2di(0,0));
return aRes;
}
template <class Type> cIm2D<Type> cIm2D<Type>::Dup() const
{
cIm2D<Type> aRes(DIm().P0(),DIm().P1());
DIm().DupIn(aRes.DIm());
return aRes;
}
#define INSTANTIATE_IM2D(Type)\
template class cIm2D<Type>;\
template class cDataIm2D<Type>;
INSTANTIATE_IM2D(tINT1)
INSTANTIATE_IM2D(tINT2)
INSTANTIATE_IM2D(tINT4)
INSTANTIATE_IM2D(tU_INT1)
INSTANTIATE_IM2D(tU_INT2)
INSTANTIATE_IM2D(tU_INT4)
INSTANTIATE_IM2D(tREAL4)
INSTANTIATE_IM2D(tREAL8)
INSTANTIATE_IM2D(tREAL16)
};
| 23.381443 | 135 | 0.645944 | dronemapper-io |
173146c0cba0fa47527e4d530ca230027e9051f4 | 1,944 | cpp | C++ | source/directinput/CapabilitiesDI.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/directinput/CapabilitiesDI.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/directinput/CapabilitiesDI.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* 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 <dinput.h>
#include "CapabilitiesDI.h"
#include "Guids.h"
#include "DeviceSubType.h"
using namespace System;
namespace SlimDX
{
namespace DirectInput
{
Capabilities::Capabilities( const DIDEVCAPS &caps )
{
axesCount = caps.dwAxes;
buttonCount = caps.dwButtons;
povCount = caps.dwPOVs;
ffSamplePeriod = caps.dwFFSamplePeriod;
ffMinTimeResolution = caps.dwFFMinTimeResolution;
ffDriverVersion = caps.dwFFDriverVersion;
firmwareRevision = caps.dwFirmwareRevision;
hardwareRevision = caps.dwHardwareRevision;
flags = static_cast<DeviceFlags>( caps.dwFlags );
type = static_cast<DeviceType>( caps.dwDevType );
subType = caps.dwDevType >> 8;
if( ( caps.dwDevType & DIDEVTYPE_HID ) != 0 )
hid = true;
else
hid = false;
}
}
} | 35.345455 | 80 | 0.736626 | HeavenWu |
1734cd367bde7adaa4ca92a36bd65474366fffd3 | 3,564 | cpp | C++ | src/hdk/ui/hdCheckbox.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | 2 | 2016-06-15T17:47:50.000Z | 2019-07-29T10:33:05.000Z | src/hdk/ui/hdCheckbox.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | null | null | null | src/hdk/ui/hdCheckbox.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | null | null | null | /*
* Copyright (c) 2014 Hackdirt Ltd.
* Author: David Petrie (david@davidpetrie.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 "hdCheckbox.h"
hdCheckbox::hdCheckbox(const char *textureOnNormal,
const char *textureOnOver,
const char *textureOffNormal,
const char *textureOffOver,
hdGameWorld* gameWorld) : hdReceiver(gameWorld, true)
{
// create two buttons
m_onButton = new hdButton(textureOnNormal,
textureOnOver,
textureOnOver);
m_offButton = new hdButton(textureOffNormal,
textureOffOver,
textureOffOver);
m_activeButton = m_onButton;
m_callbackObject = NULL;
m_valueChangedCallback = NULL;
}
hdCheckbox::~hdCheckbox()
{
if (m_onButton)
delete m_onButton;
if (m_offButton)
delete m_offButton;
}
void hdCheckbox::SetAs2DBox(const float& x, const float& y, const float& w, const float& h)
{
m_onButton->SetAs2DBox(x, y, w, h);
m_offButton->SetAs2DBox(x, y, w, h);
}
void hdCheckbox::AddValueChangedListener(void *obj, void (*func)(void *, void *))
{
m_callbackObject = obj;
m_valueChangedCallback = func;
}
bool hdCheckbox::MouseDown(float x, float y)
{
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
return m_activeButton->MouseDown(x, y);
}
bool hdCheckbox::MouseOver(float x, float y)
{
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
return m_activeButton->MouseOver(x, y);
}
bool hdCheckbox::MouseUp(float x, float y)
{
bool res;
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
res = m_activeButton->MouseUp(x, y);
if (res)
{
Toggle();
if (m_callbackObject != NULL && m_valueChangedCallback != NULL)
{
(*m_valueChangedCallback)(m_callbackObject, this);
}
}
return res;
}
bool hdCheckbox::MouseDoubleClick(float x, float y)
{
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
return m_activeButton->MouseDoubleClick(x, y);
}
void hdCheckbox::Toggle()
{
if (m_activeButton == m_onButton)
m_activeButton = m_offButton;
else
m_activeButton = m_onButton;
}
void hdCheckbox::SetOn()
{
hdAssert(m_onButton != NULL);
m_activeButton = m_onButton;
}
void hdCheckbox::SetOff()
{
hdAssert(m_offButton != NULL);
m_activeButton = m_offButton;
}
void hdCheckbox::Draw() const
{
m_activeButton->Draw();
}
bool hdCheckbox::IsOn() const
{
return (m_activeButton == m_onButton);
}
| 24.081081 | 91 | 0.650954 | cdave1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.