hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2fd158e68edbe45a9c974c01319d53d3d5100685
| 1,430
|
cpp
|
C++
|
5-1_if_else_if_2.cpp
|
ahfa92/cpp
|
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
|
[
"MIT"
] | null | null | null |
5-1_if_else_if_2.cpp
|
ahfa92/cpp
|
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
|
[
"MIT"
] | null | null | null |
5-1_if_else_if_2.cpp
|
ahfa92/cpp
|
bddd80ea5c6aca23c91bd6693bb32da06e67cbd2
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <string>
main()
{
char kd[3],mskp[15];
int kls;
long hrg=0;
cout<<"Masukkan Kode Pesawat [MPT/GRD/BTV] : ";cin>>kd;
cout<<"Kelas Pesawat : ";cin>>kls;
if(strcmp(kd,"MPT") || strcmp(kd,"mpt") || strcmp(kd,"Mpt"))
{
strcpy(mskp,"Merpati");
if(kls == 1){
hrg = 1500000;
}
else if(kls == 2){
hrg = 900000;
}
else if(kls == 3){
hrg = 500000;
}
else {
cout<<"Kode Kelas Salah"<<endl;
}
}
else if(strcmp(kd,"GRD") || strcmp(kd,"grd") || strcmp(kd,"Grd"))
{
strcpy(mskp,"Garuda");
if(kls == '1'){
hrg = 1200000;
}
else if(kls == '2'){
hrg = 800000;
}
else if(kls == '3'){
hrg = 400000;
}
else {
cout<<"Kode Kelas Salah"<<endl;
}
}
else if(strcmp(kd,"BTV") || strcmp(kd,"btv") || strcmp(kd,"Btv"))
{
strcpy(mskp,"Batavia");
if(kls == '1'){
hrg = 1000000;
}
else if(kls == '2'){
hrg = 700000;
}
else if(kls == '3'){
hrg = 300000;
}
else {
cout<<"Kode Kelas Salah"<<endl;
}
}
else {
cout<<"Kode Maskapai Salah"<<endl;
}
cout<<"======================"<<endl;
cout<<"Nama Pesawat : "<<mskp<<endl;
cout<<"Harga Tiket : "<<hrg<<endl;
getch();
}
| 19.324324
| 70
| 0.443357
|
ahfa92
|
2fd2689eda384e86d0f9c0e3dd861e7f3487a81a
| 912
|
cpp
|
C++
|
DxEngine/GDepthStencil.cpp
|
psk7142/DirectX2D
|
1d91e8a863aab2dbf57fecd2df111261a90dd3de
|
[
"MIT"
] | null | null | null |
DxEngine/GDepthStencil.cpp
|
psk7142/DirectX2D
|
1d91e8a863aab2dbf57fecd2df111261a90dd3de
|
[
"MIT"
] | null | null | null |
DxEngine/GDepthStencil.cpp
|
psk7142/DirectX2D
|
1d91e8a863aab2dbf57fecd2df111261a90dd3de
|
[
"MIT"
] | 2
|
2020-03-09T15:12:11.000Z
|
2020-03-09T16:04:04.000Z
|
#include "GDepthStencil.h"
GDepthStencil::GDepthStencil( )
: mDSDesc(D3D11_DEPTH_STENCIL_DESC( ))
, mState(nullptr)
{
EMPTY_STATEMENT;
}
GDepthStencil::~GDepthStencil( )
{
if ( nullptr != mState )
{
mState->Release( );
mState = nullptr;
}
}
bool GDepthStencil::Create( )
{
mDSDesc.DepthEnable = true;
mDSDesc.DepthFunc = D3D11_COMPARISON_FUNC::D3D11_COMPARISON_LESS;
mDSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK::D3D11_DEPTH_WRITE_MASK_ALL;
mDSDesc.StencilEnable = false;
return Create(mDSDesc);
}
bool GDepthStencil::Create(const D3D11_DEPTH_STENCIL_DESC& _desc)
{
if ( &mDSDesc != &_desc )
{
mDSDesc = _desc;
}
if ( FAILED(GEngineDevice::MainDevice( ).GetIDevice( ).CreateDepthStencilState(&mDSDesc, &mState)) )
{
CRASH_PROG;
return false;
}
return true;
}
void GDepthStencil::Update( )
{
GEngineDevice::MainDevice( ).GetIContext( ).OMSetDepthStencilState(mState, 0);
}
| 18.612245
| 101
| 0.730263
|
psk7142
|
2fd425d15c738d0423fd34bc77ada9b61274025e
| 7,803
|
hpp
|
C++
|
sdl/Hypergraph/ArcParserFct.hpp
|
sdl-research/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 29
|
2015-01-26T21:49:51.000Z
|
2021-06-18T18:09:42.000Z
|
sdl/Hypergraph/ArcParserFct.hpp
|
hypergraphs/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 1
|
2015-12-08T15:03:15.000Z
|
2016-01-26T14:31:06.000Z
|
sdl/Hypergraph/ArcParserFct.hpp
|
hypergraphs/hyp
|
d39f388f9cd283bcfa2f035f399b466407c30173
|
[
"Apache-2.0"
] | 4
|
2015-11-21T14:25:38.000Z
|
2017-10-30T22:22:00.000Z
|
// Copyright 2014-2015 SDL plc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** \file
parse text format hypergraph arcs.
*/
#ifndef HYP__HYPERGRAPH_ARCPARSERFCT_HPP
#define HYP__HYPERGRAPH_ARCPARSERFCT_HPP
#pragma once
#include <sdl/Hypergraph/ArcParser.hpp>
#include <sdl/Hypergraph/Exception.hpp>
#include <sdl/Hypergraph/IHypergraph.hpp>
#include <sdl/Hypergraph/IMutableHypergraph.hpp>
#include <sdl/Hypergraph/LabelPair.hpp>
#include <sdl/Hypergraph/ParsedArcsToHg.hpp>
#include <sdl/Hypergraph/SymbolPrint.hpp>
#include <sdl/Util/Contains.hpp>
#include <sdl/Util/Flag.hpp>
#include <sdl/Util/Input.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <sdl/Util/NormalizeUtf8.hpp>
#include <sdl/IVocabulary.hpp>
#include <sdl/SharedPtr.hpp>
#include <cassert>
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace sdl {
namespace Hypergraph {
namespace ArcParserFctUtil {
/**
Determines if string starts and end with angle brackets and
has some chars in between, e.g., <eps>.
*/
inline bool isInAngleBrackets(std::string const& str) {
std::string::size_type len = str.length();
return len > 2 && str[0] == '<' && str[len - 1] == '>';
}
//
/**
\return symbol from string
unless output, if <xmt-blockN>, then increment numBlockStartSymsSeen
Special syms like <eps> are not enclosed in quotes but in < >. If the parsed
text contains other syms like "the" or "<html>", they will be in quotes.
*/
inline Sym add(IVocabulary& voc, std::string const& word, bool lex, std::size_t* numBlockStartSymsSeen,
Sym defaultSym = NoSymbol, bool increaseNumBlocks = true) {
if (word.empty()) return defaultSym;
// we don't allow quoted "<special>"
if (lex)
return voc.add(word, kTerminal);
else {
if (isInAngleBrackets(word)) {
Sym id = Vocabulary::specialSymbols().sym(word);
if (id) {
if (id == BLOCK_START::ID) {
assert(numBlockStartSymsSeen);
id += (SymInt)*numBlockStartSymsSeen;
if (increaseNumBlocks) ++*numBlockStartSymsSeen;
}
return id;
} else {
SDL_WARN(Hypergraph.ArcParser, "unknown special symbol " << word << " - treating as nonterminal");
}
}
return voc.add(word, kNonterminal);
}
}
}
LabelPair const NoSymbols(NoSymbol, NoSymbol);
template <class Arc>
void addState(ParserUtil::State& s, SymsToState* symsToState, StateId& highestStateId, IVocabulary& voc,
IMutableHypergraph<Arc>* result, std::string const& src, std::size_t linenum,
std::size_t* numBlockStartSymsSeen) {
// need to call input before output symbol so block-start is incremented (true)
Sym const input = ArcParserFctUtil::add(voc, s.inputSymbol, s.isInputSymbolLexical, numBlockStartSymsSeen,
NoSymbol, true);
Sym const output = ArcParserFctUtil::add(voc, s.outputSymbol, s.isOutputSymbolLexical,
numBlockStartSymsSeen, NoSymbol, false);
LabelPair newLabels(input, output);
if (s.id == kNoState) {
if (newLabels == NoSymbols)
SDL_THROW_LOG(Hypergraph.ArcParserFct, FileFormatException,
"syntax error: addState for no labels and no state");
StateId* pState;
if (Util::update(*symsToState, newLabels, pState)) {
result->addStateId(s.id = *pState = ++highestStateId, newLabels);
} else {
s.id = *pState;
assert(s.id < result->size());
}
} else if (s.id == ParserUtil::State::kStart || s.id == ParserUtil::State::kFinal) {
if (newLabels != NoSymbols)
SDL_THROW_LOG(Hypergraph.ArcParserFct, FileFormatException,
"syntax error: " << src << ":" << linenum
<< ":syntax error (START and FINAL cannot have symbols)"
<< ": " << s);
} else { // state was specified already
(*symsToState)[newLabels]
= s.id; // this may be updated several times if user keeps using diff stateids w/ same label
LabelPair existingLabels = result->labelPairOptionalOutput(s.id);
if (newLabels == NoSymbols) {
result->addStateId(s.id);
} else if (existingLabels == NoSymbols || existingLabels == newLabels) {
result->addStateId(s.id, newLabels);
} else if (compatible(existingLabels, newLabels)) {
if (!newLabels.second) {
newLabels.second = newLabels.first;
(*symsToState)[newLabels] = s.id;
}
result->addStateId(s.id, newLabels);
} else {
SDL_THROW_LOG(Hypergraph.ArcParserFct, FileFormatException,
src << ":" << linenum << ": syntax error (incompatible symbols for state " << s.id << ")"
<< ": " << s << "; previous labels=" << printer(existingLabels, &voc)
<< " vs. new labels=" << printer(newLabels, &voc));
}
}
}
namespace impl {
/**
used as parseText(ParsedArcs ...) which takes ownership of new arcs. TODO: smart ptr
*/
struct ParsedArcsConsumer {
ParsedArcs& arcs;
ParsedArcsConsumer(ParsedArcs& arcs) : arcs(arcs) {}
ArcParser arcParser;
mutable Util::Counter linenum;
/// line is chomped (no trailing '\n') per StringConsumer
void operator()(std::string const& line) const {
++linenum;
if (!(line.empty() || line[0] == '#')) {
ParserUtil::Arc* pArc = arcParser.parse(line);
if (!pArc)
SDL_THROW_LOG(Hypergraph.ParsedLines, FileFormatException, ":" << linenum << ":syntax error" << line);
arcs.push_back(pArc);
}
}
};
}
template <class Arc>
void parseText(std::istream& in, std::string const& inFilename, IMutableHypergraph<Arc>* result,
bool requireNfc = true) {
ParsedArcs arcs;
impl::ParsedArcsConsumer accept(arcs);
Util::visitChompedLines(in, accept, requireNfc);
parsedArcsToHg(arcs, result, inFilename);
}
template <class Arc>
MutableHypergraph<Arc>* readHypergraphNew(std::istream& in, IVocabularyPtr pVoc,
Properties props = kFsmOutProperties,
std::string const& inName = "input") {
MutableHypergraph<Arc>* r = new MutableHypergraph<Arc>(props);
r->setVocabulary(pVoc);
parseText(in, inName, r);
return r;
}
template <class Arc>
shared_ptr<IHypergraph<Arc>> readHypergraph(std::istream& in, IVocabularyPtr pVoc,
Properties props = kFsmOutProperties,
std::string const& inName = "input") {
return readHypergraphNew<Arc>(in, pVoc, props, inName);
}
template <class Arc>
IHypergraph<Arc>& readHypergraph(std::istream& in, IMutableHypergraph<Arc>& hg,
std::string const& inName = "input") {
hg.clear();
hg.forceStoreArcs();
parseText(in, inName, &hg);
return hg;
}
template <class Arc>
shared_ptr<IHypergraph<Arc>> readHypergraph(Util::InputStream const& in, IVocabularyPtr pVoc,
Properties props = kFsmOutProperties) {
return readHypergraph<Arc>(*in, pVoc, props, in.name);
}
template <class Arc>
IHypergraph<Arc>& readHypergraph(Util::InputStream const& in, IMutableHypergraph<Arc>& hg) {
return readHypergraph(*in, hg, in.name);
}
}}
#endif
| 36.125
| 110
| 0.647059
|
sdl-research
|
7c7c49b76b1ea1161b86cdc65d96117cdc9b96ea
| 2,655
|
cpp
|
C++
|
Discord Cornfield/MessageWrap.cpp
|
ContionMig/Mitsuzi
|
90218e5e83845ad26c1398266453dcfbeeff4565
|
[
"MIT"
] | 1
|
2020-10-15T00:15:24.000Z
|
2020-10-15T00:15:24.000Z
|
Discord Cornfield/MessageWrap.cpp
|
ContionMig/Mitsuzi
|
90218e5e83845ad26c1398266453dcfbeeff4565
|
[
"MIT"
] | null | null | null |
Discord Cornfield/MessageWrap.cpp
|
ContionMig/Mitsuzi
|
90218e5e83845ad26c1398266453dcfbeeff4565
|
[
"MIT"
] | 3
|
2020-08-14T18:14:39.000Z
|
2021-04-11T10:46:46.000Z
|
#include "include.h"
namespace MessageWrap {
void BasicEmbedReturn(bool Error, std::string Disc, discord::MessageEvent& event, uint64_t timestamp) {
Helpers::ChecksStr(Disc);
event.channel()->send_embed([&Error, &Disc, ×tamp](discord::Embed& e) {
if (Error)
e.set_title(":red_circle: Error");
else
e.set_title(":green_circle: Success");
e.set_description(Disc);
uint64_t CurrentTimeStamp = Helpers::TimeStamp();
std::string TimeDifferent = std::to_string(CurrentTimeStamp - timestamp);
e.set_footer(std::string("Took " + TimeDifferent + " ms to execute"));
});
}
void EmbedReturn(std::string title, std::string disc, discord::MessageEvent& event, uint64_t timestamp) {
Helpers::ChecksStr(title); Helpers::ChecksStr(disc);
event.channel()->send_embed([&title, &disc, ×tamp](discord::Embed& e) {
if (title.length() > 0)
e.set_title(title);
if (disc.length() > 0)
e.set_description(disc);
uint64_t CurrentTimeStamp = Helpers::TimeStamp();
std::string TimeDifferent = std::to_string(CurrentTimeStamp - timestamp);
e.set_footer(std::string("Took " + TimeDifferent + " ms to execute"));
});
}
void EmbedLinkReturn(std::string title, std::string disc, std::string link, discord::MessageEvent& event, uint64_t timestamp) {
Helpers::ChecksStr(title); Helpers::ChecksStr(disc);
event.channel()->send_embed([&title, &disc, &link, ×tamp](discord::Embed& e) {
if (title.length() > 0)
e.set_title(title);
if (disc.length() > 0)
e.set_description(disc);
if (link.length() > 0)
e.set_url(link);
uint64_t CurrentTimeStamp = Helpers::TimeStamp();
std::string TimeDifferent = std::to_string(CurrentTimeStamp - timestamp);
e.set_footer(std::string("Took " + TimeDifferent + " ms to execute"));
});
}
void EmbedImageReturn(std::string URL, discord::MessageEvent& event, uint64_t timestamp) {
Helpers::ChecksStr(URL);
event.channel()->send_embed([&URL, ×tamp](discord::Embed& e) {
e.set_image(URL);
uint64_t CurrentTimeStamp = Helpers::TimeStamp();
std::string TimeDifferent = std::to_string(CurrentTimeStamp - timestamp);
e.set_footer(std::string("Took " + TimeDifferent + " ms to execute"));
});
}
}
| 44.25
| 132
| 0.580038
|
ContionMig
|
7c7d02ef078a9afa4d8469b8b6ed6e06f9f2d757
| 2,327
|
cpp
|
C++
|
Photon/photon/gfx/Shader.cpp
|
tatjam/Photon
|
a0c1584d10e1422cc2e468a6f94351a8310b7599
|
[
"MIT"
] | 1
|
2017-05-28T12:10:30.000Z
|
2017-05-28T12:10:30.000Z
|
Photon/photon/gfx/Shader.cpp
|
tatjam/Photon
|
a0c1584d10e1422cc2e468a6f94351a8310b7599
|
[
"MIT"
] | null | null | null |
Photon/photon/gfx/Shader.cpp
|
tatjam/Photon
|
a0c1584d10e1422cc2e468a6f94351a8310b7599
|
[
"MIT"
] | null | null | null |
#include "Shader.h"
namespace ph
{
void Shader::use()
{
glUseProgram(pr);
}
void Shader::load(std::string vpath, std::string fpath)
{
en->log(INF) << "Loading shaders: (" << vpath << ", " << fpath << ")" << endlog;
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
try
{
vShaderFile.open(vpath);
fShaderFile.open(fpath);
if (vShaderFile.bad() || fShaderFile.bad())
{
throw(std::exception("!"));
}
std::stringstream vShaderStream, fShaderStream;
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::exception e)
{
en->log(ERR) << "Could not load shader files" << endlog;
}
const GLchar* vShaderCode = vertexCode.c_str();
const GLchar * fShaderCode = fragmentCode.c_str();
GLuint vertex, fragment;
GLint success;
GLchar infoLog[512];
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
en->log(ERR) << "Could not compile vertex shader: " << infoLog << endlog;
}
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
en->log(ERR) << "Could not compile fragment shader: " << infoLog << endlog;
}
this->pr = glCreateProgram();
glAttachShader(this->pr, vertex);
glAttachShader(this->pr, fragment);
glLinkProgram(this->pr);
glGetProgramiv(this->pr, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(this->pr, 512, NULL, infoLog);
en->log(ERR) << "Could not link program: " << infoLog << endlog;
}
glDeleteShader(vertex);
glDeleteShader(fragment);
if (success)
{
en->log(WIN) << "Loaded shader successfully!" << endlog;
}
}
Shader::Shader(std::string v, std::string f, Engine* e)
{
en = e;
load(v, f);
}
Shader::Shader(Engine* e)
{
en = e;
}
Shader::~Shader()
{
}
}
| 23.27
| 82
| 0.661796
|
tatjam
|
7c840bbc662a3b2f2a5ed47ac08ede5b7f917771
| 1,778
|
cc
|
C++
|
src/ui/lib/escher/vk/image.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 210
|
2019-02-05T12:45:09.000Z
|
2022-03-28T07:59:06.000Z
|
src/ui/lib/escher/vk/image.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 56
|
2021-06-03T03:16:25.000Z
|
2022-03-20T01:07:44.000Z
|
src/ui/lib/escher/vk/image.cc
|
allansrc/fuchsia
|
a2c235b33fc4305044d496354a08775f30cdcf37
|
[
"BSD-2-Clause"
] | 73
|
2019-03-06T18:55:23.000Z
|
2022-03-26T12:04:51.000Z
|
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/lib/escher/vk/image.h"
#include "src/ui/lib/escher/util/image_utils.h"
namespace escher {
const ResourceTypeInfo Image::kTypeInfo("Image", ResourceType::kResource, ResourceType::kImage);
ImagePtr Image::WrapVkImage(ResourceManager* image_owner, ImageInfo info, vk::Image vk_image,
vk::ImageLayout initial_layout) {
// Wrapping transient image is disallowed because this class doesn't have access to the
// vk::DeviceMemory required to implement GetDeviceMemoryCommitment().
FX_CHECK(!info.is_transient()) << "Cannot wrap a transient image.";
return fxl::AdoptRef(new Image(image_owner, info, vk_image, 0, nullptr, initial_layout));
}
Image::Image(ResourceManager* image_owner, ImageInfo info, vk::Image image, vk::DeviceSize size,
uint8_t* host_ptr, vk::ImageLayout initial_layout)
: Resource(image_owner),
info_(info),
image_(image),
has_depth_(image_utils::IsDepthFormat(info.format)),
has_stencil_(image_utils::IsStencilFormat(info.format)),
size_(size),
host_ptr_(host_ptr),
layout_(initial_layout) {}
vk::DeviceSize Image::GetDeviceMemoryCommitment() {
// See WrapVkImage(). Since WrapVkImage() is the only way to directly instantiate an Image,
// and since WrapVkImage() disallows wrapping of transient images, this implies that this is an
// instance of a subclass of Image, which must override this implementation of
// GetDeviceMemoryCommitment().
FX_CHECK(!is_transient()) << "Subclass must implement GetDeviceMemoryCommitment()";
return size();
}
} // namespace escher
| 42.333333
| 97
| 0.731721
|
allansrc
|
7c856d5931fe7f03034f2733b37ebc942c2aab8a
| 50,799
|
cpp
|
C++
|
ps1/simplewindow/linux/fssimplewindow.cpp
|
lord-pradhan/CPP_graphics
|
1d4ea35c266b987947bf94bd07f4fa6c1c7684f2
|
[
"MIT"
] | null | null | null |
ps1/simplewindow/linux/fssimplewindow.cpp
|
lord-pradhan/CPP_graphics
|
1d4ea35c266b987947bf94bd07f4fa6c1c7684f2
|
[
"MIT"
] | null | null | null |
ps1/simplewindow/linux/fssimplewindow.cpp
|
lord-pradhan/CPP_graphics
|
1d4ea35c266b987947bf94bd07f4fa6c1c7684f2
|
[
"MIT"
] | null | null | null |
/* ////////////////////////////////////////////////////////////
File Name: fsglxwrapper.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
#include <X11/Xatom.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include "fssimplewindow.h"
#define FS_NUM_XK 65536
extern void FsXCreateKeyMapping(void);
extern int FsXKeySymToFskey(int keysym);
extern char FsXKeySymToChar(int keysym);
extern int FsXFskeyToKeySym(int fskey);
class FsMouseEventLog
{
public:
int eventType;
int lb,mb,rb;
int mx,my;
unsigned int shift,ctrl;
};
#define NKEYBUF 256
static int nKeyBufUsed=0;
static int keyBuffer[NKEYBUF];
static int nCharBufUsed=0;
static int charBuffer[NKEYBUF];
static int nMosBufUsed=0;
static FsMouseEventLog mosBuffer[NKEYBUF];
static Display *ysXDsp;
static Window ysXWnd;
static Colormap ysXCMap;
static XVisualInfo *ysXVis;
static const int ysXEventMask=(KeyPressMask|KeyReleaseMask|ButtonPressMask|ButtonReleaseMask|PointerMotionMask|ExposureMask|StructureNotifyMask);
static GLXContext ysGlRC;
static int ysGlxCfgSingle[]={GLX_RGBA,GLX_DEPTH_SIZE,16,None};
static int ysGlxCfgDouble[]={GLX_DOUBLEBUFFER,GLX_RGBA,GLX_DEPTH_SIZE,16,None};
static int ysXWid,ysXHei,ysXlupX,ysXlupY;
static int fsKeyPress[FSKEY_NUM_KEYCODE];
static int exposure=0;
static int lastKnownLb=0,lastKnownMb=0,lastKnownRb=0;
// For FsGui library tunnel >>
static long long int clipBoardContentLength=0;
static char *clipBoardContent=NULL;
static long long int pastedContentLength=0;
static char *pastedContent=NULL;
static void ProcessSelectionRequest(XEvent &evt);
// For FsGui library tunnel <<
static void ForceMoveWindow(Display *dsp,Window &wnd,int x,int y);
void FsOpenWindow(const FsOpenWindowOption &opt)
{
int x0=opt.x0;
int y0=opt.y0;
int wid=opt.wid;
int hei=opt.hei;
int useDoubleBuffer=(int)opt.useDoubleBuffer;
// int useMultiSampleBuffer=(int)opt.useMultiSampleBuffer;
const char *title=(NULL!=opt.windowTitle ? opt.windowTitle : "Main Window");
int n;
char **m,*def;
XSetWindowAttributes swa;
Font font;
int lupX,lupY,sizX,sizY;
lupX=x0;
lupY=y0;
sizX=wid;
sizY=hei;
FsXCreateKeyMapping();
for(n=0; n<FSKEY_NUM_KEYCODE; n++)
{
fsKeyPress[n]=0;
}
ysXDsp=XOpenDisplay(NULL);
if(ysXDsp!=NULL)
{
printf("Opened display.\n");
if(glXQueryExtension(ysXDsp,NULL,NULL)!=0)
{
printf("Acquired GLX extension.\n");
int tryAlternativeSingleBuffer=0;
if(useDoubleBuffer!=0)
{
ysXVis=glXChooseVisual(ysXDsp,DefaultScreen(ysXDsp),ysGlxCfgDouble);
}
else
{
ysXVis=glXChooseVisual(ysXDsp,DefaultScreen(ysXDsp),ysGlxCfgSingle);
if(NULL==ysXVis)
{
ysXVis=glXChooseVisual(ysXDsp,DefaultScreen(ysXDsp),ysGlxCfgDouble);
tryAlternativeSingleBuffer=1;
}
}
printf("Chose visual.\n");
if(ysXVis!=NULL)
{
ysXCMap=XCreateColormap(ysXDsp,RootWindow(ysXDsp,ysXVis->screen),ysXVis->visual,AllocNone);
printf("Created colormap.\n");
ysGlRC=glXCreateContext(ysXDsp,ysXVis,None,GL_TRUE);
if(ysGlRC!=NULL)
{
printf("Created OpenGL context.\n");
swa.colormap=ysXCMap;
swa.border_pixel=0;
swa.event_mask=ysXEventMask;
// Memo: lupX and lupY given to XCreateWindow will be ignored.
// Window must be moved to the desired position by XMoveWindow after XMapWindow.
ysXWnd=XCreateWindow(ysXDsp,RootWindow(ysXDsp,ysXVis->screen),
lupX,lupY,sizX,sizY,
1,
ysXVis->depth,
InputOutput,
ysXVis->visual,
CWEventMask|CWBorderPixel|CWColormap,&swa);
printf("Created Window.\n");
ysXWid=sizX;
ysXHei=sizY;
ysXlupX=lupX;
ysXlupY=lupY;
XStoreName(ysXDsp,ysXWnd,title);
// Should I use XSetWMProperties? titlebar problem.
XWMHints wmHints;
wmHints.flags=0;
wmHints.initial_state=NormalState;
XSetWMHints(ysXDsp,ysXWnd,&wmHints);
XSetIconName(ysXDsp,ysXWnd,title);
XMapWindow(ysXDsp,ysXWnd);
// Memo: XCreateWindow probably ignore lupX and lupY. Window must be moved here.
ForceMoveWindow(ysXDsp,ysXWnd,lupX,lupY);
// ForceMoveWindow may have failed to place the window, but let's at least reset lupX and lupY.
ysXlupX=lupX;
ysXlupY=lupY;
printf("Zzz...\n");
sleep(1);
printf("Slept one second.\n");
/* printf("Wait Expose Event\n");
XEvent ev;
while(XCheckTypedEvent(ysXDsp,Expose,&ev)!=True)
{
printf("Waiting for create notify\n");
sleep(1);
}
printf("Window=%d\n",ev.xexpose.window);
printf("Window Created\n"); */
glXMakeCurrent(ysXDsp,ysXWnd,ysGlRC);
// These lines are needed, or window will not appear >>
glClearColor(1.0F,1.0F,1.0F,0.0F);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glFlush();
// glXSwapBuffers(ysXDsp,ysXWnd);
// These lines are needed, or window will not appear <<
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);
GLfloat dif[]={0.8F,0.8F,0.8F,1.0F};
GLfloat amb[]={0.4F,0.4F,0.4F,1.0F};
GLfloat spc[]={0.9F,0.9F,0.9F,1.0F};
GLfloat shininess[]={50.0,50.0,50.0,0.0};
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0,GL_DIFFUSE,dif);
glLightfv(GL_LIGHT0,GL_SPECULAR,spc);
glMaterialfv(GL_FRONT|GL_BACK,GL_SHININESS,shininess);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,amb);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
if(0!=tryAlternativeSingleBuffer)
{
glDrawBuffer(GL_FRONT);
}
glClearColor(1.0F,1.0F,1.0F,0.0F);
glClearDepth(1.0F);
glDisable(GL_DEPTH_TEST);
glViewport(0,0,sizX,sizY);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,(float)sizX-1,(float)sizY-1,0,-1,1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glShadeModel(GL_FLAT);
glPointSize(1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glColor3ub(0,0,0);
if(NULL!=fsOpenGLInitializationCallBack)
{
(*fsOpenGLInitializationCallBack)(fsOpenGLInitializationCallBackParam);
}
if(NULL!=fsAfterWindowCreationCallBack)
{
(*fsAfterWindowCreationCallBack)(fsAfterWindowCreationCallBackParam);
}
}
else
{
fprintf(stderr,"Cannot create OpenGL context.\n");
exit(1);
}
}
else
{
fprintf(stderr,"Double buffer not supported?\n");
exit(1);
}
}
else
{
fprintf(stderr,"This system doesn't support OpenGL.\n");
exit(1);
}
}
else
{
fprintf(stderr,"Cannot Open Display.\n");
exit(1);
}
return;
}
int FsCheckWindowOpen(void)
{
if(ysXWnd!=NULL)
{
return 1;
}
return 0;
}
static void ForceMoveWindow(Display *dsp,Window &wnd,int goalX,int goalY)
{
// This function tries to address the inability of X-Window system to place a window at a precise location.
// However, the window may still be moved to a random location after this function.
// There seems to be no remedy.
auto timeOut=time(NULL);
int tryX=goalX;
int tryY=goalY;
int tryingX=tryX+1;
int tryingY=tryY+1;
// Wait until the second border
while(time(NULL)==timeOut)
{
}
// timeOut=time(NULL);
// while(time(NULL)==timeOut)
// {
// XEvent ev;
// XCheckTypedWindowEvent(dsp,wnd,ConfigureNotify,&ev);
// }
timeOut=time(NULL)+1;
while(time(NULL)<timeOut) // Until the window is really located at lupX, lupY
{
if(tryingX!=tryX || tryingY!=tryY)
{
XMoveWindow(dsp,wnd,tryX,tryY);
tryingX=tryX;
tryingY=tryY;
}
XEvent ev;
if(XCheckTypedWindowEvent(dsp,wnd,ConfigureNotify,&ev)==True)
{
const int actualX=ev.xconfigure.x;
const int actualY=ev.xconfigure.y;
printf("%d %d %d %d\n",actualX,actualY,goalX,goalY);
const int dx=goalX-actualX;
const int dy=goalY-actualY;
if(-1<=dx && dx<=1 && -1<=dy && dy<=1)
{
break;
}
printf("dx %d dy %d\n",dx,dy);
tryX+=dx;
tryY+=dy;
if(0<dx)
{
++tryX;
}
else if(0>dx)
{
--tryX;
}
if(0<dy)
{
++tryY;
}
else if(0>dy)
{
--tryY;
}
}
}
}
void FsGetWindowSize(int &wid,int &hei)
{
wid=ysXWid;
hei=ysXHei;
}
void FsGetWindowPosition(int &x0,int &y0)
{
x0=ysXlupX;
y0=ysXlupY;
}
void FsSetWindowTitle(const char windowTitle[])
{
printf("Sorry. %s not supported on this platform yet\n",__FUNCTION__);
}
void FsPollDevice(void)
{
int i,fsKey;
char chr;
KeySym ks;
XEvent ev;
fsKey=FSKEY_NULL;
while(XCheckWindowEvent(ysXDsp,ysXWnd,KeyPressMask|KeyReleaseMask,&ev)==True)
{
int i;
KeySym *keySymMap;
int keysyms_per_keycode_return;
keySymMap=XGetKeyboardMapping(ysXDsp,ev.xkey.keycode,1,&keysyms_per_keycode_return);
// printf("NumKeySym=%d\n",keysyms_per_keycode_return);
// printf("%s %s\n",XKeysymToString(keySymMap[0]),XKeysymToString(keySymMap[1]));
// printf("%d %d %d %d %d %d %d %d\n",
// (ev.xkey.state&LockMask)!=0,
// (ev.xkey.state&ShiftMask)!=0,
// (ev.xkey.state&ControlMask)!=0,
// (ev.xkey.state&Mod1Mask)!=0, // Alt
// (ev.xkey.state&Mod2Mask)!=0, // Num Lock
// (ev.xkey.state&Mod3Mask)!=0,
// (ev.xkey.state&Mod4Mask)!=0, // Windows key
// (ev.xkey.state&Mod5Mask)!=0);
if(0!=(ev.xkey.state&ControlMask) || 0!=(ev.xkey.state&Mod1Mask))
{
chr=0;
}
else if((ev.xkey.state&LockMask)==0 && (ev.xkey.state&ShiftMask)==0)
{
chr=FsXKeySymToChar(keySymMap[0]); // mapXKtoChar[keySymMap[0]];
}
else if((ev.xkey.state&LockMask)==0 && (ev.xkey.state&ShiftMask)!=0)
{
chr=FsXKeySymToChar(keySymMap[1]); // mapXKtoChar[keySymMap[1]];
}
else if((ev.xkey.state&ShiftMask)==0 && (ev.xkey.state&LockMask)!=0)
{
chr=FsXKeySymToChar(keySymMap[0]); // mapXKtoChar[keySymMap[0]];
if('a'<=chr && chr<='z')
{
chr=chr+('A'-'a');
}
}
else if((ev.xkey.state&ShiftMask)!=0 && (ev.xkey.state&LockMask)!=0)
{
chr=FsXKeySymToChar(keySymMap[1]); // mapXKtoChar[keySymMap[1]];
if('a'<=chr && chr<='z')
{
chr=chr+('A'-'a');
}
}
// Memo:
// XK code is so badly designed. XK_KP_Divide, XK_KP_Multiply,
// XK_KP_Subtract, XK_KP_Add, should not be altered to
// XK_XF86_Next_VMode or like that. Other XK_KP_ code
// can be altered by Mod2Mask.
// following keys should be flipped based on Num Lock mask. Apparently mod2mask is num lock by standard.
// XK_KP_Space
// XK_KP_Tab
// XK_KP_Enter
// XK_KP_F1
// XK_KP_F2
// XK_KP_F3
// XK_KP_F4
// XK_KP_Home
// XK_KP_Left
// XK_KP_Up
// XK_KP_Right
// XK_KP_Down
// XK_KP_Prior
// XK_KP_Page_Up
// XK_KP_Next
// XK_KP_Page_Down
// XK_KP_End
// XK_KP_Begin
// XK_KP_Insert
// XK_KP_Delete
// XK_KP_Equal
// XK_KP_Multiply
// XK_KP_Add
// XK_KP_Separator
// XK_KP_Subtract
// XK_KP_Decimal
// XK_KP_Divide
// XK_KP_0
// XK_KP_1
// XK_KP_2
// XK_KP_3
// XK_KP_4
// XK_KP_5
// XK_KP_6
// XK_KP_7
// XK_KP_8
// XK_KP_9
ks=XKeycodeToKeysym(ysXDsp,ev.xkey.keycode,0);
if(XK_a<=ks && ks<=XK_z)
{
ks=ks+XK_A-XK_a;
}
if(ks==XK_Alt_R)
{
ks=XK_Alt_L;
}
if(ks==XK_Shift_R)
{
ks=XK_Shift_L;
}
if(ks==XK_Control_R)
{
ks=XK_Control_L;
}
if(0<=ks && ks<FS_NUM_XK)
{
fsKey=FsXKeySymToFskey(ks); // mapXKtoFSKEY[ks];
// 2005/03/29 >>
if(fsKey==0)
{
KeyCode kcode;
kcode=XKeysymToKeycode(ysXDsp,ks);
if(kcode!=0)
{
ks=XKeycodeToKeysym(ysXDsp,kcode,0);
if(XK_a<=ks && ks<=XK_z)
{
ks=ks+XK_A-XK_a;
}
if(ks==XK_Alt_R)
{
ks=XK_Alt_L;
}
if(ks==XK_Shift_R)
{
ks=XK_Shift_L;
}
if(ks==XK_Control_R)
{
ks=XK_Control_L;
}
if(0<=ks && ks<FS_NUM_XK)
{
fsKey=FsXKeySymToFskey(ks); // mapXKtoFSKEY[ks];
}
}
}
// 2005/03/29 <<
if(ev.type==KeyPress && fsKey!=0)
{
fsKeyPress[fsKey]=1;
if(ev.xkey.window==ysXWnd) // 2005/04/08
{
if(nKeyBufUsed<NKEYBUF)
{
keyBuffer[nKeyBufUsed++]=fsKey;
}
if(chr!=0 && nCharBufUsed<NKEYBUF)
{
charBuffer[nCharBufUsed++]=chr;
}
}
}
else
{
fsKeyPress[fsKey]=0;
}
}
}
while(XCheckWindowEvent(ysXDsp,ysXWnd,ButtonPressMask|ButtonReleaseMask|PointerMotionMask,&ev)==True)
{
if(ButtonPress==ev.type || ButtonRelease==ev.type)
{
fsKey=FSKEY_NULL;
if(ev.xbutton.button==Button4)
{
fsKey=FSKEY_WHEELUP;
}
else if(ev.xbutton.button==Button5)
{
fsKey=FSKEY_WHEELDOWN;
}
if(FSKEY_NULL!=fsKey)
{
if(ev.type==ButtonPress)
{
fsKeyPress[fsKey]=1;
if(ev.xbutton.window==ysXWnd)
{
if(nKeyBufUsed<NKEYBUF)
{
keyBuffer[nKeyBufUsed++]=fsKey;
}
}
}
else if(ev.type==ButtonRelease)
{
fsKeyPress[fsKey]=0;
}
}
else if(NKEYBUF>nMosBufUsed)
{
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_NONE;
if(ev.type==ButtonPress)
{
switch(ev.xbutton.button)
{
case Button1:
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_LBUTTONDOWN;
lastKnownLb=1;
break;
case Button2:
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_MBUTTONDOWN;
lastKnownMb=1;
break;
case Button3:
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_RBUTTONDOWN;
lastKnownRb=1;
break;
}
}
else if(ev.type==ButtonRelease)
{
switch(ev.xbutton.button)
{
case Button1:
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_LBUTTONUP;
lastKnownLb=0;
break;
case Button2:
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_MBUTTONUP;
lastKnownMb=0;
break;
case Button3:
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_RBUTTONUP;
lastKnownRb=0;
break;
}
}
mosBuffer[nMosBufUsed].mx=ev.xbutton.x;
mosBuffer[nMosBufUsed].my=ev.xbutton.y;
// Turned out these button states are highly unreliable.
// It may come with (state&Button1Mask)==0 on ButtonPress event of Button 1.
// Confirmed this problem in VirtualBox. This silly flaw may not occur in
// real environment.
// mosBuffer[nMosBufUsed].lb=(0!=(ev.xbutton.state & Button1Mask));
// mosBuffer[nMosBufUsed].mb=(0!=(ev.xbutton.state & Button2Mask));
// mosBuffer[nMosBufUsed].rb=(0!=(ev.xbutton.state & Button3Mask));
mosBuffer[nMosBufUsed].lb=lastKnownLb;
mosBuffer[nMosBufUsed].mb=lastKnownMb;
mosBuffer[nMosBufUsed].rb=lastKnownRb;
mosBuffer[nMosBufUsed].shift=(0!=(ev.xbutton.state & ShiftMask));
mosBuffer[nMosBufUsed].ctrl=(0!=(ev.xbutton.state & ControlMask));
nMosBufUsed++;
}
}
else if(ev.type==MotionNotify)
{
int mx=ev.xbutton.x;
int my=ev.xbutton.y;
int lb=lastKnownLb; // XButtonEvent.state turns out to be highly unreliable (0!=(ev.xbutton.state & Button1Mask));
int mb=lastKnownMb; // (0!=(ev.xbutton.state & Button2Mask));
int rb=lastKnownRb; // (0!=(ev.xbutton.state & Button3Mask));
int shift=(0!=(ev.xbutton.state & ShiftMask));
int ctrl=(0!=(ev.xbutton.state & ControlMask));
if(0<nMosBufUsed &&
mosBuffer[nMosBufUsed-1].eventType==FSMOUSEEVENT_MOVE &&
mosBuffer[nMosBufUsed-1].lb==lb &&
mosBuffer[nMosBufUsed-1].mb==mb &&
mosBuffer[nMosBufUsed-1].rb==rb &&
mosBuffer[nMosBufUsed-1].shift==shift &&
mosBuffer[nMosBufUsed-1].ctrl==ctrl)
{
mosBuffer[nMosBufUsed-1].mx=mx;
mosBuffer[nMosBufUsed-1].my=my;
}
if(NKEYBUF>nMosBufUsed)
{
mosBuffer[nMosBufUsed].mx=mx;
mosBuffer[nMosBufUsed].my=my;
mosBuffer[nMosBufUsed].lb=lb;
mosBuffer[nMosBufUsed].mb=mb;
mosBuffer[nMosBufUsed].rb=rb;
mosBuffer[nMosBufUsed].shift=shift;
mosBuffer[nMosBufUsed].ctrl=ctrl;
mosBuffer[nMosBufUsed].eventType=FSMOUSEEVENT_MOVE;
nMosBufUsed++;
}
}
}
if(XCheckTypedWindowEvent(ysXDsp,ysXWnd,ConfigureNotify,&ev)==True)
{
ysXWid=ev.xconfigure.width;
ysXHei=ev.xconfigure.height;
ysXlupX=ev.xconfigure.x;
ysXlupY=ev.xconfigure.y;
}
if(XCheckWindowEvent(ysXDsp,ysXWnd,ExposureMask,&ev)==True)
{
exposure=1;
if(NULL!=fsOnPaintCallback)
{
(*fsOnPaintCallback)(fsOnPaintCallbackParam);
}
}
// Clipboard Tunnel for FsGuiLib >>
if(True==XCheckTypedWindowEvent(ysXDsp,ysXWnd,SelectionRequest,&ev) ||
True==XCheckTypedWindowEvent(ysXDsp,ysXWnd,SelectionClear,&ev))
{
if(ev.type==SelectionRequest)
{
ProcessSelectionRequest(ev);
}
else if(ev.type==SelectionClear)
{
printf("Lost selection ownership.\n");
}
}
// Clipboard Tunnel for FsGuiLib <<
if(XCheckTypedWindowEvent(ysXDsp,ysXWnd,DestroyNotify,&ev)==True)
{
exit(1);
}
return;
}
void FsPushOnPaintEvent(void)
{
XExposeEvent evt;
evt.type=Expose;
evt.serial=0;
evt.send_event=true;
evt.display=ysXDsp;
evt.window=ysXWnd;
evt.x=0;
evt.y=0;
evt.width=ysXWid;
evt.height=ysXHei;
evt.count=0;
XSendEvent(ysXDsp,ysXWnd,true,ExposureMask,(XEvent *)&evt);
}
void FsCloseWindow(void)
{
if(NULL!=clipBoardContent)
{
delete [] clipBoardContent;
}
if(NULL!=pastedContent)
{
delete [] pastedContent;
}
XCloseDisplay(ysXDsp);
}
void FsMaximizeWindow(void)
{
printf("Sorry. %s not supported on this platform yet\n",__FUNCTION__);
}
void FsUnmaximizeWindow(void)
{
printf("Sorry. %s not supported on this platform yet\n",__FUNCTION__);
}
void FsMakeFullScreen(void)
{
printf("Sorry. %s not supported on this platform yet\n",__FUNCTION__);
}
void FsSleep(int ms)
{
if(ms>0)
{
fd_set set;
struct timeval wait;
wait.tv_sec=ms/1000;
wait.tv_usec=(ms%1000)*1000;
FD_ZERO(&set);
select(0,&set,NULL,NULL,&wait);
}
}
long long int FsPassedTime(void)
{
static long long int lastTick;
long long int tick;
static int first=1;
if(1==first)
{
lastTick=FsSubSecondTimer();
first=0;
}
tick=FsSubSecondTimer();
long long passed=tick-lastTick;
lastTick=tick;
return passed;
}
long long int FsSubSecondTimer(void)
{
timeval tm;
gettimeofday(&tm,NULL);
long long int sec=tm.tv_sec;
long long int usec=tm.tv_usec;
long long int clk=sec*(long long int)1000+usec/(long long int)1000;
static long long int lastValue=0;
static long long int base=0;
if(clk<lastValue) // Underflow. It's tomorrow now.
{
base+=1000*3600*24;
}
lastValue=clk;
static int first=1;
static long long int t0=0;
if(1==first)
{
t0=base+clk;
first=0;
}
return base+clk-t0;
}
void FsGetMouseState(int &lb,int &mb,int &rb,int &mx,int &my)
{
Window r,c;
int xInRoot,yInRoot;
unsigned int mask;
XQueryPointer(ysXDsp,ysXWnd,&r,&c,&xInRoot,&yInRoot,&mx,&my,&mask);
/* These masks are seriouly unreliable. It could still report zero after ButtonPress event
is issued. Therefore, it causes inconsistency and unusable. Flaw confirmed in VirtualBox.
lb=((mask & Button1Mask) ? 1 : 0);
mb=((mask & Button2Mask) ? 1 : 0);
rb=((mask & Button3Mask) ? 1 : 0); */
lb=lastKnownLb;
mb=lastKnownMb;
rb=lastKnownRb;
}
int FsGetMouseEvent(int &lb,int &mb,int &rb,int &mx,int &my)
{
if(0<nMosBufUsed)
{
int eventType=mosBuffer[0].eventType;
mx=mosBuffer[0].mx;
my=mosBuffer[0].my;
lb=mosBuffer[0].lb;
mb=mosBuffer[0].mb;
rb=mosBuffer[0].rb;
int i;
for(i=0; i<nMosBufUsed-1; i++)
{
mosBuffer[i]=mosBuffer[i+1];
}
nMosBufUsed--;
return eventType;
}
else
{
FsGetMouseState(lb,mb,rb,mx,my);
return FSMOUSEEVENT_NONE;
}
}
void FsSwapBuffers(void)
{
glFlush();
glXSwapBuffers(ysXDsp,ysXWnd);
}
int FsInkey(void)
{
if(nKeyBufUsed>0)
{
int i,keyCode;
keyCode=keyBuffer[0];
nKeyBufUsed--;
for(i=0; i<nKeyBufUsed; i++)
{
keyBuffer[i]=keyBuffer[i+1];
}
return keyCode;
}
return 0;
}
int FsInkeyChar(void)
{
if(nCharBufUsed>0)
{
int i,asciiCode;
asciiCode=charBuffer[0];
nCharBufUsed--;
for(i=0; i<nCharBufUsed; i++)
{
charBuffer[i]=charBuffer[i+1];
}
return asciiCode;
}
return 0;
}
int FsGetKeyState(int fsKeyCode)
{
if(0<fsKeyCode && fsKeyCode<FSKEY_NUM_KEYCODE)
{
return fsKeyPress[fsKeyCode];
}
return 0;
}
int FsCheckWindowExposure(void)
{
int ret;
ret=exposure;
exposure=0;
return ret;
}
////////////////////////////////////////////////////////////
// Clipboard support
static void ProcessSelectionRequest(XEvent &evt)
{
XEvent reply;
Atom targetsAtom=XInternAtom(ysXDsp,"TARGETS",0);
reply.xselection.type=SelectionNotify;
reply.xselection.serial=evt.xselectionrequest.serial;
reply.xselection.send_event=True;
reply.xselection.display=ysXDsp;
reply.xselection.requestor=evt.xselectionrequest.requestor;
reply.xselection.selection=evt.xselectionrequest.selection;
reply.xselection.target=evt.xselectionrequest.target;
reply.xselection.property=evt.xselectionrequest.property; // None for nothing.
reply.xselection.time=evt.xselectionrequest.time; // None for nothing.
if(evt.xselectionrequest.target==targetsAtom)
{
Atom dataType[]={XA_STRING,targetsAtom};
XChangeProperty(ysXDsp,evt.xselectionrequest.requestor,evt.xselectionrequest.property,XA_ATOM,32,PropModeReplace,(unsigned char *)dataType,2);
printf("Answered supported data type.\n");
}
else if(evt.xselectionrequest.target==XA_STRING) // Since it declares it only accepts XA_TARGETS and XA_STRING, target should be a XA_STRING
{
XChangeProperty(ysXDsp,evt.xselectionrequest.requestor,evt.xselectionrequest.property,evt.xselectionrequest.target,8,PropModeReplace,(unsigned char *)clipBoardContent,clipBoardContentLength);
}
else // Just in case.
{
// Apparently, in this case, the requestor is supposed to try a different target type.
reply.xselection.property=None;
}
XSendEvent(ysXDsp,evt.xselectionrequest.requestor,True,NoEventMask,&reply);
}
void FsX11GetClipBoardString(long long int &returnLength,char *&returnStr)
{
if(NULL!=pastedContent)
{
delete [] pastedContent;
}
pastedContent=NULL;
pastedContentLength=0;
returnLength=0;
returnStr=NULL;
Atom clipboardAtom=XInternAtom(ysXDsp,"CLIPBOARD",0);
Atom dataReceiverAtom=XInternAtom(ysXDsp,"GET_DATA",0); // For receiving
Atom type_return;
int format_return;
long unsigned int nitems_return;
long unsigned int bytes_after_return;
unsigned char *bufPtr=NULL;
XConvertSelection(ysXDsp,clipboardAtom,XA_STRING,dataReceiverAtom,ysXWnd,CurrentTime);
// See experiment/XWindow/cutbuf/selfcopypaste.cpp
// If this program owns a clipboard, and also inquire the clipboard contents,
// this program needs to manage both SelectionRequest and SelectionNotify to
// return the clipboard content.
for(;;)
{
XEvent evt;
if(True==XCheckTypedWindowEvent(ysXDsp,ysXWnd,SelectionRequest,&evt) ||
True==XCheckTypedWindowEvent(ysXDsp,ysXWnd,SelectionClear,&evt) ||
True==XCheckTypedWindowEvent(ysXDsp,ysXWnd,SelectionNotify,&evt))
{
if(evt.type==SelectionRequest)
{
ProcessSelectionRequest(evt);
}
else if(evt.type==SelectionClear)
{
printf("Lost selection ownership.\n");
}
else if(evt.type==SelectionNotify)
{
if(None!=evt.xselection.property)
{
Atom type_return;
int format_return;
long unsigned int nitems_return;
long unsigned int bytes_after_return;
unsigned char *bufPtr=NULL;
XGetWindowProperty(ysXDsp,ysXWnd,evt.xselection.property,0,256,False,XA_STRING,&type_return,&format_return,&nitems_return,&bytes_after_return,&bufPtr);
printf("Type %d\n",(int)type_return);
printf("%d bytes\n",(int)nitems_return);
printf("%d remain\n",(int)bytes_after_return);
printf("%s\n",bufPtr);
pastedContentLength=nitems_return;
pastedContent=new char [nitems_return];
for(int idx=0; idx<nitems_return; ++idx)
{
pastedContent[idx]=(char)bufPtr[idx];
}
XFree(bufPtr);
}
else
{
printf("No selection.\n");
}
break;
}
else
{
printf("Other event.\n");
}
}
}
returnLength=pastedContentLength;
returnStr=pastedContent;
}
void FsX11SetClipBoardString(long long int length,const char str[])
{
if(NULL!=clipBoardContent)
{
delete [] clipBoardContent;
clipBoardContent=NULL;
clipBoardContentLength=0;
}
clipBoardContentLength=length;
clipBoardContent=new char [length];
for(int i=0; i<length; ++i)
{
clipBoardContent[i]=str[i];
}
Atom clipboardAtom=XInternAtom(ysXDsp,"CLIPBOARD",0);
XSetSelectionOwner(ysXDsp,clipboardAtom,ysXWnd,CurrentTime);
XSetSelectionOwner(ysXDsp,XA_PRIMARY,ysXWnd,CurrentTime);
}
void FsChangeToProgramDir(void)
{
char buf[4096];
auto len=readlink("/proc/self/exe",buf,4095);
if(len<4095)
{
buf[len]=0;
for(len=strlen(buf); 0<len; --len) // Probably it is safe to say for(len=len; 0<len; --len)
{
if(buf[len]=='/')
{
buf[len]=0;
break;
}
}
if(0!=chdir(buf))
{
switch(errno)
{
case EACCES:
printf("EACCES\n");
break;
case EFAULT:
printf("EFAULT\n");
break;
case EIO:
printf("EIO\n");
break;
case ELOOP:
printf("ELOOP\n");
break;
case ENAMETOOLONG:
printf("ENAMETOOLONG\n");
break;
case ENOENT:
printf("ENOENT\n");
break;
case ENOMEM:
printf("ENOMEM\n");
break;
case ENOTDIR:
printf("ENOTDIR\n");
break;
case EBADF:
printf("EBADF\n");
break;
}
}
// 2016/1/1 chdir ignored?
getcwd(buf,4095);
printf("Changed to %s\n",buf);
}
else
{
printf("Current process file name too long.\n");
}
}
void FsPushKey(int fskey)
{
if(nKeyBufUsed<NKEYBUF)
{
keyBuffer[nKeyBufUsed++]=fskey;
}
}
void FsPushChar(int c)
{
if(nCharBufUsed<NKEYBUF)
{
charBuffer[nCharBufUsed++]=c;
}
}
int FsGetNumCurrentTouch(void)
{
return 0;
}
const FsVec2i *FsGetCurrentTouch(void)
{
return nullptr;
}
////////////////////////////////////////////////////////////
// How can I enable IME in Linux?
int FsEnableIME(void)
{
return 0;
}
void FsDisableIME(void)
{
}
////////////////////////////////////////////////////////////
int FsIsNativeTextInputAvailable(void)
{
return 0;
}
int FsOpenNativeTextInput(int x1,int y1,int wid,int hei)
{
return 0;
}
void FsCloseNativeTextInput(void)
{
}
void FsSetNativeTextInputText(const wchar_t [])
{
}
int FsGetNativeTextInputTextLength(void)
{
return 0;
}
void FsGetNativeTextInputText(wchar_t str[],int bufLen)
{
if(0<bufLen)
{
str[0]=0;
}
}
int FsGetNativeTextInputEvent(void)
{
return FSNATIVETEXTEVENT_NONE;
}
/* ////////////////////////////////////////////////////////////
File Name: fsglxkeymap.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
static int mapXKtoFSKEY[FS_NUM_XK];
static char mapXKtoChar[FS_NUM_XK];
static int mapFSKEYtoXK[FSKEY_NUM_KEYCODE];
static void FsXAddKeyMapping(int fskey,int keysym)
{
if(fskey<0 || FSKEY_NUM_KEYCODE<=fskey)
{
fprintf(stderr,"FSKEY is out of range\n");
return;
}
if(keysym<0 || FS_NUM_XK<=keysym)
{
fprintf(stderr,"XK is out of range\n");
return;
}
mapXKtoFSKEY[keysym]=fskey;
mapFSKEYtoXK[fskey]=keysym;
}
static void FsXAddKeysymToCharMapping(int keysym,char c)
{
if(0<keysym && keysym<FS_NUM_XK)
{
mapXKtoChar[keysym]=c;
}
}
void FsXCreateKeyMapping(void)
{
int i;
for(i=0; i<FS_NUM_XK; i++)
{
mapXKtoFSKEY[i]=0;
mapXKtoChar[i]=0;
}
for(i=0; i<FSKEY_NUM_KEYCODE; i++)
{
mapFSKEYtoXK[i]=0;
}
FsXAddKeyMapping(FSKEY_SPACE, XK_space);
FsXAddKeyMapping(FSKEY_0, XK_0);
FsXAddKeyMapping(FSKEY_1, XK_1);
FsXAddKeyMapping(FSKEY_2, XK_2);
FsXAddKeyMapping(FSKEY_3, XK_3);
FsXAddKeyMapping(FSKEY_4, XK_4);
FsXAddKeyMapping(FSKEY_5, XK_5);
FsXAddKeyMapping(FSKEY_6, XK_6);
FsXAddKeyMapping(FSKEY_7, XK_7);
FsXAddKeyMapping(FSKEY_8, XK_8);
FsXAddKeyMapping(FSKEY_9, XK_9);
FsXAddKeyMapping(FSKEY_A, XK_A);
FsXAddKeyMapping(FSKEY_B, XK_B);
FsXAddKeyMapping(FSKEY_C, XK_C);
FsXAddKeyMapping(FSKEY_D, XK_D);
FsXAddKeyMapping(FSKEY_E, XK_E);
FsXAddKeyMapping(FSKEY_F, XK_F);
FsXAddKeyMapping(FSKEY_G, XK_G);
FsXAddKeyMapping(FSKEY_H, XK_H);
FsXAddKeyMapping(FSKEY_I, XK_I);
FsXAddKeyMapping(FSKEY_J, XK_J);
FsXAddKeyMapping(FSKEY_K, XK_K);
FsXAddKeyMapping(FSKEY_L, XK_L);
FsXAddKeyMapping(FSKEY_M, XK_M);
FsXAddKeyMapping(FSKEY_N, XK_N);
FsXAddKeyMapping(FSKEY_O, XK_O);
FsXAddKeyMapping(FSKEY_P, XK_P);
FsXAddKeyMapping(FSKEY_Q, XK_Q);
FsXAddKeyMapping(FSKEY_R, XK_R);
FsXAddKeyMapping(FSKEY_S, XK_S);
FsXAddKeyMapping(FSKEY_T, XK_T);
FsXAddKeyMapping(FSKEY_U, XK_U);
FsXAddKeyMapping(FSKEY_V, XK_V);
FsXAddKeyMapping(FSKEY_W, XK_W);
FsXAddKeyMapping(FSKEY_X, XK_X);
FsXAddKeyMapping(FSKEY_Y, XK_Y);
FsXAddKeyMapping(FSKEY_Z, XK_Z);
FsXAddKeyMapping(FSKEY_ESC, XK_Escape);
FsXAddKeyMapping(FSKEY_F1, XK_F1);
FsXAddKeyMapping(FSKEY_F2, XK_F2);
FsXAddKeyMapping(FSKEY_F3, XK_F3);
FsXAddKeyMapping(FSKEY_F4, XK_F4);
FsXAddKeyMapping(FSKEY_F5, XK_F5);
FsXAddKeyMapping(FSKEY_F6, XK_F6);
FsXAddKeyMapping(FSKEY_F7, XK_F7);
FsXAddKeyMapping(FSKEY_F8, XK_F8);
FsXAddKeyMapping(FSKEY_F9, XK_F9);
FsXAddKeyMapping(FSKEY_F10, XK_F10);
FsXAddKeyMapping(FSKEY_F11, XK_F11);
FsXAddKeyMapping(FSKEY_F12, XK_F12);
FsXAddKeyMapping(FSKEY_PRINTSCRN, 0);
FsXAddKeyMapping(FSKEY_SCROLLLOCK, 0);
FsXAddKeyMapping(FSKEY_PAUSEBREAK, XK_Cancel);
FsXAddKeyMapping(FSKEY_TILDA, 0);
FsXAddKeyMapping(FSKEY_MINUS, XK_minus);
FsXAddKeyMapping(FSKEY_PLUS, XK_plus);
FsXAddKeyMapping(FSKEY_BS, XK_BackSpace);
FsXAddKeyMapping(FSKEY_TAB, XK_Tab);
FsXAddKeyMapping(FSKEY_LBRACKET, XK_bracketleft);
FsXAddKeyMapping(FSKEY_RBRACKET, XK_bracketright);
FsXAddKeyMapping(FSKEY_BACKSLASH, XK_backslash);
FsXAddKeyMapping(FSKEY_CAPSLOCK, 0);
FsXAddKeyMapping(FSKEY_SEMICOLON, ';');
// FsXAddKeyMapping(FSKEY_COLON, ':');
FsXAddKeyMapping(FSKEY_SINGLEQUOTE, '\'');
FsXAddKeyMapping(FSKEY_ENTER, XK_Return);
FsXAddKeyMapping(FSKEY_SHIFT, XK_Shift_L);
FsXAddKeyMapping(FSKEY_COMMA, XK_comma);
FsXAddKeyMapping(FSKEY_DOT, XK_period);
FsXAddKeyMapping(FSKEY_SLASH, XK_slash);
FsXAddKeyMapping(FSKEY_CTRL, XK_Control_L);
FsXAddKeyMapping(FSKEY_ALT, XK_Alt_L);
FsXAddKeyMapping(FSKEY_INS, XK_Insert);
FsXAddKeyMapping(FSKEY_DEL, XK_Delete);
FsXAddKeyMapping(FSKEY_HOME, XK_Home);
FsXAddKeyMapping(FSKEY_END, XK_End);
FsXAddKeyMapping(FSKEY_PAGEUP, XK_Page_Up);
FsXAddKeyMapping(FSKEY_PAGEDOWN, XK_Page_Down);
FsXAddKeyMapping(FSKEY_UP, XK_Up);
FsXAddKeyMapping(FSKEY_DOWN, XK_Down);
FsXAddKeyMapping(FSKEY_LEFT, XK_Left);
FsXAddKeyMapping(FSKEY_RIGHT, XK_Right);
FsXAddKeyMapping(FSKEY_NUMLOCK, XK_Num_Lock);
FsXAddKeyMapping(FSKEY_TEN0, XK_KP_0);
FsXAddKeyMapping(FSKEY_TEN1, XK_KP_1);
FsXAddKeyMapping(FSKEY_TEN2, XK_KP_2);
FsXAddKeyMapping(FSKEY_TEN3, XK_KP_3);
FsXAddKeyMapping(FSKEY_TEN4, XK_KP_4);
FsXAddKeyMapping(FSKEY_TEN5, XK_KP_5);
FsXAddKeyMapping(FSKEY_TEN6, XK_KP_6);
FsXAddKeyMapping(FSKEY_TEN7, XK_KP_7);
FsXAddKeyMapping(FSKEY_TEN8, XK_KP_8);
FsXAddKeyMapping(FSKEY_TEN9, XK_KP_9);
FsXAddKeyMapping(FSKEY_TENDOT, XK_KP_Decimal);
FsXAddKeyMapping(FSKEY_TENSLASH, XK_KP_Divide);
FsXAddKeyMapping(FSKEY_TENSTAR, XK_KP_Multiply);
FsXAddKeyMapping(FSKEY_TENMINUS, XK_KP_Subtract);
FsXAddKeyMapping(FSKEY_TENPLUS, XK_KP_Add);
FsXAddKeyMapping(FSKEY_TENENTER, XK_KP_Enter);
FsXAddKeysymToCharMapping(XK_space, ' ');
FsXAddKeysymToCharMapping(XK_0, '0');
FsXAddKeysymToCharMapping(XK_1, '1');
FsXAddKeysymToCharMapping(XK_2, '2');
FsXAddKeysymToCharMapping(XK_3, '3');
FsXAddKeysymToCharMapping(XK_4, '4');
FsXAddKeysymToCharMapping(XK_5, '5');
FsXAddKeysymToCharMapping(XK_6, '6');
FsXAddKeysymToCharMapping(XK_7, '7');
FsXAddKeysymToCharMapping(XK_8, '8');
FsXAddKeysymToCharMapping(XK_9, '9');
FsXAddKeysymToCharMapping(XK_A, 'A');
FsXAddKeysymToCharMapping(XK_B, 'B');
FsXAddKeysymToCharMapping(XK_C, 'C');
FsXAddKeysymToCharMapping(XK_D, 'D');
FsXAddKeysymToCharMapping(XK_E, 'E');
FsXAddKeysymToCharMapping(XK_F, 'F');
FsXAddKeysymToCharMapping(XK_G, 'G');
FsXAddKeysymToCharMapping(XK_H, 'H');
FsXAddKeysymToCharMapping(XK_I, 'I');
FsXAddKeysymToCharMapping(XK_J, 'J');
FsXAddKeysymToCharMapping(XK_K, 'K');
FsXAddKeysymToCharMapping(XK_L, 'L');
FsXAddKeysymToCharMapping(XK_M, 'M');
FsXAddKeysymToCharMapping(XK_N, 'N');
FsXAddKeysymToCharMapping(XK_O, 'O');
FsXAddKeysymToCharMapping(XK_P, 'P');
FsXAddKeysymToCharMapping(XK_Q, 'Q');
FsXAddKeysymToCharMapping(XK_R, 'R');
FsXAddKeysymToCharMapping(XK_S, 'S');
FsXAddKeysymToCharMapping(XK_T, 'T');
FsXAddKeysymToCharMapping(XK_U, 'U');
FsXAddKeysymToCharMapping(XK_V, 'V');
FsXAddKeysymToCharMapping(XK_W, 'W');
FsXAddKeysymToCharMapping(XK_X, 'X');
FsXAddKeysymToCharMapping(XK_Y, 'Y');
FsXAddKeysymToCharMapping(XK_Z, 'Z');
FsXAddKeysymToCharMapping(XK_a, 'a');
FsXAddKeysymToCharMapping(XK_b, 'b');
FsXAddKeysymToCharMapping(XK_c, 'c');
FsXAddKeysymToCharMapping(XK_d, 'd');
FsXAddKeysymToCharMapping(XK_e, 'e');
FsXAddKeysymToCharMapping(XK_f, 'f');
FsXAddKeysymToCharMapping(XK_g, 'g');
FsXAddKeysymToCharMapping(XK_h, 'h');
FsXAddKeysymToCharMapping(XK_i, 'i');
FsXAddKeysymToCharMapping(XK_j, 'j');
FsXAddKeysymToCharMapping(XK_k, 'k');
FsXAddKeysymToCharMapping(XK_l, 'l');
FsXAddKeysymToCharMapping(XK_m, 'm');
FsXAddKeysymToCharMapping(XK_n, 'n');
FsXAddKeysymToCharMapping(XK_o, 'o');
FsXAddKeysymToCharMapping(XK_p, 'p');
FsXAddKeysymToCharMapping(XK_q, 'q');
FsXAddKeysymToCharMapping(XK_r, 'r');
FsXAddKeysymToCharMapping(XK_s, 's');
FsXAddKeysymToCharMapping(XK_t, 't');
FsXAddKeysymToCharMapping(XK_u, 'u');
FsXAddKeysymToCharMapping(XK_v, 'v');
FsXAddKeysymToCharMapping(XK_w, 'w');
FsXAddKeysymToCharMapping(XK_x, 'x');
FsXAddKeysymToCharMapping(XK_y, 'y');
FsXAddKeysymToCharMapping(XK_z, 'z');
FsXAddKeysymToCharMapping(XK_Escape, 0x1b);
FsXAddKeysymToCharMapping(XK_BackSpace, 0x08);
FsXAddKeysymToCharMapping(XK_Tab, '\t');
FsXAddKeysymToCharMapping(XK_Return, '\n');
FsXAddKeysymToCharMapping(XK_grave, '`');
FsXAddKeysymToCharMapping(XK_asciitilde, '~');
FsXAddKeysymToCharMapping(XK_exclam, '!');
FsXAddKeysymToCharMapping(XK_at, '@');
FsXAddKeysymToCharMapping(XK_numbersign, '#');
FsXAddKeysymToCharMapping(XK_dollar, '$');
FsXAddKeysymToCharMapping(XK_percent, '%');
FsXAddKeysymToCharMapping(XK_asciicircum, '^');
FsXAddKeysymToCharMapping(XK_ampersand, '&');
FsXAddKeysymToCharMapping(XK_asterisk, '*');
FsXAddKeysymToCharMapping(XK_parenleft, '(');
FsXAddKeysymToCharMapping(XK_parenright, ')');
FsXAddKeysymToCharMapping(XK_minus, '-');
FsXAddKeysymToCharMapping(XK_underscore, '_');
FsXAddKeysymToCharMapping(XK_equal, '=');
FsXAddKeysymToCharMapping(XK_plus, '+');
FsXAddKeysymToCharMapping(XK_bracketleft, '[');
FsXAddKeysymToCharMapping(XK_braceleft, '{');
FsXAddKeysymToCharMapping(XK_bracketright, ']');
FsXAddKeysymToCharMapping(XK_braceright, '}');
FsXAddKeysymToCharMapping(XK_backslash, '\\');
FsXAddKeysymToCharMapping(XK_bar, '|');
FsXAddKeysymToCharMapping(XK_semicolon, ';');
FsXAddKeysymToCharMapping(XK_colon, ';');
FsXAddKeysymToCharMapping(XK_apostrophe, '\'');
FsXAddKeysymToCharMapping(XK_quotedbl, '\"');
FsXAddKeysymToCharMapping(XK_comma, ',');
FsXAddKeysymToCharMapping(XK_less, '<');
FsXAddKeysymToCharMapping(XK_period, '.');
FsXAddKeysymToCharMapping(XK_greater, '>');
FsXAddKeysymToCharMapping(XK_slash, '/');
FsXAddKeysymToCharMapping(XK_question, '?');
FsXAddKeysymToCharMapping(XK_KP_0, '0');
FsXAddKeysymToCharMapping(XK_KP_1, '1');
FsXAddKeysymToCharMapping(XK_KP_2, '2');
FsXAddKeysymToCharMapping(XK_KP_3, '3');
FsXAddKeysymToCharMapping(XK_KP_4, '4');
FsXAddKeysymToCharMapping(XK_KP_5, '5');
FsXAddKeysymToCharMapping(XK_KP_6, '6');
FsXAddKeysymToCharMapping(XK_KP_7, '7');
FsXAddKeysymToCharMapping(XK_KP_8, '8');
FsXAddKeysymToCharMapping(XK_KP_9, '9');
FsXAddKeysymToCharMapping(XK_KP_Decimal, '.');
FsXAddKeysymToCharMapping(XK_KP_Divide, '/');
FsXAddKeysymToCharMapping(XK_KP_Multiply, '*');
FsXAddKeysymToCharMapping(XK_KP_Subtract, '-');
FsXAddKeysymToCharMapping(XK_KP_Add, '+');
FsXAddKeysymToCharMapping(XK_KP_Enter, '\n');
}
int FsXKeySymToFskey(int keysym)
{
if(0<=keysym && keysym<FS_NUM_XK)
{
return mapXKtoFSKEY[keysym];
}
return 0;
}
char FsXKeySymToChar(int keysym)
{
if(0<=keysym && keysym<FS_NUM_XK)
{
return mapXKtoChar[keysym];
}
return 0;
}
int FsXFskeyToKeySym(int fskey)
{
if(0<=fskey && fskey<FSKEY_NUM_KEYCODE)
{
return mapFSKEYtoXK[fskey];
}
return 0;
}
/* ////////////////////////////////////////////////////////////
File Name: fssimplewindowcommon.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#include <stdio.h>
#include <string.h>
#include "fssimplewindow.h"
FsOpenWindowOption::FsOpenWindowOption()
{
x0=16;
y0=16;
wid=800;
hei=600;
windowTitle="Main Window";
useDoubleBuffer=false;
useMultiSampleBuffer=false;
sizeOpt=NORMAL_WINDOW;
}
void FsOpenWindow(int x0,int y0,int wid,int hei,int useDoubleBuffer)
{
FsOpenWindow(x0,y0,wid,hei,useDoubleBuffer,NULL);
}
void FsOpenWindow(int x0,int y0,int wid,int hei,int useDoubleBuffer,const char windowName[])
{
FsOpenWindowOption opt;
opt.x0=x0;
opt.y0=y0;
opt.wid=wid;
opt.hei=hei;
opt.windowTitle=windowName;
opt.useDoubleBuffer=(bool)useDoubleBuffer;
FsOpenWindow(opt);
}
void FsClearEventQueue(void)
{
auto intervalFunc=fsIntervalCallBack;
auto intervalParam=fsIntervalCallBackParameter;
FsRegisterIntervalCallBack(NULL,NULL);
for(;;)
{
int checkAgain=0;
FsPollDevice();
int lb,mb,rb,mx,my;
while(FSMOUSEEVENT_NONE!=FsGetMouseEvent(lb,mb,rb,mx,my) ||
FSKEY_NULL!=FsInkey() ||
0!=FsInkeyChar() ||
0!=FsCheckWindowExposure())
{
checkAgain=1;
}
if(0!=lb || 0!=rb || 0!=mb)
{
checkAgain=1;
}
if(0!=FsCheckKeyHeldDown())
{
checkAgain=1;
}
if(0==checkAgain)
{
break;
}
FsSleep(50);
}
FsRegisterIntervalCallBack(intervalFunc,intervalParam);
}
int FsCheckKeyHeldDown(void)
{
int keyCode;
for(keyCode=FSKEY_NULL+1; keyCode<FSKEY_NUM_KEYCODE; keyCode++)
{
if(0!=FsGetKeyState(keyCode))
{
return 1;
}
}
return 0;
}
static const char *const keyCodeToStr[]=
{
"NULL",
"SPACE",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"ESC",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"PRINTSCRN",
"CAPSLOCK",
"SCROLLLOCK",
"PAUSEBREAK",
"BS",
"TAB",
"ENTER",
"SHIFT",
"CTRL",
"ALT",
"INS",
"DEL",
"HOME",
"END",
"PAGEUP",
"PAGEDOWN",
"UP",
"DOWN",
"LEFT",
"RIGHT",
"NUMLOCK",
"TILDA",
"MINUS",
"PLUS",
"LBRACKET",
"RBRACKET",
"BACKSLASH",
"SEMICOLON",
"SINGLEQUOTE",
"COMMA",
"DOT",
"SLASH",
"TEN0",
"TEN1",
"TEN2",
"TEN3",
"TEN4",
"TEN5",
"TEN6",
"TEN7",
"TEN8",
"TEN9",
"TENDOT",
"TENSLASH",
"TENSTAR",
"TENMINUS",
"TENPLUS",
"TENENTER",
"WHEELUP",
"WHEELDOWN",
"CONTEXT",
"HENKAN",
"MUHENKAN",
"KANA", // Japanese JIS Keyboard Only => Win32 VK_KANA
"LEFT_CTRL",
"RIGHT_CTRL",
"LEFT_SHIFT",
"RIGHT_SHIFT",
"LEFT_ALT",
"RIGHT_ALT",
};
const char *FsKeyCodeToString(int keyCode)
{
if(0<=keyCode && keyCode<FSKEY_NUM_KEYCODE)
{
return keyCodeToStr[keyCode];
}
return "(Undefined keycode)";
}
int FsStringToKeyCode(const char str[])
{
if(nullptr==str)
{
return FSKEY_NULL;
}
char upper[256];
for(int i=0; i<255 && 0!=str[i]; ++i)
{
upper[i ]=str[i];
upper[i+1]=0;
if('a'<=upper[i] && upper[i]<='z')
{
upper[i]=upper[i]+'A'-'a';
}
}
for(int i=0; i<FSKEY_NUM_KEYCODE; ++i)
{
if(0==strcmp(upper,keyCodeToStr[i]))
{
return i;
}
}
return FSKEY_NULL;
}
void *fsCloseWindowCallBackParam=NULL;
bool (*fsCloseWindowCallBack)(void *param)=NULL;
void *fsOpenGLContextCreationCallBackParam=NULL;
bool (*fsOpenGLContextCreationCallBack)(void *param)=NULL;
void *fsAfterWindowCreationCallBackParam=NULL;
void (*fsAfterWindowCreationCallBack)(void *param)=NULL;
void *fsOpenGLInitializationCallBackParam=NULL;
bool (*fsOpenGLInitializationCallBack)(void *param)=NULL;
void *fsSwapBuffersHookParam=NULL;
bool (*fsSwapBuffersHook)(void *param)=NULL;
void *fsOnPaintCallbackParam=NULL;
void (*fsOnPaintCallback)(void *param)=NULL;
void *fsOnResizeCallBackParam=NULL;
void (*fsOnResizeCallBack)(void *param,int wid,int hei)=NULL;
void (*fsIntervalCallBack)(void *)=NULL;
void *fsIntervalCallBackParameter=NULL;
void (*fsPollDeviceHook)(void *)=NULL;
void *fsPollDeviceHookParam=NULL;
void FsRegisterCloseWindowCallBack(bool (*callback)(void *),void *param)
{
fsCloseWindowCallBack=callback;
fsCloseWindowCallBackParam=param;
}
void FsRegisterBeforeOpenGLContextCreationCallBack(bool (*callback)(void *),void *param)
{
fsOpenGLContextCreationCallBack=callback;
fsOpenGLContextCreationCallBackParam=param;
}
void FsRegisterAfterWindowCreationCallBack(void (*callback)(void *),void *param)
{
fsAfterWindowCreationCallBackParam=param;
fsAfterWindowCreationCallBack=callback;
}
void FsRegisterOpenGLInitializationCallBack(bool (*callback)(void *),void *param)
{
fsOpenGLInitializationCallBack=callback;
fsOpenGLInitializationCallBackParam=param;
}
void FsRegisterSwapBuffersCallBack(bool (*callback)(void *),void *param)
{
fsSwapBuffersHookParam=param;
fsSwapBuffersHook=callback;
}
void FsRegisterOnPaintCallBack(void (*callback)(void *),void *param)
{
fsOnPaintCallbackParam=param;
fsOnPaintCallback=callback;
}
void FsRegisterWindowResizeCallBack(void (*callback)(void *,int wid,int hei),void *param)
{
fsOnResizeCallBackParam=param;
fsOnResizeCallBack=callback;
}
void FsRegisterIntervalCallBack(void (*callback)(void *),void *param)
{
fsIntervalCallBack=callback;
fsIntervalCallBackParameter=param;
}
void FsRegisterPollDeviceCallBack(void (*callback)(void *),void *param)
{
fsPollDeviceHook=callback;
fsPollDeviceHookParam=param;
}
| 25.799391
| 194
| 0.637768
|
lord-pradhan
|
7c88af4a689a965a5621c9c1050e8228c0189ed9
| 8,154
|
cpp
|
C++
|
Examples/DocsExamples/source/Programming with Documents/Split Documents/Split into html pages.cpp
|
btolfa/Aspose.Words-for-C
|
f75c77380b75546907ee63b96590f5250d2ffa90
|
[
"MIT"
] | 32
|
2018-08-23T07:48:20.000Z
|
2021-12-24T07:27:02.000Z
|
Examples/DocsExamples/source/Programming with Documents/Split Documents/Split into html pages.cpp
|
btolfa/Aspose.Words-for-C
|
f75c77380b75546907ee63b96590f5250d2ffa90
|
[
"MIT"
] | 1
|
2021-11-23T03:35:31.000Z
|
2022-01-26T09:19:44.000Z
|
Examples/DocsExamples/source/Programming with Documents/Split Documents/Split into html pages.cpp
|
btolfa/Aspose.Words-for-C
|
f75c77380b75546907ee63b96590f5250d2ffa90
|
[
"MIT"
] | 13
|
2018-07-31T05:02:33.000Z
|
2022-03-06T22:12:36.000Z
|
#include "Split into html pages.h"
#include <Aspose.Words.Cpp/Body.h>
#include <Aspose.Words.Cpp/BreakType.h>
#include <Aspose.Words.Cpp/Fields/Field.h>
#include <Aspose.Words.Cpp/ImportFormatMode.h>
#include <Aspose.Words.Cpp/MailMerging/MailMerge.h>
#include <Aspose.Words.Cpp/Node.h>
#include <Aspose.Words.Cpp/NodeCollection.h>
#include <Aspose.Words.Cpp/NodeType.h>
#include <Aspose.Words.Cpp/ParagraphFormat.h>
#include <Aspose.Words.Cpp/Properties/BuiltInDocumentProperties.h>
#include <Aspose.Words.Cpp/Saving/ExportHeadersFootersMode.h>
#include <Aspose.Words.Cpp/Saving/HtmlSaveOptions.h>
#include <Aspose.Words.Cpp/Saving/SaveOutputParameters.h>
#include <Aspose.Words.Cpp/SectionCollection.h>
#include <Aspose.Words.Cpp/StyleIdentifier.h>
#include <system/char.h>
#include <system/enumerator_adapter.h>
#include <system/exceptions.h>
#include <system/text/string_builder.h>
#include "Programming with Documents/Split Documents/Split into html pages.h"
using namespace Aspose::Words;
using namespace Aspose::Words::MailMerging;
using namespace Aspose::Words::Saving;
namespace DocsExamples { namespace Programming_with_Documents { namespace Split_Documents {
void WordToHtmlConverter::HandleTocMergeField::FieldMerging(System::SharedPtr<FieldMergingArgs> e)
{
if (mBuilder == nullptr)
{
mBuilder = System::MakeObject<DocumentBuilder>(e->get_Document());
}
// Our custom data source returns topic objects.
auto topic = System::StaticCast<Topic>(e->get_FieldValue());
mBuilder->MoveToMergeField(e->get_FieldName());
mBuilder->InsertHyperlink(topic->get_Title(), topic->get_FileName(), false);
// Signal to the mail merge engine that it does not need to insert text into the field.
e->set_Text(u"");
}
void WordToHtmlConverter::HandleTocMergeField::ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args)
{
// Do nothing.
}
void WordToHtmlConverter::Execute(System::String srcFileName, System::String tocTemplate, System::String dstDir)
{
mDoc = System::MakeObject<Document>(srcFileName);
mTocTemplate = tocTemplate;
mDstDir = dstDir;
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> topicStartParas = SelectTopicStarts();
InsertSectionBreaks(topicStartParas);
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> topics = SaveHtmlTopics();
SaveTableOfContents(topics);
}
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> WordToHtmlConverter::SelectTopicStarts()
{
System::SharedPtr<NodeCollection> paras = mDoc->GetChildNodes(NodeType::Paragraph, true);
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> topicStartParas =
System::MakeObject<System::Collections::Generic::List<System::SharedPtr<Paragraph>>>();
for (const auto& para : System::IterateOver<Paragraph>(paras))
{
StyleIdentifier style = para->get_ParagraphFormat()->get_StyleIdentifier();
if (style == StyleIdentifier::Heading1)
{
topicStartParas->Add(para);
}
}
return topicStartParas;
}
void WordToHtmlConverter::InsertSectionBreaks(System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Paragraph>>> topicStartParas)
{
auto builder = System::MakeObject<DocumentBuilder>(mDoc);
for (const auto& para : topicStartParas)
{
System::SharedPtr<Section> section = para->get_ParentSection();
// Insert section break if the paragraph is not at the beginning of a section already.
if (para != section->get_Body()->get_FirstParagraph())
{
builder->MoveTo(para->get_FirstChild());
builder->InsertBreak(BreakType::SectionBreakNewPage);
// This is the paragraph that was inserted at the end of the now old section.
// We don't really need the extra paragraph, we just needed the section.
section->get_Body()->get_LastParagraph()->Remove();
}
}
}
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> WordToHtmlConverter::SaveHtmlTopics()
{
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> topics =
System::MakeObject<System::Collections::Generic::List<System::SharedPtr<Topic>>>();
for (int32_t sectionIdx = 0; sectionIdx < mDoc->get_Sections()->get_Count(); sectionIdx++)
{
System::SharedPtr<Section> section = mDoc->get_Sections()->idx_get(sectionIdx);
System::String paraText = section->get_Body()->get_FirstParagraph()->GetText();
// Use the text of the heading paragraph to generate the HTML file name.
System::String fileName = MakeTopicFileName(paraText);
if (fileName == u"")
{
fileName = System::String(u"UNTITLED SECTION ") + sectionIdx;
}
fileName = System::IO::Path::Combine(mDstDir, fileName + u".html");
// Use the text of the heading paragraph to generate the title for the TOC.
System::String title = MakeTopicTitle(paraText);
if (title == u"")
{
title = System::String(u"UNTITLED SECTION ") + sectionIdx;
}
auto topic = System::MakeObject<Topic>(title, fileName);
topics->Add(topic);
SaveHtmlTopic(section, topic);
}
return topics;
}
System::String WordToHtmlConverter::MakeTopicFileName(System::String paraText)
{
auto b = System::MakeObject<System::Text::StringBuilder>();
for (char16_t c : paraText)
{
if (System::Char::IsLetterOrDigit(c))
{
b->Append(c);
}
else if (c == u' ')
{
b->Append(u'_');
}
}
return b->ToString();
}
System::String WordToHtmlConverter::MakeTopicTitle(System::String paraText)
{
return paraText.Substring(0, paraText.get_Length() - 1);
}
void WordToHtmlConverter::SaveHtmlTopic(System::SharedPtr<Section> section, System::SharedPtr<Topic> topic)
{
auto dummyDoc = System::MakeObject<Document>();
dummyDoc->RemoveAllChildren();
dummyDoc->AppendChild(dummyDoc->ImportNode(section, true, ImportFormatMode::KeepSourceFormatting));
dummyDoc->get_BuiltInDocumentProperties()->set_Title(topic->get_Title());
auto saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_PrettyFormat(true);
saveOptions->set_AllowNegativeIndent(true);
saveOptions->set_ExportHeadersFootersMode(ExportHeadersFootersMode::None);
dummyDoc->Save(topic->get_FileName(), saveOptions);
}
void WordToHtmlConverter::SaveTableOfContents(System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Topic>>> topics)
{
auto tocDoc = System::MakeObject<Document>(mTocTemplate);
// We use a custom mail merge event handler defined below,
// and a custom mail merge data source based on collecting the topics we created.
tocDoc->get_MailMerge()->set_FieldMergingCallback(System::MakeObject<WordToHtmlConverter::HandleTocMergeField>());
tocDoc->get_MailMerge()->ExecuteWithRegions(System::MakeObject<TocMailMergeDataSource>(topics));
tocDoc->Save(System::IO::Path::Combine(mDstDir, u"contents.html"));
}
namespace gtest_test {
class SplitIntoHtmlPages : public ::testing::Test
{
protected:
static System::SharedPtr<::DocsExamples::Programming_with_Documents::Split_Documents::SplitIntoHtmlPages> s_instance;
void SetUp() override
{
s_instance->SetUp();
};
static void SetUpTestCase()
{
s_instance = System::MakeObject<::DocsExamples::Programming_with_Documents::Split_Documents::SplitIntoHtmlPages>();
s_instance->OneTimeSetUp();
};
static void TearDownTestCase()
{
s_instance->OneTimeTearDown();
s_instance = nullptr;
};
};
System::SharedPtr<::DocsExamples::Programming_with_Documents::Split_Documents::SplitIntoHtmlPages> SplitIntoHtmlPages::s_instance;
TEST_F(SplitIntoHtmlPages, HtmlPages)
{
s_instance->HtmlPages();
}
} // namespace gtest_test
}}} // namespace DocsExamples::Programming_with_Documents::Split_Documents
| 36.565022
| 146
| 0.712288
|
btolfa
|
7c88e4be17f38025a56f8f702c0f8fd535de93b8
| 1,839
|
cpp
|
C++
|
devmand/gateway/src/devmand/channels/cli/datastore/Datastore.cpp
|
gurrapualt/magma
|
13e05788fa6c40293a58b6e03cfb394bb79fa98f
|
[
"BSD-3-Clause"
] | 2
|
2020-12-09T11:42:30.000Z
|
2021-09-26T03:28:33.000Z
|
devmand/gateway/src/devmand/channels/cli/datastore/Datastore.cpp
|
gurrapualt/magma
|
13e05788fa6c40293a58b6e03cfb394bb79fa98f
|
[
"BSD-3-Clause"
] | 124
|
2020-08-21T06:11:21.000Z
|
2022-03-21T05:25:26.000Z
|
devmand/gateway/src/devmand/channels/cli/datastore/Datastore.cpp
|
yogi8091/magma
|
edc3b249068ad871047e898c912f3228ee9f2c88
|
[
"BSD-3-Clause"
] | 1
|
2020-09-21T04:25:06.000Z
|
2020-09-21T04:25:06.000Z
|
/*
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
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 <devmand/channels/cli/datastore/Datastore.h>
#include <devmand/channels/cli/engine/Engine.h>
#include <devmand/devices/cli/schema/Model.h>
namespace devmand::channels::cli::datastore {
using devmand::channels::cli::Engine;
using devmand::channels::cli::datastore::DatastoreException;
using devmand::devices::cli::SchemaContext;
using std::make_unique;
Datastore::Datastore(DatastoreType type, SchemaContext& _schemaContext)
: schemaContext(_schemaContext) {
llly_ctx* pLyCtx = schemaContext.getLyContext();
datastoreState = make_shared<DatastoreState>(pLyCtx, type);
}
unique_ptr<DatastoreTransaction> Datastore::newTx() {
unique_lock<mutex> lock(_mutex);
checkIfTransactionRunning();
setTransactionRunning();
return make_unique<DatastoreTransaction>(datastoreState, schemaContext);
}
void Datastore::checkIfTransactionRunning() {
if (datastoreState->transactionUnderway) {
DatastoreException ex(
"Transaction in datastore already running, only 1 at a time permitted");
MLOG(MWARNING) << ex.what();
throw ex;
}
}
void Datastore::setTransactionRunning() {
datastoreState->transactionUnderway.store(true);
}
DatastoreType Datastore::operational() {
return DatastoreType::operational;
}
DatastoreType Datastore::config() {
return DatastoreType::config;
}
} // namespace devmand::channels::cli::datastore
| 31.169492
| 80
| 0.777053
|
gurrapualt
|
7c899c2446dad17bae3be6e34fcf3c0507512781
| 204
|
cpp
|
C++
|
modules/core/perf/perf_main.cpp
|
snosov1/opencv
|
ce05d6cb89450a5778f4c0169b5da5589798192a
|
[
"BSD-3-Clause"
] | 144
|
2015-01-15T03:38:44.000Z
|
2022-02-17T09:07:52.000Z
|
modules/core/perf/perf_main.cpp
|
snosov1/opencv
|
ce05d6cb89450a5778f4c0169b5da5589798192a
|
[
"BSD-3-Clause"
] | 28
|
2016-10-16T19:42:37.000Z
|
2018-09-14T21:29:48.000Z
|
modules/core/perf/perf_main.cpp
|
snosov1/opencv
|
ce05d6cb89450a5778f4c0169b5da5589798192a
|
[
"BSD-3-Clause"
] | 58
|
2015-01-14T23:43:49.000Z
|
2021-11-15T05:19:08.000Z
|
#include "perf_precomp.hpp"
#ifdef _MSC_VER
# if _MSC_VER >= 1700
# pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
# endif
#endif
CV_PERF_TEST_MAIN(core)
| 22.666667
| 97
| 0.769608
|
snosov1
|
7c8bd80dcf97df51bd3ba2e6dea94e5878938ebb
| 1,301
|
hpp
|
C++
|
Firmware/graphics/gs_event_dispatcher.hpp
|
ValentiWorkLearning/GradWork
|
70bb5a629df056a559bae3694b47a2e5dc98c23b
|
[
"MIT"
] | 39
|
2019-10-23T12:06:16.000Z
|
2022-01-26T04:28:29.000Z
|
Firmware/graphics/gs_event_dispatcher.hpp
|
ValentiWorkLearning/GradWork
|
70bb5a629df056a559bae3694b47a2e5dc98c23b
|
[
"MIT"
] | 20
|
2020-03-21T20:21:46.000Z
|
2021-11-19T14:34:03.000Z
|
Firmware/graphics/gs_event_dispatcher.hpp
|
ValentiWorkLearning/GradWork
|
70bb5a629df056a559bae3694b47a2e5dc98c23b
|
[
"MIT"
] | 7
|
2019-10-18T09:44:10.000Z
|
2021-06-11T13:05:16.000Z
|
#pragma once
#include "ih/gs_events.hpp"
#include "utils/Noncopyable.hpp"
#include <any>
#include <atomic>
#include <functional>
#include <memory>
#include <vector>
#include <etl/queue_spsc_atomic.h>
#include <etl/vector.h>
namespace Graphics::Events
{
class EventDispatcher : private Utils::noncopyable
{
public:
using TEventHandler = std::function<void(const TEvent&)>;
static constexpr inline int MaxSubscriberLimit = 3;
using SubscriberStorage = etl::vector<TEventHandler, MaxSubscriberLimit>;
void subscribe(EventGroup _eventGroup, const TEventHandler& _handler) noexcept;
void postEvent(TEvent&& _eventToProcess) noexcept;
void processEventQueue() noexcept;
private:
static constexpr inline int EventsCount =
Events::enumConvert<EventGroup>(EventGroup::EventGroupEnd);
static constexpr inline int EventPoolSize = 16;
using TEventsMap = etl::vector<std::pair<EventGroup, SubscriberStorage>, EventsCount>;
TEventsMap m_eventsMap;
using TEventsQueue =
etl::queue_spsc_atomic<TEvent, EventPoolSize, etl::memory_model::MEMORY_MODEL_SMALL>;
TEventsQueue m_eventsQueue;
};
using TEventDispatcherPtr = std::unique_ptr<EventDispatcher>;
TEventDispatcherPtr createEventDispatcher() noexcept;
} // namespace Graphics::Events
| 25.019231
| 93
| 0.757879
|
ValentiWorkLearning
|
7c8f5df5442113163ba49a41d021f26edd928d35
| 3,421
|
cpp
|
C++
|
DeviceConfig.cpp
|
bhardwajRahul/gpuPlotGenerator
|
ad90dc34a648382898abfa81017bc853ac022ca9
|
[
"BSD-2-Clause-FreeBSD"
] | 57
|
2015-02-13T12:26:01.000Z
|
2022-03-29T17:57:26.000Z
|
DeviceConfig.cpp
|
bhardwajRahul/gpuPlotGenerator
|
ad90dc34a648382898abfa81017bc853ac022ca9
|
[
"BSD-2-Clause-FreeBSD"
] | 47
|
2016-10-18T14:41:17.000Z
|
2020-12-11T07:53:47.000Z
|
DeviceConfig.cpp
|
daveahartley/BurstGPUPlotter
|
cd72747825307c5724c540bd7209055fc1161ef7
|
[
"BSD-2-Clause-FreeBSD"
] | 34
|
2015-06-27T07:29:11.000Z
|
2022-03-25T05:20:57.000Z
|
/*
GPU plot generator for Burst coin.
Author: Cryo
Bitcoin: 138gMBhCrNkbaiTCmUhP9HLU9xwn5QKZgD
Burst: BURST-YA29-QCEW-QXC3-BKXDL
Based on the code of the official miner and dcct's plotgen.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <stdexcept>
#include <algorithm>
#include <memory>
#include "util.h"
#include "DeviceConfig.h"
namespace cryo {
namespace gpuPlotGenerator {
DeviceConfig::DeviceConfig(std::size_t p_platform, std::size_t p_device, std::size_t p_globalWorkSize, std::size_t p_localWorkSize, unsigned int p_hashesNumber) throw (std::exception)
: m_platform(p_platform), m_device(p_device), m_globalWorkSize(p_globalWorkSize), m_localWorkSize(p_localWorkSize), m_hashesNumber(p_hashesNumber) {
}
DeviceConfig::DeviceConfig(const DeviceConfig& p_other)
: m_platform(p_other.m_platform), m_device(p_other.m_device), m_globalWorkSize(p_other.m_globalWorkSize), m_localWorkSize(p_other.m_localWorkSize), m_hashesNumber(p_other.m_hashesNumber) {
}
DeviceConfig::~DeviceConfig() throw () {
}
DeviceConfig& DeviceConfig::operator=(const DeviceConfig& p_other) {
m_platform = p_other.m_platform;
m_device = p_other.m_device;
m_globalWorkSize = p_other.m_globalWorkSize;
m_localWorkSize = p_other.m_localWorkSize;
m_hashesNumber = p_other.m_hashesNumber;
return *this;
}
void DeviceConfig::normalize() throw (std::exception) {
if(m_localWorkSize > m_globalWorkSize) {
m_localWorkSize = m_globalWorkSize;
}
if(m_globalWorkSize % m_localWorkSize != 0) {
m_localWorkSize = std::max((std::size_t)1, m_localWorkSize - m_globalWorkSize % m_localWorkSize);
}
if(m_hashesNumber == 0) {
m_hashesNumber = 1;
} else if(m_hashesNumber > PLOT_SIZE / HASH_SIZE) {
m_hashesNumber = PLOT_SIZE / HASH_SIZE;
}
}
std::vector<std::shared_ptr<DeviceConfig>> DeviceConfig::loadFromFile(const std::string& p_path) throw (std::exception) {
std::vector<std::shared_ptr<DeviceConfig>> configs;
std::ifstream file(p_path, std::ios::in);
if(!file) {
throw std::runtime_error("Unable to open config file");
}
std::unique_ptr<char[]> buf(new char[256]);
for(unsigned int i = 0 ; file.getline(buf.get(), 256) ; ++i) {
std::vector<std::string> parts(cryo::util::split(buf.get(), " "));
if(parts.size() != 5) {
std::ostringstream message;
message << "Invalid parameters count at line [" << i << "]";
throw std::runtime_error(message.str());
}
unsigned int platform = std::atol(parts[0].c_str());
unsigned int device = std::atol(parts[1].c_str());
std::size_t globalWorkSize = std::atol(parts[2].c_str());
std::size_t localWorkSize = std::atol(parts[3].c_str());
unsigned int hashesNumber = std::atol(parts[4].c_str());
configs.push_back(std::shared_ptr<DeviceConfig>(new DeviceConfig(platform, device, globalWorkSize, localWorkSize, hashesNumber)));
}
return configs;
}
void DeviceConfig::storeToFile(const std::string& p_path, const std::vector<std::shared_ptr<DeviceConfig>>& p_configs) throw (std::exception) {
std::ofstream file(p_path, std::ios::out | std::ios::trunc);
if(!file) {
throw std::runtime_error("Unable to open config file");
}
for(const std::shared_ptr<DeviceConfig>& config : p_configs) {
file << config->getPlatform() << " ";
file << config->getDevice() << " ";
file << config->getGlobalWorkSize() << " ";
file << config->getLocalWorkSize() << " ";
file << config->getHashesNumber() << std::endl;
}
}
}}
| 32.580952
| 188
| 0.72698
|
bhardwajRahul
|
7c9813af5df1b41786b3ff28fb0a636d6d50dc11
| 1,742
|
hpp
|
C++
|
src/game/Particule.hpp
|
ArthurSonzogni/InTheCube
|
c4a35096d962d23f6211802970ee44f77d29e38a
|
[
"MIT"
] | 4
|
2019-12-31T07:58:54.000Z
|
2021-09-07T18:16:51.000Z
|
src/game/Particule.hpp
|
ArthurSonzogni/InTheCube
|
c4a35096d962d23f6211802970ee44f77d29e38a
|
[
"MIT"
] | null | null | null |
src/game/Particule.hpp
|
ArthurSonzogni/InTheCube
|
c4a35096d962d23f6211802970ee44f77d29e38a
|
[
"MIT"
] | 2
|
2020-02-17T12:47:33.000Z
|
2021-09-07T18:16:52.000Z
|
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef GAME_PARTICULE_HPP
#define GAME_PARTICULE_HPP
#include <smk/Sprite.hpp>
#include "game/Hero.hpp"
class window;
class Particule {
public:
smk::Sprite sprite;
bool (*transform)(Particule*);
float xspeed, yspeed;
float x, y;
float alpha;
int t;
Particule(bool (*stepF)(Particule*));
bool Step();
void Draw(smk::Window& window);
};
// particules fonctions
Particule essai();
bool essaiStep(Particule* p);
// fire
Particule fireParticule(int x, int y);
bool fireParticuleStep(Particule* p);
// laser on hero Particule
Particule particuleLaserOnHero(int x, int y, int xstart, int ystart);
bool particuleLaserOnHeroStep(Particule* p);
// laser on glass Particule
Particule particuleLaserOnGlass(int x, int y, int xstart, int ystart);
bool particuleLaserOnGlassStep(Particule* p);
// creeper explosion
Particule particuleCreeperExplosion(int x, int y);
bool particuleCreeperExplosionStep(Particule* p);
// cloneur
Particule particuleCloneur(int x, int y);
bool particuleCloneurStep(Particule* p);
// arrowTrace
Particule particuleArrow(int x, int y);
bool particuleArrowStep(Particule* p);
// wind
Particule particuleWind(int x, int y);
bool particuleWindStep(Particule* p);
// deadParticule
Particule particuleDead(int x, int y);
bool particuleDeadStep(Particule* p);
// arbreBossParticule
Particule arbreBossParticule(int x, int y, glm::vec4 c);
bool arbreBossParticuleStep(Particule* p);
// acc
Particule accParticule(int x, int y, float xspeed, int t);
bool accParticuleStep(Particule* p);
float square(float x);
#endif /* GAME_PARTICULE_HPP */
| 23.540541
| 78
| 0.756602
|
ArthurSonzogni
|
7c98c76c83e4a124a0b925c319a6023e5794f82f
| 8,117
|
cpp
|
C++
|
enma_pe/pe_debug.cpp
|
wjcsharp/enma_pe
|
6da64a80a611a25cdba181179e5724d971a633a8
|
[
"BSD-3-Clause"
] | 1
|
2019-04-26T07:18:15.000Z
|
2019-04-26T07:18:15.000Z
|
enma_pe/pe_debug.cpp
|
frustreated/enma_pe
|
6da64a80a611a25cdba181179e5724d971a633a8
|
[
"BSD-3-Clause"
] | null | null | null |
enma_pe/pe_debug.cpp
|
frustreated/enma_pe
|
6da64a80a611a25cdba181179e5724d971a633a8
|
[
"BSD-3-Clause"
] | 1
|
2020-07-09T03:20:02.000Z
|
2020-07-09T03:20:02.000Z
|
#include "stdafx.h"
#include "pe_debug.h"
debug_item::debug_item() {
this->characteristics = 0;
this->timestamp = 0;
this->major_version = 0;
this->minor_version = 0;
this->type = 0;
this->size_of_data = 0;
this->address_of_raw_data = 0;
this->pointer_to_raw_data = 0;
}
debug_item::debug_item(const debug_item& item) {
this->operator=(item);
}
debug_item::debug_item(uint32_t characteristics, uint32_t timestamp, uint16_t major_version, uint16_t minor_version,
uint32_t type, uint32_t size_of_data, uint32_t address_of_raw_data, uint32_t pointer_to_raw_data,
void * data) {
this->characteristics = characteristics;
this->timestamp = timestamp;
this->major_version = major_version;
this->minor_version = minor_version;
this->type = type;
this->size_of_data = size_of_data;
this->address_of_raw_data = address_of_raw_data;
this->pointer_to_raw_data = pointer_to_raw_data;
item_data.resize(this->size_of_data);
memcpy(item_data.data(), data, this->size_of_data);
}
debug_item::~debug_item() {
}
debug_item& debug_item::operator=(const debug_item& item) {
this->characteristics = item.characteristics;
this->timestamp = item.timestamp;
this->major_version = item.major_version;
this->minor_version = item.minor_version;
this->type = item.type;
this->size_of_data = item.size_of_data;
this->address_of_raw_data = item.address_of_raw_data;
this->pointer_to_raw_data = item.pointer_to_raw_data;
this->item_data = item.item_data;
return *this;
}
void debug_item::set_characteristics(uint32_t characteristics) {
this->characteristics = characteristics;
}
void debug_item::set_timestamp(uint32_t timestamp) {
this->timestamp = timestamp;
}
void debug_item::set_major_version(uint16_t major_version){
this->major_version = major_version;
}
void debug_item::set_minor_version(uint16_t minor_version) {
this->minor_version = minor_version;
}
void debug_item::set_type(uint32_t type) {
this->type = type;
}
void debug_item::set_size_of_data(uint32_t size_of_data) {
this->size_of_data = size_of_data;
}
void debug_item::set_address_of_raw_data(uint32_t address_of_raw_data) {
this->address_of_raw_data = address_of_raw_data;
}
void debug_item::set_pointer_to_raw_data(uint32_t pointer_to_raw_data) {
this->pointer_to_raw_data = pointer_to_raw_data;
}
uint32_t debug_item::get_characteristics() const {
return this->characteristics;
}
uint32_t debug_item::get_timestamp() const {
return this->timestamp;
}
uint16_t debug_item::get_major_version() const{
return this->major_version;
}
uint16_t debug_item::get_minor_version() const {
return this->minor_version;
}
uint32_t debug_item::get_type() const {
return this->type;
}
uint32_t debug_item::get_size_of_data() const {
return this->size_of_data;
}
uint32_t debug_item::get_address_of_raw_data() const {
return this->address_of_raw_data;
}
uint32_t debug_item::get_pointer_to_raw_data() const {
return this->pointer_to_raw_data;
}
const std::vector<uint8_t>& debug_item::get_item_data() const {
return this->item_data;
}
std::vector<uint8_t>& debug_item::get_item_data() {
return this->item_data;
}
debug_table::debug_table() {
}
debug_table::debug_table(const debug_table& debug) {
this->operator=(debug);
}
debug_table::~debug_table() {
}
debug_table& debug_table::operator=(const debug_table& debug) {
this->items = debug.items;
return *this;
}
void debug_table::add_item(const debug_item& item) {
items.push_back(item);
}
void debug_table::clear() {
this->items.clear();
}
size_t debug_table::size() const {
return items.size();
}
const std::vector<debug_item>& debug_table::get_items() const {
return items;
}
std::vector<debug_item>& debug_table::get_items() {
return items;
}
directory_code get_debug_table(const pe_image &image, debug_table& debug) {
debug.get_items().clear();
uint32_t virtual_address = image.get_directory_virtual_address(IMAGE_DIRECTORY_ENTRY_DEBUG);
uint32_t virtual_size = image.get_directory_virtual_size(IMAGE_DIRECTORY_ENTRY_DEBUG);
if (virtual_address && virtual_size) {
pe_image_io debug_io(image);
debug_io.set_image_offset(virtual_address);
while (debug_io.get_image_offset() < virtual_address + virtual_size) {
image_debug_directory debug_desc;
if (debug_io.read(&debug_desc,sizeof(debug_desc)) != enma_io_success) {
return directory_code::directory_code_currupted;
}
debug_item item;
item.set_characteristics(debug_desc.characteristics);
item.set_timestamp(debug_desc.time_date_stamp);
item.set_major_version(debug_desc.major_version);
item.set_minor_version(debug_desc.minor_version);
item.set_type(debug_desc.type);
item.set_size_of_data(debug_desc.size_of_data);
item.set_address_of_raw_data(debug_desc.address_of_raw_data);
item.set_pointer_to_raw_data(debug_desc.pointer_to_raw_data);
if (debug_desc.size_of_data && debug_desc.address_of_raw_data) {
size_t _offset_real = 0;
size_t available_size = 0;
size_t down_oversize = 0;
size_t up_oversize = 0;
debug_io.view_image(
debug_desc.address_of_raw_data, debug_desc.size_of_data,
_offset_real,
available_size, down_oversize, up_oversize
);
if (down_oversize || up_oversize) {
return directory_code::directory_code_currupted;
}
if (pe_image_io(image).set_image_offset(debug_desc.address_of_raw_data).read(
item.get_item_data(), debug_desc.size_of_data) != enma_io_success) {
return directory_code::directory_code_currupted;
}
}
debug.add_item(item);
}
return directory_code::directory_code_success;
}
return directory_code::directory_code_not_present;
}
directory_code get_placement_debug_table(const pe_image &image, pe_directory_placement& placement) {
uint32_t virtual_address = image.get_directory_virtual_address(IMAGE_DIRECTORY_ENTRY_DEBUG);
uint32_t virtual_size = image.get_directory_virtual_size(IMAGE_DIRECTORY_ENTRY_DEBUG);
if (virtual_address && virtual_size) {
pe_image_io debug_io(image);
uint32_t total_desc_size = 0;
debug_io.set_image_offset(virtual_address);
while (debug_io.get_image_offset() < virtual_address + virtual_size) {
total_desc_size += (uint32_t)sizeof(image_debug_directory);
image_debug_directory debug_desc;
if (debug_io.read(&debug_desc, sizeof(debug_desc)) != enma_io_success) {
return directory_code::directory_code_currupted;
}
if (debug_desc.size_of_data && debug_desc.address_of_raw_data) {
size_t _offset_real = 0;
size_t available_size = 0;
size_t down_oversize = 0;
size_t up_oversize = 0;
debug_io.view_image(
debug_desc.address_of_raw_data, ALIGN_UP(debug_desc.size_of_data, 0x10),
_offset_real,
available_size, down_oversize, up_oversize
);
if (down_oversize || up_oversize) {
return directory_code::directory_code_currupted;
}
placement[debug_desc.address_of_raw_data] = directory_placement(available_size, id_pe_debug_item_data, "");
}
}
placement[virtual_address] = directory_placement(ALIGN_UP(total_desc_size, 0x10), id_pe_debug_descriptor, "");
return directory_code::directory_code_success;
}
return directory_code::directory_code_not_present;
}
| 32.210317
| 126
| 0.681902
|
wjcsharp
|
7c99511af0b6cd91d4403e9bf55b979be3005c6c
| 1,997
|
cpp
|
C++
|
libmetartc2/src/yangcapture/YangScreenShare.cpp
|
guoai2015/metaRTC
|
70e9a09c9a703a547e791cd246c4054d87881f08
|
[
"MIT"
] | 147
|
2021-09-12T07:23:45.000Z
|
2021-11-11T11:31:26.000Z
|
libmetartc2/src/yangcapture/YangScreenShare.cpp
|
guoai2015/metaRTC
|
70e9a09c9a703a547e791cd246c4054d87881f08
|
[
"MIT"
] | 6
|
2021-11-30T07:53:09.000Z
|
2022-02-25T01:36:38.000Z
|
libmetartc2/src/yangcapture/YangScreenShare.cpp
|
guoai2015/metaRTC
|
70e9a09c9a703a547e791cd246c4054d87881f08
|
[
"MIT"
] | 36
|
2021-11-16T03:32:41.000Z
|
2022-03-31T07:21:32.000Z
|
/*
* YangScreenShareLinux.cpp
*
* Created on: 2020年8月30日
* Author: yang
*/
#include "YangScreenShare.h"
#include "yangutil/yang_unistd.h"
#include "yangavutil/video/YangYuvConvert.h"
YangScreenCapture::YangScreenCapture(){
m_isStart=0;
}
YangScreenCapture::~YangScreenCapture(){
}
void YangScreenCapture::run() {
m_isStart = 1;
startLoop();
m_isStart = 0;
}
void YangScreenCapture::stop() {
stopLoop();
}
YangScreenShare::YangScreenShare() {
//m_capture=new YangScreenShareImpl();
//m_vhandle=new YangVideoCaptureHandle();
m_isloop=0;
m_out_videoBuffer=NULL;
m_capture=NULL;
m_isCapture=0;
m_interval=0;
}
YangScreenShare::~YangScreenShare() {
m_capture=NULL;
m_out_videoBuffer=NULL;
}
void YangScreenShare::setOutVideoBuffer(YangVideoBuffer *pbuf){
m_out_videoBuffer=pbuf;
}
void YangScreenShare::setScreenHandle(YangScreenCaptureHandleI *handle){
m_capture=handle;
}
void YangScreenShare::setInterval(int32_t pinterval){
m_interval=1000*pinterval;
}
void YangScreenShare::setVideoCaptureStart() {
m_isCapture = 1;
}
void YangScreenShare::setVideoCaptureStop() {
m_isCapture = 0;
}
int32_t YangScreenShare::getVideoCaptureState() {
return m_isCapture;
}
void YangScreenShare::initstamp() {
//m_vhandle->initstamp();
}
void YangScreenShare::stopLoop() {
m_isloop = 0;
}
int32_t YangScreenShare::init() {
return m_capture->init();
}
void YangScreenShare::startLoop() {
m_isloop = 1;
/**
//m_vhandle->m_start_time = 0;
int32_t width=m_capture->m_width;
int32_t height=m_capture->m_height;
uint8_t buf[width*height*4];
uint8_t yuv[width*height*3/2];
int32_t yuvLen=width*height*3/2;
YangYuvConvert con;
int64_t timestamp=0;
YangFrame videoFrame;
memset(&m_audioFrame,0,sizeof(YangFrame));
while (m_isloop) {
m_capture->captureFrame(buf);
con.rgb24toI420(buf,yuv,width,height);
videoFrame.payload=yuv;
videoFrame.nb=yuvLen;
videoFrame.timestamp=timestamp;
m_out_videoBuffer->putVideo(&videoFrame);
yang_usleep(3000);
}**/
}
| 21.244681
| 72
| 0.750125
|
guoai2015
|
7ca18f920a7e1cd8b9a12e9af396431ee1a6f4ac
| 3,601
|
cpp
|
C++
|
src/api/c/surface.cpp
|
sanjaymsh/forge
|
173ddaa199b10115abdd3c5d34287a7950f6bff3
|
[
"BSD-3-Clause"
] | null | null | null |
src/api/c/surface.cpp
|
sanjaymsh/forge
|
173ddaa199b10115abdd3c5d34287a7950f6bff3
|
[
"BSD-3-Clause"
] | null | null | null |
src/api/c/surface.cpp
|
sanjaymsh/forge
|
173ddaa199b10115abdd3c5d34287a7950f6bff3
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************
* Copyright (c) 2015-2019, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <common/chart_renderables.hpp>
#include <common/handle.hpp>
#include <fg/surface.h>
using namespace forge;
using forge::common::getSurface;
fg_err fg_create_surface(fg_surface* pSurface, const unsigned pXPoints,
const unsigned pYPoints, const fg_dtype pType,
const fg_plot_type pPlotType,
const fg_marker_type pMarkerType) {
try {
ARG_ASSERT(1, (pXPoints > 0));
ARG_ASSERT(2, (pYPoints > 0));
*pSurface = getHandle(new common::Surface(
pXPoints, pYPoints, (forge::dtype)pType, pPlotType, pMarkerType));
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_retain_surface(fg_surface* pOut, fg_surface pIn) {
try {
ARG_ASSERT(1, (pIn != 0));
common::Surface* temp = new common::Surface(getSurface(pIn));
*pOut = getHandle(temp);
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_release_surface(fg_surface pSurface) {
try {
ARG_ASSERT(0, (pSurface != 0));
delete getSurface(pSurface);
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_set_surface_color(fg_surface pSurface, const float pRed,
const float pGreen, const float pBlue,
const float pAlpha) {
try {
ARG_ASSERT(0, (pSurface != 0));
getSurface(pSurface)->setColor(pRed, pGreen, pBlue, pAlpha);
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_set_surface_legend(fg_surface pSurface, const char* pLegend) {
try {
ARG_ASSERT(0, (pSurface != 0));
ARG_ASSERT(1, (pLegend != 0));
getSurface(pSurface)->setLegend(pLegend);
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_get_surface_vertex_buffer(unsigned* pOut, const fg_surface pSurface) {
try {
ARG_ASSERT(1, (pSurface != 0));
*pOut = getSurface(pSurface)->vbo();
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_get_surface_color_buffer(unsigned* pOut, const fg_surface pSurface) {
try {
ARG_ASSERT(1, (pSurface != 0));
*pOut = getSurface(pSurface)->cbo();
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_get_surface_alpha_buffer(unsigned* pOut, const fg_surface pSurface) {
try {
ARG_ASSERT(1, (pSurface != 0));
*pOut = getSurface(pSurface)->abo();
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_get_surface_vertex_buffer_size(unsigned* pOut,
const fg_surface pSurface) {
try {
ARG_ASSERT(1, (pSurface != 0));
*pOut = (unsigned)getSurface(pSurface)->vboSize();
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_get_surface_color_buffer_size(unsigned* pOut,
const fg_surface pSurface) {
try {
ARG_ASSERT(1, (pSurface != 0));
*pOut = (unsigned)getSurface(pSurface)->cboSize();
}
CATCHALL
return FG_ERR_NONE;
}
fg_err fg_get_surface_alpha_buffer_size(unsigned* pOut,
const fg_surface pSurface) {
try {
ARG_ASSERT(1, (pSurface != 0));
*pOut = (unsigned)getSurface(pSurface)->aboSize();
}
CATCHALL
return FG_ERR_NONE;
}
| 24.006667
| 80
| 0.588725
|
sanjaymsh
|
7ca1f03d0d13e5ab1b0e383a1d885f68dca4a426
| 388
|
cpp
|
C++
|
src/server/main.cpp
|
Ooggle/MUSIC-exclamation-mark
|
55f4dd750d57227fac29d887d90e0c8ec2ad7397
|
[
"MIT"
] | 7
|
2020-08-28T21:47:54.000Z
|
2021-01-01T17:54:27.000Z
|
src/server/main.cpp
|
Ooggle/MUSIC-exclamation-mark
|
55f4dd750d57227fac29d887d90e0c8ec2ad7397
|
[
"MIT"
] | null | null | null |
src/server/main.cpp
|
Ooggle/MUSIC-exclamation-mark
|
55f4dd750d57227fac29d887d90e0c8ec2ad7397
|
[
"MIT"
] | 1
|
2020-12-26T17:08:54.000Z
|
2020-12-26T17:08:54.000Z
|
/*
Compilation : g++ main.cpp -std=c++17 `sdl2-config --libs` -lSDL2_mixer `taglib-config --libs` `pkg-config --cflags --libs taglib` -lz
Some flags are useless for now.
*/
#include "DatabaseHandler.h"
#include "WebHandler.h"
#include <stdio.h>
#define SERVER_VERSION "0.1"
int main()
{
printf("Welcome to MUSIC! server %s.\n", SERVER_VERSION);
return EXIT_SUCCESS;
}
| 21.555556
| 138
| 0.67268
|
Ooggle
|
7ca26cc859aae12a80ec9397f9da9a51ce1475d5
| 323
|
cpp
|
C++
|
project/OFEC_sc2/core/global.cpp
|
BaiChunhui-9803/bch_sc2_OFEC
|
d50211b27df5a51a953a2475b6c292d00cbfeff6
|
[
"MIT"
] | null | null | null |
project/OFEC_sc2/core/global.cpp
|
BaiChunhui-9803/bch_sc2_OFEC
|
d50211b27df5a51a953a2475b6c292d00cbfeff6
|
[
"MIT"
] | null | null | null |
project/OFEC_sc2/core/global.cpp
|
BaiChunhui-9803/bch_sc2_OFEC
|
d50211b27df5a51a953a2475b6c292d00cbfeff6
|
[
"MIT"
] | null | null | null |
#include "global.h"
namespace OFEC {
factory<Problem> g_reg_problem;
factory<Algorithm> g_reg_algorithm;
std::map<std::string, std::set<std::string>> g_alg_for_pro;
std::set<std::string> g_param_omit;
std::map<std::string, std::string> g_param_abbr;
std::string g_working_dir = OFEC_DIR;
std::mutex g_cout_mutex;
}
| 26.916667
| 60
| 0.74613
|
BaiChunhui-9803
|
7ca48e1c9feca936e90619635dbdb1a2fba604ab
| 1,624
|
hpp
|
C++
|
ch10/stack_by_list.hpp
|
klong13579/cppL
|
7aa8afaf2d2e17578c7fd91654bedcccf0a6baab
|
[
"MIT"
] | 261
|
2015-01-11T20:42:33.000Z
|
2022-02-17T01:33:39.000Z
|
ch10/stack_by_list.hpp
|
LeungGeorge/CLRS
|
7aa8afaf2d2e17578c7fd91654bedcccf0a6baab
|
[
"MIT"
] | 4
|
2015-04-05T11:49:45.000Z
|
2017-02-19T08:29:52.000Z
|
ch10/stack_by_list.hpp
|
LeungGeorge/CLRS
|
7aa8afaf2d2e17578c7fd91654bedcccf0a6baab
|
[
"MIT"
] | 98
|
2015-01-03T12:58:50.000Z
|
2021-07-16T07:29:31.000Z
|
/***************************************************************************
* @file stack_by_list.hpp
* @author Alan.W
* @date 30 May 2014
* @remark Chapter 10, Introduction to Algorithms
* @note code style : STL
***************************************************************************/
//!
//! ex10.2-2
//! Implement a stack using a singly linked list L. The operations PUSH and POP
//! should still take O(1) time.
//!
#ifndef STACK_BY_LIST_H
#define STACK_BY_LIST_H
#include "single_list.hpp"
namespace ch10{
namespace list{
template<typename T>
class stack_by_list
{
public:
using ValueType = T;
using Node = node<ValueType>;
using sPointer = std::shared_ptr<Node>;
using SizeType = std::size_t;
using List = single_list_ring<ValueType>;
/**
* @brief default ctor
*/
stack_by_list() = default;
SizeType size() const
{
return data.size();
}
bool empty() const
{
return data.empty();
}
void print() const
{
std::cout << data;
}
/**
* @brief enqueue
*
* @complexity O(1)
*
* as required in ex10.2-2
*/
void enqueue(const ValueType& val)
{
data.insert(val);
}
/**
* @brief dequeue
*
* @complexity O(1)
*
* as required in ex10.2-2
*/
ValueType dequeue()
{
ValueType top = data.begin()->key;
data.remove(data.begin());
return top;
}
private:
List data;
};
}//namespace list
}//namespace ch10
#endif // STACK_BY_LIST_H
| 18.247191
| 79
| 0.501847
|
klong13579
|
7ca6c6de9cb2d59da81fa25e8a16df62b6c0e72b
| 3,490
|
cpp
|
C++
|
PolyCubeCut/PolyCubeCutInterface.cpp
|
msraig/CE-PolyCube
|
e46aff6e0594b711735118bfa902a91bc3d392ca
|
[
"MIT"
] | 19
|
2020-08-13T05:15:09.000Z
|
2022-03-31T14:51:29.000Z
|
PolyCubeCut/PolyCubeCutInterface.cpp
|
xh-liu-tech/CE-PolyCube
|
86d4ed0023215307116b6b3245e2dbd82907cbb8
|
[
"MIT"
] | 2
|
2020-09-08T07:03:04.000Z
|
2021-08-04T05:43:27.000Z
|
PolyCubeCut/PolyCubeCutInterface.cpp
|
xh-liu-tech/CE-PolyCube
|
86d4ed0023215307116b6b3245e2dbd82907cbb8
|
[
"MIT"
] | 10
|
2020-08-06T02:37:46.000Z
|
2021-07-01T09:12:06.000Z
|
#include "PolyCubeCutInterface.h"
#include "PolyCubeCut.h"
PolyCubeCutInterface::PolyCubeCutInterface(
const std::vector<ig::CVec<double, 3>> &v_input_point,
const std::vector<unsigned int> &v_input_face,
const std::vector<int> &v_input_chart,
const std::vector<int> &v_input_label
)
{
m_pcc = new PolyCubeCut(v_input_point, v_input_face, v_input_chart, v_input_label);
}
PolyCubeCutInterface::~PolyCubeCutInterface()
{
if (m_pcc)
delete m_pcc;
}
void PolyCubeCutInterface::get_cuttable_edge(std::vector<unsigned int> &v_cuttable_edge)
{
m_pcc->get_cuttable_edge(v_cuttable_edge);
}
void PolyCubeCutInterface::get_associated_edge(
std::map<
std::pair<unsigned int, unsigned int>,
std::vector<std::pair<unsigned int, unsigned int>>
> &map_associated_edge
)
{
m_pcc->get_associated_edge(map_associated_edge);
}
void PolyCubeCutInterface::get_convex_map(std::map<std::pair<unsigned int, unsigned int>, bool> &map_is_convex_edge)
{
m_pcc->get_convex_map(map_is_convex_edge);
}
bool PolyCubeCutInterface::is_equivalent_cut(
const std::vector<unsigned int> &v_cut_edge_a,
const std::vector<double> &v_cut_depth_a,
const std::vector<unsigned int> &v_cut_edge_b,
const std::vector<double> &v_cut_depth_b
)
{
return m_pcc->is_equivalent_cut(v_cut_edge_a, v_cut_depth_a, v_cut_edge_b, v_cut_depth_b);
}
void PolyCubeCutInterface::cut_test(
const std::vector<unsigned int> &v_cut_edge,
const std::vector<double> &v_cut_depth,
const double &max_volume,
const double &tet_quality
)
{
m_pcc->cut_test(v_cut_edge, v_cut_depth, max_volume, tet_quality);
}
void PolyCubeCutInterface::cut(
const std::vector<unsigned int> &v_cut_edge,
const std::vector<double> &v_cut_depth,
const double &max_volume,
const double &tet_quality,
std::vector<ig::CVec<double, 3>> &v_output_point,
std::vector<unsigned int> &v_output_tet,
std::vector<int> &v_output_chart,
std::vector<int> &v_output_label,
std::vector<int> &v_cut_type,
std::vector<int> &v_cut_section_chart,
std::vector<int> &v_seam_edge_vertex_id,
std::vector<std::vector<int>> &vv_congruent_face,
std::vector<ThreeCut> &v_three_cut
)
{
m_pcc->cut(
v_cut_edge, v_cut_depth, max_volume, tet_quality,
v_output_point, v_output_tet, v_output_chart, v_output_label, v_cut_type,
v_cut_section_chart, v_seam_edge_vertex_id, vv_congruent_face, v_three_cut
);
}
void PolyCubeCutInterface::cut(
const std::vector<Halfedge_handle> &v_cut_edge,
const std::vector<double> &v_cut_depth,
const double &max_volume,
const double &tet_quality,
std::vector<ig::CVec<double, 3>> &v_output_point,
std::vector<unsigned int> &v_output_tet,
std::vector<int> &v_output_chart,
std::vector<int> &v_output_label,
std::vector<int> &v_cut_type,
std::vector<int> &v_cut_section_chart,
std::vector<int> &v_seam_edge_vertex_id,
std::vector<std::vector<int>> &vv_congruent_face,
std::vector<ThreeCut> &v_three_cut
)
{
m_pcc->cut(
v_cut_edge, v_cut_depth, max_volume, tet_quality,
v_output_point, v_output_tet, v_output_chart, v_output_label, v_cut_type,
v_cut_section_chart, v_seam_edge_vertex_id, vv_congruent_face, v_three_cut
);
}
void PolyCubeCutInterface::get_cut_edge_map(std::map<std::pair<unsigned int, unsigned int>, std::vector<std::pair<unsigned int, unsigned int>>>& um_cut_edge_map)
{
m_pcc->get_cut_edge_map(um_cut_edge_map);
}
| 31.727273
| 161
| 0.738682
|
msraig
|
7ca82ca251546cfb09a8f149676c8ede2ce19251
| 3,948
|
cpp
|
C++
|
Libraries/RobsJuceModules/rosic/sequencing/rosic_AcidPattern.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 34
|
2017-04-19T18:26:02.000Z
|
2022-02-15T17:47:26.000Z
|
Libraries/RobsJuceModules/rosic/sequencing/rosic_AcidPattern.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 307
|
2017-05-04T21:45:01.000Z
|
2022-02-03T00:59:01.000Z
|
Libraries/RobsJuceModules/rosic/sequencing/rosic_AcidPattern.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 4
|
2017-09-05T17:04:31.000Z
|
2021-12-15T21:24:28.000Z
|
//#include "rosic_AcidPattern.h"
//using namespace rosic;
AcidPattern::AcidPattern()
{
numSteps = 16;
stepLength = 0.5;
}
//-------------------------------------------------------------------------------------------------
// setup:
void AcidPattern::clear()
{
for(int i=0; i<maxNumSteps; i++)
{
notes[i].key = 0;
notes[i].octave = 0;
notes[i].accent = false;
notes[i].slide = false;
notes[i].gate = false;
}
}
void AcidPattern::randomize()
{
for(int i=0; i<maxNumSteps; i++)
{
notes[i].key = roundToInt(RAPT::rsRandomUniform( 0, 11));
notes[i].octave = roundToInt(RAPT::rsRandomUniform(-2, 2));
notes[i].accent = roundToInt(RAPT::rsRandomUniform( 0, 1)) == 1;
notes[i].slide = roundToInt(RAPT::rsRandomUniform( 0, 1)) == 1;
notes[i].gate = roundToInt(RAPT::rsRandomUniform( 0, 1)) == 1;
}
// todo: use PRNG member, provide the options to randomize only accents, slides, etc.
}
void AcidPattern::setNumSteps(int newNumber)
{
RAPT::rsAssert(newNumber <= maxNumSteps);
numSteps = maxNumSteps;
}
void AcidPattern::circularShiftAll(int numStepsToShift)
{
RAPT::rsArrayTools::circularShift(notes, maxNumSteps, numStepsToShift);
}
int rsMod(int val, int modulus)
{
while(val >= modulus) val -= modulus;
while(val < 0 ) val += modulus;
return val;
}
// move somewhere else
void AcidPattern::circularShiftAccents(int shift)
{
AcidPattern tmp = *this;
for(int i = 0; i < numSteps; i++)
notes[i].accent = tmp.notes[rsMod(i-shift, numSteps)].accent;
}
// seems not to work - maybe the mod operation doe not work for negative numbers
void AcidPattern::circularShiftSlides(int shift)
{
AcidPattern tmp = *this;
for(int i = 0; i < numSteps; i++)
notes[i].slide = tmp.notes[rsMod(i-shift, numSteps)].slide;
}
void AcidPattern::circularShiftOctaves(int shift)
{
AcidPattern tmp = *this;
for(int i = 0; i < numSteps; i++)
notes[i].octave = tmp.notes[rsMod(i-shift, numSteps)].octave;
}
void AcidPattern::circularShiftNotes(int shift)
{
AcidPattern tmp = *this;
for(int i = 0; i < numSteps; i++) {
notes[i].key = tmp.notes[rsMod(i-shift, numSteps)].key;
notes[i].gate = tmp.notes[rsMod(i-shift, numSteps)].gate; }
}
void AcidPattern::reverseAll()
{
for(int i = 0; i < numSteps/2; i++)
RAPT::rsSwap(notes[i], notes[numSteps-1-i]);
}
void AcidPattern::reverseAccents()
{
for(int i = 0; i < numSteps/2; i++)
RAPT::rsSwap(notes[i].accent, notes[numSteps-1-i].accent);
}
void AcidPattern::reverseSlides()
{
for(int i = 0; i < numSteps/2; i++)
RAPT::rsSwap(notes[i].slide, notes[numSteps-1-i].slide);
}
void AcidPattern::reverseOctaves()
{
for(int i = 0; i < numSteps/2; i++)
RAPT::rsSwap(notes[i].octave, notes[numSteps-1-i].octave);
}
void AcidPattern::reverseNotes()
{
for(int i = 0; i < numSteps/2; i++)
RAPT::rsSwap(notes[i].key, notes[numSteps-1-i].key);
}
void AcidPattern::invertAccents()
{
for(int i = 0; i < numSteps; i++)
notes[i].accent = !notes[i].accent;
}
void AcidPattern::invertSlides()
{
for(int i = 0; i < numSteps; i++)
notes[i].slide = !notes[i].slide;
}
void AcidPattern::invertOctaves()
{
for(int i = 0; i < numSteps; i++)
notes[i].octave = -notes[i].octave;
}
void AcidPattern::swapAccentsWithSlides()
{
for(int i = 0; i < numSteps; i++)
RAPT::rsSwap(notes[i].accent, notes[i].slide);
}
void AcidPattern::xorAccentsWithSlides()
{
for(int i = 0; i < numSteps; i++)
notes[i].accent = rsXor(notes[i].accent, notes[i].slide);
}
void AcidPattern::xorSlidesWithAccents()
{
for(int i = 0; i < numSteps; i++)
notes[i].accent = rsXor(notes[i].accent, notes[i].slide);
}
//-------------------------------------------------------------------------------------------------
// inquiry:
bool AcidPattern::isEmpty() const
{
for(int i=0; i<maxNumSteps; i++)
{
if( notes[i].gate == true )
return false;
}
return true;
}
| 23.783133
| 102
| 0.609929
|
RobinSchmidt
|
7cb0565cdf3ef1b07f4fedd4818055fb2bb9932a
| 1,326
|
cc
|
C++
|
lang/c++/impl/Types.cc
|
AIngleLab/aae
|
6e95f89fad60e62bb5305afe97c72f3278d8e04b
|
[
"Apache-2.0"
] | null | null | null |
lang/c++/impl/Types.cc
|
AIngleLab/aae
|
6e95f89fad60e62bb5305afe97c72f3278d8e04b
|
[
"Apache-2.0"
] | null | null | null |
lang/c++/impl/Types.cc
|
AIngleLab/aae
|
6e95f89fad60e62bb5305afe97c72f3278d8e04b
|
[
"Apache-2.0"
] | null | null | null |
/**
*/
#include "Types.hh"
#include <iostream>
#include <string>
namespace aingle {
namespace strings {
const std::string typeToString[] = {
"string",
"bytes",
"int",
"long",
"float",
"double",
"boolean",
"null",
"record",
"enum",
"array",
"map",
"union",
"fixed",
"symbolic"};
static_assert((sizeof(typeToString) / sizeof(std::string)) == (AINGLE_NUM_TYPES + 1),
"Incorrect AIngle typeToString");
} // namespace strings
// this static assert exists because a 32 bit integer is used as a bit-flag for each type,
// and it would be a problem for this flag if we ever supported more than 32 types
static_assert(AINGLE_NUM_TYPES < 32, "Too many AIngle types");
const std::string &toString(Type type) noexcept {
static std::string undefinedType = "Undefined type";
if (isAIngleTypeOrPseudoType(type)) {
return strings::typeToString[type];
} else {
return undefinedType;
}
}
std::ostream &operator<<(std::ostream &os, Type type) {
if (isAIngleTypeOrPseudoType(type)) {
os << strings::typeToString[type];
} else {
os << static_cast<int>(type);
}
return os;
}
std::ostream &operator<<(std::ostream &os, const Null &) {
os << "(null value)";
return os;
}
} // namespace aingle
| 21.737705
| 90
| 0.619155
|
AIngleLab
|
7cb2402039a6a28448524e88606e450eddb9e1a8
| 9,846
|
cc
|
C++
|
src/math/test_heightfield.cc
|
mnvl/scratch
|
7717772e0b9a85c8feb73fdc3562425f48b4a727
|
[
"BSD-3-Clause"
] | 1
|
2016-08-15T11:55:32.000Z
|
2016-08-15T11:55:32.000Z
|
src/math/test_heightfield.cc
|
mnvl/scratch
|
7717772e0b9a85c8feb73fdc3562425f48b4a727
|
[
"BSD-3-Clause"
] | null | null | null |
src/math/test_heightfield.cc
|
mnvl/scratch
|
7717772e0b9a85c8feb73fdc3562425f48b4a727
|
[
"BSD-3-Clause"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include <boost/cstdint.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#include "heightfield.h"
BOOST_AUTO_TEST_SUITE(test_triangle)
BOOST_AUTO_TEST_CASE(test_raytrace_simple_1)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0, 10.0f, 0), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0, 0, 0)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_2)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0.5f, 10.0f, 0), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0.5f, 0.5f, 0)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_3)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(1, 10.0f, 0), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(1, 1, 0)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_4)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0, 10.0f, 0.5f), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0, 1.5f, 0.5f)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_5)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0, 10.0f,1), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0, 3, 1)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_6)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(1, 10.0f,1), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(1, 7, 1)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_1)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(6.6737876f, 0, 4.9803157f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_2)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(2.0899076f, 0, 5.1918087f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_3)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(4.0656757f, 0, 7.5460067f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_4)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
for (int i = 0; i < 100; ++i)
{
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(math::scalar(rand()) / RAND_MAX * 10, 0, math::scalar(rand()) / RAND_MAX * 10);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_save_load_1)
{
std::string dump;
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
std::stringstream ss;
boost::archive::binary_oarchive oa(ss);
oa & hf;
dump = ss.str();
}
math::heightfield<boost::uint8_t> hf(math::matrix<4,4>(), 10, 10);
std::stringstream stream(dump);
boost::archive::binary_iarchive(stream) & hf;
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(2.0899076f, 0, 5.1918087f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(1.7286383f, 1.7286377f, 4.2943335f)).length_sq() < 1e-6f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_y_under)
{
math::matrix<4,4> tf;
tf.scaling(1, 1, 1);
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t heights[2 * 2] = {
0, 1,
4, 9,
};
hf.load_from_raw_buffer(heights);
for (size_t i = 0; i < 100; ++i)
{
math::scalar height = hf.y_under(math::vec<3>(i / 100.0f, 100, 0));
BOOST_REQUIRE (abs(height - i / 100.0) < 1e-3);
}
for (size_t i = 0; i < 100; ++i)
{
math::scalar height = hf.y_under(math::vec<3>(0, 100, i / 100.0f));
BOOST_REQUIRE (abs(height - 4 * i / 100.0f) < 1e-3);
}
for (size_t i = 0; i < 100; ++i)
{
math::scalar height1 = hf.y_under(math::vec<3>(i / 100.0f, 100, 1 - 1e-6f));
math::scalar height2 = 4 + (9 - 4) * i / 100.0f;
BOOST_REQUIRE (abs(height1 - height2) < 0.01f);
}
for (size_t i = 0; i < 100; ++i)
{
math::scalar height1 = hf.y_under(math::vec<3>(1 - 1e-6f, 100, i / 100.0f));
math::scalar height2 = 1 + (9 - 1) * i / 100.0f;
BOOST_REQUIRE (abs(height1 - height2) < 0.01f);
}
}
BOOST_AUTO_TEST_SUITE_END()
| 26.467742
| 108
| 0.582064
|
mnvl
|
7cb2ddc579a2d08161f030133cc2d6295ec37fb1
| 89,722
|
cpp
|
C++
|
src/reader.cpp
|
david-cortes/readsparse
|
1d816bdccd628788027041e92d83e8e20702de86
|
[
"BSD-2-Clause"
] | 5
|
2021-01-10T06:22:11.000Z
|
2021-04-13T12:59:40.000Z
|
src/reader.cpp
|
david-cortes/readsparse
|
1d816bdccd628788027041e92d83e8e20702de86
|
[
"BSD-2-Clause"
] | 1
|
2021-01-10T04:42:17.000Z
|
2021-01-10T10:55:58.000Z
|
src/reader.cpp
|
david-cortes/readsparse
|
1d816bdccd628788027041e92d83e8e20702de86
|
[
"BSD-2-Clause"
] | 1
|
2021-04-13T12:59:41.000Z
|
2021-04-13T12:59:41.000Z
|
/* Generated through 'instantiate_templates.py', do not edit manually. */
/* Read and write sparse matrices in text format:
* <labels(s)> <column>:<value> <column>:<value> ...
*
* BSD 2-Clause License
* Copyright (c) 2021, David Cortes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_FOR_PYTHON) || defined(_FOR_R) || !defined(_WIN32)
#define EXPORTABLE
#else
#ifdef READSPARSE_COMPILE
#define EXPORTABLE __declspec(dllexport)
#else
#define EXPORTABLE __declspec(dllimport)
#endif
#endif
#include "reader.hpp"
#ifdef _FOR_R
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
#elif defined(_FOR_PYTHON)
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
#else
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
#endif /* _FOR_R, _FOR_PYTHON */
| 23.058854
| 84
| 0.617441
|
david-cortes
|
7cb574e9ac5f67235a3ff3c89c8c918f75508ed3
| 1,546
|
cpp
|
C++
|
internalconnector/internalrastercoverageconnector.cpp
|
ridoo/IlwisCore
|
9d9837507d804a4643545a03fd40d9b4d0eaee45
|
[
"Apache-2.0"
] | null | null | null |
internalconnector/internalrastercoverageconnector.cpp
|
ridoo/IlwisCore
|
9d9837507d804a4643545a03fd40d9b4d0eaee45
|
[
"Apache-2.0"
] | null | null | null |
internalconnector/internalrastercoverageconnector.cpp
|
ridoo/IlwisCore
|
9d9837507d804a4643545a03fd40d9b4d0eaee45
|
[
"Apache-2.0"
] | null | null | null |
#include "kernel.h"
#include "raster.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "connectorinterface.h"
#include "mastercatalog.h"
#include "ilwisobjectconnector.h"
#include "catalogexplorer.h"
#include "catalogconnector.h"
#include "internalrastercoverageconnector.h"
using namespace Ilwis;
using namespace Internal;
ConnectorInterface *Ilwis::Internal::InternalRasterCoverageConnector::create(const Ilwis::Resource &resource,bool load,const IOOptions& options)
{
return new InternalRasterCoverageConnector(resource, load, options);
}
InternalRasterCoverageConnector::InternalRasterCoverageConnector(const Resource &resource, bool load,const IOOptions& options) : IlwisObjectConnector(resource, load, options)
{
}
bool InternalRasterCoverageConnector::loadMetaData(IlwisObject *data, const IOOptions &options){
RasterCoverage *gcoverage = static_cast<RasterCoverage *>(data);
if(_dataType == gcoverage->datadef().range().isNull())
return false;
if ( !gcoverage->datadef().range().isNull())
_dataType = gcoverage->datadef().range()->valueType();
gcoverage->gridRef()->prepare(gcoverage,gcoverage->size());
return true;
}
bool InternalRasterCoverageConnector::loadData(IlwisObject *, const IOOptions &){
return true;
}
QString Ilwis::Internal::InternalRasterCoverageConnector::provider() const
{
return "internal";
}
IlwisObject *InternalRasterCoverageConnector::create() const
{
return new RasterCoverage();
}
| 27.607143
| 174
| 0.76326
|
ridoo
|
7cbc334cb01636a1bcb59b8de0f8ff2fcf0c0a52
| 2,385
|
cpp
|
C++
|
src/D3D9Hook.cpp
|
muhopensores/dmc3-inputs-thing
|
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
|
[
"MIT"
] | 5
|
2021-06-09T23:53:28.000Z
|
2022-02-21T06:09:41.000Z
|
src/D3D9Hook.cpp
|
muhopensores/dmc3-inputs-thing
|
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
|
[
"MIT"
] | 9
|
2021-06-09T23:52:43.000Z
|
2021-09-17T14:05:47.000Z
|
src/D3D9Hook.cpp
|
muhopensores/dmc3-inputs-thing
|
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <spdlog/spdlog.h>
#include "D3D9Hook.hpp"
using namespace std;
static D3D9Hook* g_d3d9_hook = nullptr;
D3D9Hook::~D3D9Hook() {
unhook();
}
uintptr_t end_scene_jmp_ret = 0;
__declspec(naked) void end_scene_hook(void) {
__asm {
pushad
push eax
call D3D9Hook::end_scene
popad
pop eax
push eax
call dword ptr [ecx+0xA8]
jmp dword ptr [end_scene_jmp_ret]
}
}
uintptr_t reset_jmp_ret = 0;
__declspec(naked) void reset_hook(void) {
__asm {
pushad
push eax
call D3D9Hook::reset
popad
pop eax
push eax
call dword ptr [ecx+0x40]
mov esi, eax
jmp dword ptr [reset_jmp_ret]
}
}
bool D3D9Hook::hook() {
spdlog::info("Hooking D3D9");
g_d3d9_hook = this;
IDirect3DDevice9** game = (IDirect3DDevice9**)0x0252F374;
IDirect3DDevice9* d3d9_device = *game; // TODO: base + offset?
m_device = d3d9_device;
uintptr_t reset_fn = (*(uintptr_t**)d3d9_device)[16];
uintptr_t end_scene_fn = (*(uintptr_t**)d3d9_device)[42];
m_end_scene_hook = std::make_unique<FunctionHook>(end_scene_fn, (uintptr_t)&end_scene);//std::make_unique<FunctionHook>(end_scene_fn, (uintptr_t)&end_scene_hook);
m_reset_hook = std::make_unique<FunctionHook>(reset_fn, (uintptr_t)&reset);
//end_scene_jmp_ret = 0x006DC48E + 0x6;
//reset_jmp_ret = reset_fn + 5;
m_hooked = m_end_scene_hook->create() && m_reset_hook->create();
return m_hooked;
}
bool D3D9Hook::unhook() {
return true;
}
#if 1
HRESULT WINAPI D3D9Hook::end_scene(LPDIRECT3DDEVICE9 pDevice) {
auto d3d9 = g_d3d9_hook;
//d3d9->m_device = pDevice;
if (d3d9->m_on_end_scene) {
d3d9->m_on_end_scene(*d3d9);
}
//return S_OK;
auto end_scene_fn =
d3d9->m_end_scene_hook->get_original<decltype(D3D9Hook::end_scene)>();
return end_scene_fn(pDevice);
}
#else
static void end_scene_our(LPDIRECT3DDEVICE9 pDevice) {
auto d3d9 = g_d3d9_hook;
d3d9->set_device(pDevice);
if (d3d9->m_on_end_scene) {
d3d9->m_on_end_scene(*d3d9);
}
}
#endif
HRESULT WINAPI D3D9Hook::reset(LPDIRECT3DDEVICE9 pDevice, D3DPRESENT_PARAMETERS *pPresentationParameters) {
auto d3d9 = g_d3d9_hook;
d3d9->m_presentation_params = pPresentationParameters;
if (d3d9->m_on_reset) {
d3d9->m_on_reset(*d3d9);
}
//return S_OK;
auto reset_fn =
d3d9->m_reset_hook->get_original<decltype(D3D9Hook::reset)>();
return reset_fn(pDevice, pPresentationParameters);
}
| 21.681818
| 166
| 0.72369
|
muhopensores
|
7cbc953df2964ce38192ac835e350fa99d16ce84
| 947
|
cpp
|
C++
|
Strings/LengthOfLastWord58.cpp
|
devangi2000/Data-Structures-Algorithms-Handbook
|
ce0f00de89af5da7f986e65089402dc6908a09b5
|
[
"MIT"
] | 38
|
2021-10-14T09:36:53.000Z
|
2022-01-27T02:36:19.000Z
|
Strings/LengthOfLastWord58.cpp
|
devangi2000/Data-Structures-Algorithms-Handbook
|
ce0f00de89af5da7f986e65089402dc6908a09b5
|
[
"MIT"
] | null | null | null |
Strings/LengthOfLastWord58.cpp
|
devangi2000/Data-Structures-Algorithms-Handbook
|
ce0f00de89af5da7f986e65089402dc6908a09b5
|
[
"MIT"
] | 4
|
2021-12-06T15:47:12.000Z
|
2022-02-04T04:25:00.000Z
|
// Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
// A word is a maximal substring consisting of non-space characters only.
// Example 1:
// Input: s = "Hello World"
// Output: 5
// Explanation: The last word is "World" with length 5.
// Example 2:
// Input: s = " fly me to the moon "
// Output: 4
// Explanation: The last word is "moon" with length 4.
// Example 3:
// Input: s = "luffy is still joyboy"
// Output: 6
// Explanation: The last word is "joyboy" with length 6.
// Constraints:
// 1 <= s.length <= 104
// s consists of only English letters and spaces ' '.
// There will be at least one word in s.
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, n = s.size()-1;
while(n >= 0 and s[n] == ' ') n--;
while(n >= 0 and s[n--] != ' ') len++;
return len;
}
};
| 32.655172
| 131
| 0.600845
|
devangi2000
|
7cbdbb18250cf7d6bfd0461342c062690aebbb75
| 579
|
cpp
|
C++
|
threading.cpp
|
brandonbraun653/TeamSOAR
|
472c7e900de20545476e76395ebe89ab5467ae11
|
[
"MIT"
] | null | null | null |
threading.cpp
|
brandonbraun653/TeamSOAR
|
472c7e900de20545476e76395ebe89ab5467ae11
|
[
"MIT"
] | null | null | null |
threading.cpp
|
brandonbraun653/TeamSOAR
|
472c7e900de20545476e76395ebe89ab5467ae11
|
[
"MIT"
] | null | null | null |
#include "threading.hpp"
QueueHandle_t qAHRS = xQueueCreate(1, sizeof(AHRSData_t));
SemaphoreHandle_t ahrsBufferMutex = xSemaphoreCreateMutex();
boost::container::vector<void*> TaskHandle(TOTAL_TASK_SIZE);
BaseType_t xTaskSendMessage(TaskIndex idx, uint32_t msg)
{
if (TaskHandle[idx])
return xTaskNotify(TaskHandle[idx], msg, eSetValueWithOverwrite);
else
return pdFAIL;
}
BaseType_t xTaskSendMessageFromISR(TaskIndex idx, uint32_t msg)
{
if (TaskHandle[idx])
return xTaskNotifyFromISR(TaskHandle[idx], msg, eSetValueWithOverwrite, NULL);
else
return pdFAIL;
}
| 24.125
| 80
| 0.787565
|
brandonbraun653
|
7cbf6b75bd6ea36ecdadc7160eb5608779872ea9
| 40,214
|
cpp
|
C++
|
lib/klc3/Core/Executor.cpp
|
liuzikai/klc3
|
0c7c1504158f1cce3e6bff32f69b4cb3067cffff
|
[
"NCSA"
] | null | null | null |
lib/klc3/Core/Executor.cpp
|
liuzikai/klc3
|
0c7c1504158f1cce3e6bff32f69b4cb3067cffff
|
[
"NCSA"
] | null | null | null |
lib/klc3/Core/Executor.cpp
|
liuzikai/klc3
|
0c7c1504158f1cce3e6bff32f69b4cb3067cffff
|
[
"NCSA"
] | null | null | null |
//
// Created by liuzikai on 3/19/20.
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
#include "klc3/Core/Executor.h"
#include "klc3/Generation/ReportFormatter.h"
#define LOG_BR_FORK 0
#define LOG_SYM_ADDR_FORK 0
#define DISABLE_FORK_ON_SYM_ADDR 0
namespace klc3 {
extern llvm::cl::OptionCategory KLC3ExecutionCat;
llvm::cl::opt<int> ForkOnSymAddrThreshold(
"cache-sym-addr-threshold",
llvm::cl::desc("Cache a memory access of a symbolic address whose "
"number of possible concrete values is less than this limit "
"under the initial constraints. "
"Set to 0 to disable. Set to -1 for unlimited. (default=0)"),
llvm::cl::init(0),
llvm::cl::cat(KLC3ExecutionCat));
Executor::Executor(ExprBuilder *builder, Solver *solver, const map<uint16_t, ref<MemValue>> &mem)
: WithBuilder(builder),
symAddrCacheHits("SymAddrCacheHits", "SAHits"),
symAddrCacheMisses("SymAddrCacheMisses", "SAMiss"), solver(solver) {
// baseMem initialized to nullptr (by ref())
for (const auto &m: mem) {
baseMem[m.first] = m.second;
}
if (ForkOnSymAddrThreshold != 0) {
newProgWarn() << "using the symbolic address cache with threshold " << ForkOnSymAddrThreshold
<< ", which is only effective for well designed input spaces.\n";
}
}
State *Executor::createInitState(const vector<ref<Expr>> &constraints, uint16_t initPC, IssuePackage *issuePackage) {
auto *s = stateAllocator.createInitState(builder, baseMem, initPC, issuePackage);
// Load constraints into state and check compatibility
for (const auto &c : constraints) {
bool res;
bool success = solver->mustBeFalse(Query(s->constraints, c), res);
assert(success && "Unexpected solver failure");
s->solverCount++;
if (res) {
newProgErr() << "Initial constraints are provably unsatisfiable! Failed to create initial state!" << "\n"
<< " Triggering constraint: " << c << "\n";
progExit();
} else {
s->addConstraint(c);
}
}
// Save a copy of initial constraints for possibleValuesCache, for example
initConstraints = s->constraints;
return s;
}
bool Executor::step(State *s, StateVector &result, bool returnImmediatelyIfWillFork) {
result.clear();
/// Phase 1. Fetch Instruction
ref<InstValue> ir = nullptr;
fetchInst(s, ir);
if (s->status != State::NORMAL) {
result.push_back(s);
return true;
}
if (returnImmediatelyIfWillFork && !ir.isNull() && ir->instID() == InstValue::BR) {
ref<Expr> brCond;
Solver::Validity br = solveBRCond(s, ir, brCond);
if (br == klee::Solver::Unknown) {
return false;
}
}
// Update path info
for (unsigned i = 1; i < State::RECORD_FETCHED_INST_COUNT; i++) {
s->latestInst[i] = s->latestInst[i - 1];
}
s->latestInst[0] = ir.get();
if (!ir->belongsToOS) {
for (unsigned i = 1; i < State::RECORD_FETCHED_INST_COUNT; i++) {
s->latestNonOSInst[i] = s->latestNonOSInst[i - 1];
}
s->latestNonOSInst[0] = ir.get();
}
++s->stepCount; // include OS node
/// Phase 2. Update IR and PC
updateIRAndPC(s, ir);
if (s->status != State::NORMAL) {
result.push_back(s);
return true;
}
/// Phase 3. Execute Instruction
switch (ir->instID()) {
case InstValue::BR:
executeBR(s, ir, result);
return true; // result is already filled
case InstValue::LDR:
executeLDR(s, ir, result);
return true;
case InstValue::LDI:
executeLDI(s, ir, result);
return true;
case InstValue::STR:
executeSTR(s, ir, result);
return true;
case InstValue::STI:
executeSTI(s, ir, result);
return true;
case InstValue::ADD:
case InstValue::ADDi:
executeADD(s, ir);
break;
case InstValue::AND:
case InstValue::ANDi:
executeAND(s, ir);
break;
case InstValue::JMP:
executeJMP(s, ir);
break;
case InstValue::JSR:
executeJSR(s, ir);
break;
case InstValue::JSRR:
executeJSRR(s, ir);
break;
case InstValue::LD:
executeLD(s, ir);
break;
case InstValue::LEA:
executeLEA(s, ir);
break;
case InstValue::NOT:
executeNOT(s, ir);
break;
case InstValue::ST:
executeST(s, ir);
break;
case InstValue::TRAP:
executeTRAP(s, ir);
break;
case InstValue::RTI:
if (auto issueInfo = s->newStateIssue(Issue::ERR_INVALID_INST, ir)) {
issueInfo->setNote("RTI is not supported at " + reportFormatter->formattedContext(ir) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
break;
default:
assert(!"Instruction is not supported yet");
}
result.push_back(s);
return true;
}
void Executor::fetchInst(State *s, ref<InstValue> &ir) {
uint16_t pc = s->getPC();
ref<MemValue> val = s->mem.read(pc);
if (!val.isNull() && val->type == MemValue::MEM_INST) {
ir = dyn_cast<InstValue>(val);
} else {
// Use last executed inst as break point
if (val.isNull()) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_EXECUTE_UNINITIALIZED_MEMORY, s->latestNonOSInst[0])) {
issueInfo->setNote("trying to execute addr " + toLC3Hex(pc) + ".\n");
}
} else if (val->type == MemValue::MEM_DATA) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_EXECUTE_DATA_AS_INST, s->latestNonOSInst[0])) {
issueInfo->setNote("trying to execute addr " + toLC3Hex(pc) + ".\n");
}
}
assert(s->status == State::BROKEN && "Non-continuable error");
}
}
void Executor::updateIRAndPC(State *s, const ref<InstValue> &ir) {
setReg(s, R_IR, ir->e, ir);
setReg(s, R_PC, (s->getPC() + 1) & 0xFFFF, ir);
}
void Executor::executeSTR(State *s, const ref<InstValue> &ir, StateVector &result) {
handleExprST(s,
builder->Add(getReg(s, ir->baseR(), ir), buildConstant(ir->imm6())),
getReg(s, ir->sr(), ir, true), // bypass uninitialized register null value
ir,
result);
}
void Executor::executeSTI(State *s, const ref<InstValue> &ir, StateVector &result) {
uint16_t addr = s->getPC() + ir->imm9(); // auto wrap 0xFFFF
ref<Expr> midAddr;
memReadData(s, addr, midAddr, ir, -1);
if (s->status != State::NORMAL) {
result.push_back(s);
return;
}
handleExprST(s, midAddr, getReg(s, ir->sr(), ir, true), ir, result); // by pass null
}
void Executor::handleExprST(State *s, const ref<Expr> &addr, const ref<Expr> &value, const ref<InstValue> &ir,
StateVector &result) {
if (addr->getKind() == Expr::Constant) {
memWriteData(s, castConstant(addr), value, ir); // if value is null, still bypass it
result.push_back(s);
} else {
vector<pair<uint16_t, State *>> instances;
forkOnRange(s, addr, ir, instances);
assert(!instances.empty() && "Immediate address evaluate to no range, which means constraints have conflicts");
for (auto &it : instances) {
uint16_t realizedAddr = it.first;
State *t = it.second;
memWriteData(t, realizedAddr, value, ir); // if value is null, still bypass it
result.push_back(t);
}
}
}
void Executor::executeLDR(State *s, const ref<InstValue> &ir, StateVector &result) {
Reg DR = ir->dr();
ref<Expr> midAddr = builder->Add(getReg(s, ir->baseR(), ir), buildConstant(ir->imm6()));
handleExprLD(s, DR, midAddr, ir, result);
}
void Executor::executeLDI(State *s, const ref<InstValue> &ir, StateVector &result) {
Reg DR = ir->dr();
uint16_t addr = s->getPC() + ir->imm9();
ref<Expr> midAddr;
memReadData(s, addr, midAddr, ir, -1);
if (s->status != State::NORMAL) {
result.push_back(s);
return;
}
handleExprLD(s, DR, midAddr, ir, result);
}
void
Executor::handleExprLD(State *s, Reg DR, const ref<Expr> &addr, const ref<InstValue> &ir, StateVector &result) {
if (addr->getKind() == Expr::Constant) {
ref<Expr> data;
memReadData(s, castConstant(addr), data, ir, DR);
if (s->status != State::NORMAL) {
result.push_back(s);
return;
}
setReg(s, DR, data, ir);
setCC(s, DR, ir);
result.push_back(s);
return;
} else {
vector<pair<uint16_t, State *>> instances;
forkOnRange(s, addr, ir, instances);
assert(!instances.empty() && "Immediate address evaluate to no range, which means constraints have conflicts");
for (auto &it : instances) {
uint16_t realizedAddr = it.first;
State *t = it.second;
ref<Expr> data;
memReadData(t, realizedAddr, data, ir, DR);
if (t->status != State::NORMAL) {
result.push_back(t);
continue;
}
setReg(t, DR, data, ir);
setCC(t, DR, ir);
result.push_back(t);
}
return;
}
}
/**
* Fork states by range of given expression
* @param s
* @param val
* @param instances [out] vector of pairs of {evaluated value, state}
*/
void Executor::forkOnRange(State *s, const ref<Expr> &val, const ref<InstValue> &ir,
vector<pair<uint16_t, State *>> &instances) {
vector<pair<uint16_t, ref<Expr>>> values;
evalPossibleValuesWithCache(val, s->constraints, values, s->solverCount);
if (values.empty()) return; // no valid range
if (values.size() > 1) { // need to fork
#if LOG_SYM_ADDR_FORK
progInfo() << "Fork " << values.size() - 1 << " states" << " At: " << ir->sourceContext() << "\n";
#endif
}
#if !DISABLE_FORK_ON_SYM_ADDR
for (unsigned i = 0; i < values.size(); i++) {
State *t = (i != values.size() - 1 ? stateAllocator.fork(s) : s); // realize s to the last value
// Notice that s must be the last, or changes on it will be forked into other states
// If there is only one values, no need to add the Eq constraint since it must be true
if (!values[i].second.isNull() && values.size() != 1) {
t->addConstraint(values[i].second);
}
instances.emplace_back(values[i].first, t);
}
#else
bool res;
bool success = solver->mustBeTrue(Query(s->constraints, values.back().second), res);
assert(success && "Unexpected solver failure");
s->solverCount++;
if (!res) s->addConstraint(values.back().second);
instances.emplace_back(values.back().first, s);
#endif
}
void Executor::evalPossibleValuesWithCache(const ref<Expr> &expr, const ConstraintSet &constraints,
vector<pair<uint16_t, ref<Expr>>> &result, int &solverCount) {
assert(expr->getWidth() == Expr::Int16);
if (ForkOnSymAddrThreshold == 0) {
evalPossibleValues(expr, constraints, result, solverCount);
return;
}
auto it = possibleValuesCache.find(expr);
if (it == possibleValuesCache.end()) {
++symAddrCacheMisses;
vector<pair<uint16_t, ref<Expr>>> resultUnderInitConstraints; // pairs of value, expr == value
// Evaluate the possible values under initial constraints, with a upper limit on possible value count
if (evalPossibleValues(expr, initConstraints, resultUnderInitConstraints, solverCount,
ForkOnSymAddrThreshold)) {
assert(!resultUnderInitConstraints.empty() && "Expr under initial constraints evaluates to no value!");
it = possibleValuesCache.emplace(expr, resultUnderInitConstraints).first;
} else {
// Place an empty vector to indicate there are too many possible values under only initial constraints
it = possibleValuesCache.emplace(expr, vector<pair<uint16_t, ref<Expr>>>{}).first;
static bool alreadyWarned = false;
if (!alreadyWarned) {
newProgWarn() << "Possible values on an Expr under initial constraints result in too many values.\n";
alreadyWarned = true;
}
}
} else {
++symAddrCacheHits;
}
// Evaluate possible values on current constraints
if (it->second.empty()) {
/*
* Evaluation on initial constraints results in too many possible values, possibly due to poorly designed input
* space. Hope the currently evaluated program is well written, so that reasonable constraints are placed on
* the variables and the evaluation on complete current constraints won't result in too many values. Otherwise,
* it will get explode anyway...
*/
evalPossibleValues(expr, constraints, result, solverCount);
} else {
for (const auto &item : it->second) {
bool res, success;
success = solver->mayBeTrue(Query(constraints, item.second), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
result.emplace_back(item);
}
}
}
}
bool Executor::evalPossibleValues(const ref<Expr> &expr, const ConstraintSet &constraints,
vector<pair<uint16_t, ref<Expr>>> &result, int &solverCount,
int maxPossibleValueCount) const {
assert(expr->getWidth() == Expr::Int16);
uint16_t minVal, maxVal;
bool res, success;
// Binary search for # of useful bits
uint64_t lo = 0, hi = 16, mid, bits = 0;
while (lo < hi) {
mid = lo + (hi - lo) / 2;
success = solver->mustBeTrue(Query(constraints,
builder->Eq(builder->LShr(expr, buildConstant(mid)),
buildConstant(0))),
res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
bits = lo;
// Binary search for min
lo = 0, hi = klee::bits64::maxValueOfNBits(bits);
while (lo < hi) {
mid = lo + (hi - lo) / 2;
success = solver->mayBeTrue(Query(constraints, builder->Ule(expr, buildConstant(mid))),
res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
minVal = lo;
// Check for the common case that maxVal == minVal
ref<Expr> c = builder->Eq(expr, buildConstant(minVal));
success = solver->mustBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
result.emplace_back(minVal, c);
return (maxPossibleValueCount == -1 || (int) result.size() <= maxPossibleValueCount);
}
// Binary search for max
lo = minVal, hi = klee::bits64::maxValueOfNBits(bits);
while (lo < hi) {
mid = lo + (hi - lo) / 2;
success = solver->mustBeTrue(Query(constraints, builder->Ule(expr, buildConstant(mid))),
res);
solverCount++;
assert(success && "FIXME: Unhandled solver failure");
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
maxVal = lo;
/*maxVal = klee::bits64::maxValueOfNBits(bits);*/
return evalPossibleValuesInRange(expr, constraints, minVal, maxVal, result, solverCount, maxPossibleValueCount);
}
bool Executor::evalPossibleValuesInRange(const ref<Expr> &expr, const ConstraintSet &constraints,
long minVal, long maxVal,
vector<pair<uint16_t, ref<Expr>>> &result, int &solverCount,
int maxPossibleValueCount) const {
// NOTE: as we do arithmetic, minVal, maxVal and midVal below must be larger than uint16_t (and better to be signed)
bool res, success;
ref<Expr> c;
if (minVal > maxVal) {
return true;
} else if (maxVal - minVal <= 3) {
/**
* [0, 3] for example
* Direct Eq: 4 queries
* Fall back to else below, worse case: 6 queries
* mid = 1
* 1) 0 <= expr <= 1? [0, 1]
* 2) expr == 0?
* 3) expr == 1?
* 4) 2 <= expr <= 3? [2, 3]
* 5) expr == 2?
* 6) expr == 3?
* Best case: 3 (half of the range is impossible, while the other must be possible or it will exit earlier)
* 1) 0 <= expr <= 1? No. Then 2 <= expr <= 3 must be true.
* 2) expr == 2?
* 3) expr == 3?
*/
// NOTE: must be larger than uint16_t or ++ may overflow
for (long val = minVal; val <= maxVal; val++) {
c = builder->Eq(expr, buildConstant(val));
success = solver->mayBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) result.emplace_back(val, c);
if (maxPossibleValueCount != -1 && (int) result.size() > maxPossibleValueCount) return false;
}
} else {
long midVal = (minVal + maxVal) / 2;
// [minVal, midVal]
if (minVal == midVal) {
// Just query Eq
if (!evalPossibleValuesInRange(expr, constraints, minVal, midVal, result, solverCount,
maxPossibleValueCount))
return false;
} else {
// Check whether this half is possible
c = builder->And(
builder->Ule(buildConstant(minVal), expr),
builder->Ule(expr, buildConstant(midVal))
);
success = solver->mayBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
if (!evalPossibleValuesInRange(expr, constraints, minVal, midVal, result, solverCount,
maxPossibleValueCount))
return false;
}
}
// [midVal + 1, maxVal]
if (midVal + 1 == maxVal) {
// Just query Eq
if (!evalPossibleValuesInRange(expr, constraints, midVal + 1, maxVal, result, solverCount,
maxPossibleValueCount))
return false;
} else {
if (!res) {
// The other half is not possible, then this half must be possible
res = true;
} else {
// Check whether this half is possible
c = builder->And(
builder->Ule(buildConstant(midVal + 1), expr),
builder->Ule(expr, buildConstant(maxVal))
);
success = solver->mayBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
}
if (res) {
if (!evalPossibleValuesInRange(expr, constraints, midVal + 1, maxVal, result, solverCount,
maxPossibleValueCount))
return false;
}
}
}
return true;
}
void Executor::executeBR(State *s, const ref<InstValue> &ir, StateVector &result) {
ref<Expr> brCond;
Solver::Validity br = solveBRCond(s, ir, brCond);
State *continueState = nullptr;
State *branchState = nullptr;
if (br == Solver::True) { // always branch
branchState = s;
} else if (br == Solver::False) { // always continue
continueState = s;
} else {
// Fork state
branchState = s;
continueState = stateAllocator.fork(s);
// Add constraints
branchState->addConstraint(brCond);
ref<Expr> continueCond = Expr::createIsZero(brCond);
continueState->addConstraint(continueCond);
#if LOG_BR_FORK
progInfo() << "Fork 1 state" << " At: " << ir->sourceContext() << "\n";
#endif
}
if (branchState != nullptr) {
// Execute branch
setReg(branchState, R_PC, branchState->getPC() + ir->imm9(), ir); // auto wrap 0xFFFF
}
if (continueState != nullptr) result.push_back(continueState);
if (branchState != nullptr) result.push_back(branchState);
}
Solver::Validity Executor::solveBRCond(State *s, const ref<InstValue> &ir, ref<Expr> &brCond) {
// Generate branch condition
// Only using Eq, Slt and Sle in canonical mode
switch (ir->cc()) {
case InstValue::CC_NONE:
brCond = nullptr;
return klee::Solver::False; // never branch
case InstValue::CC_NZP:
brCond = nullptr;
return klee::Solver::True; // always branch
case InstValue::CC_N:
brCond = builder->Slt(getCCExpr(s, ir), buildConstant(0));
break;
case InstValue::CC_Z:
brCond = Expr::createIsZero(getCCExpr(s, ir));
break;
case InstValue::CC_P:
brCond = builder->Slt(buildConstant(0), getCCExpr(s, ir));
break;
case InstValue::CC_NP:
brCond = Expr::createIsZero(Expr::createIsZero(getCCExpr(s, ir)));
break;
case InstValue::CC_NZ:
brCond = builder->Sle(getCCExpr(s, ir), buildConstant(0));
break;
case InstValue::CC_ZP:
brCond = builder->Sle(buildConstant(0), getCCExpr(s, ir));
break;
}
// Constant folding builder
if (brCond->isTrue()) return klee::Solver::True;
else if (brCond->isFalse()) return klee::Solver::False;
#if 0
progInfo() << " brCond: " << brCond << "\n" << " Constraint:" << "\n";
for (auto it = s->constraints.begin(); it != s->constraints.end(); it++) {
progInfo() << " " << *it << "\n";
}
progInfo() << "At: " << ir->sourceContext() << "\n";
#endif
klee::Solver::Validity ret;
bool success = solver->evaluate(Query(s->constraints, brCond), ret);
assert(success && "Unhandled solver failure");
s->solverCount++;
#if 0
if (ret == klee::Solver::Validity::Unknown) {
progInfo() << " brCond: " << brCond << " => Unknown\n" << " Constraint:" << "\n";
for (auto it = s->constraints.begin(); it != s->constraints.end(); it++) {
progInfo() << " " << *it << "\n";
}
}
#endif
return ret;
}
void Executor::executeST(State *s, const ref<InstValue> &ir) {
memWriteData(s,
s->getPC() + ir->imm9(), // auto wrap 0xFFFF
getReg(s, ir->sr(), ir, true), ir); // bypass uninitialized register null value
}
void Executor::executeLD(State *s, const ref<InstValue> &ir) {
Reg DR = ir->dr();
uint16_t addr = s->getPC() + ir->imm9();
ref<Expr> result;
memReadData(s, addr, result, ir, DR);
if (s->status != State::NORMAL) return;
setReg(s, DR, result, ir);
setCC(s, DR, ir);
}
void Executor::executeJMP(State *s, const ref<InstValue> &ir) {
if (!ir->belongsToOS && ir->baseR() == R_R7) {
if (!s->stackHasMessedUp && !s->colorStack.empty() && s->colorStack.size() < 2) { // in main code
if (auto issueInfo = s->newStateIssue(Issue::ERR_RET_IN_MAIN_CODE, ir)) {
issueInfo->setNote("main code starts at: " + toLC3Hex(s->colorStack.top()) + ".\n");
}
// By default ERROR, but can allow WARNING or NONE
s->stackHasMessedUp = true;
} // otherwise, do nothing, execute it and let SubroutineTracker to handle it
}
if (s->status == State::NORMAL) {
ref<Expr> newPC = getReg(s, ir->baseR(), ir);
if (newPC->getKind() != Expr::Constant) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_SYMBOLIC_PC, ir)) {
issueInfo->setNote("last instruction that set PC: " +
(s->regChangeLocation[R_PC].isNull() ?
"(none)" : reportFormatter->formattedContext(s->regChangeLocation[R_PC])) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
return;
}
setReg(s, R_PC, newPC, ir);
}
}
void Executor::executeJSRR(State *s, const ref<InstValue> &ir) {
// Note: no special handle for JMP R7 for now
ref<Expr> newPC = getReg(s, ir->baseR(), ir);
if (newPC->getKind() != Expr::Constant) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_SYMBOLIC_PC, ir)) {
issueInfo->setNote("last instruction that set PC: " +
(s->regChangeLocation[R_PC].isNull() ?
"(none)" : reportFormatter->formattedContext(s->regChangeLocation[R_PC])) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
return;
}
setReg(s, R_R7, s->getPC(), ir);
setReg(s, R_PC, newPC, ir);
}
void Executor::executeADD(State *s, const ref<InstValue> &ir) {
Reg dr = ir->dr();
ref<Expr> op1 = getReg(s, ir->sr1(), ir);
ref<Expr> op2 = (ir->instDef().format == InstValue::FMT_RRR ?
getReg(s, ir->sr2(), ir) :
static_cast<ref<Expr>>(buildConstant(ir->imm5())));
ref<Expr> result;
// If we encounter Mul expression, it must have been constructed here, so we can safely infer its structure.
// But the expression can be re-written by KLEE so left and right can swap. Use the convention:
// Left: constant. Right: Expr.
auto mul1 = op1->getKind() == klee::Expr::Mul ? dyn_cast<klee::BinaryExpr>(op1) : nullptr;
auto mul2 = op2->getKind() == klee::Expr::Mul ? dyn_cast<klee::BinaryExpr>(op2) : nullptr;
if (mul1) assert(mul1->left->getKind() == klee::Expr::Constant && "Unexpected mul1 structure");
if (mul2) assert(mul2->left->getKind() == klee::Expr::Constant && "Unexpected mul2 structure");
if (op1 == op2) {
// Replace adding itself by multiplying by 2
// Left shift by 1 also works, but multiplying can handle the more general cases in else if below
if (mul1) {
// Fold * 2 into the Mul expression
int mulVal = (castConstant(mul1->left) * 2) % 65536; // any number times 65536 overflows
if (mulVal == 0) result = buildConstant(0);
else result = builder->Mul(buildConstant(mulVal), mul1->right);
} else {
result = builder->Mul(buildConstant(2), op1);
}
} else if ((mul1 && mul1->right == op2) || (mul2 && mul2->right == op1)) {
// Fold OP2 into OP1 or vice versa
auto op = (mul1 && mul1->right == op2) ? mul1 : mul2; // the Mul expression
int mulVal = (castConstant(op->left) + 1) % 65536; // any number times 65536 overflows
if (mulVal == 0) result = buildConstant(0);
else result = builder->Mul(buildConstant(mulVal), op->right);
} else if (mul1 && mul2 && mul1->right == mul2->right) {
// Combine OP1 and OP2
int mulVal = (castConstant(mul1->left) + castConstant(mul2->left)) % 65536;
if (mulVal == 0) result = buildConstant(0);
else result = builder->Mul(buildConstant(mulVal), mul1->right);
} else {
result = builder->Add(op1, op2); // note: not masking 0xFFFF for now
}
setReg(s, dr, result, ir);
setCC(s, dr, ir);
}
void Executor::executeAND(State *s, const ref<InstValue> &ir) {
Reg dr = ir->dr();
// Here we don't use getReg(), since we don't want to give warning when AND an uninitialized reg with 0
ref<Expr> op1 = s->getReg(ir->sr1());
ref<Expr> op2 = (ir->instDef().format == InstValue::FMT_RRR ?
s->getReg(ir->sr2()) :
static_cast<ref<Expr>>(buildConstant(ir->imm5())));
if (op1.isNull()) {
// NOTE: without optimization like constant folding, it's still possible that op2 must be zero under some
// constraints, but this case is ignored since it is not obvious and should be avoided
if (op2.isNull() || !op2->isZero()) {
if (!ir->belongsToOS) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) ir->sr1()) + ".\n");
}
setReg(s, ir->sr1(), 0, ir); // write back to warning only once
}
}
}
if (op2.isNull()) {
if (op1.isNull() || !op1->isZero()) {
if (!ir->belongsToOS) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) ir->sr2()) + ".\n");
}
setReg(s, ir->sr2(), 0, ir); // write back to warning only once
}
}
}
if (op1.isNull()) op1 = buildConstant(0);
if (op2.isNull()) op2 = buildConstant(0);
ref<Expr> result = builder->And(op1, op2);
setReg(s, dr, result, ir);
setCC(s, dr, ir);
}
void Executor::executeNOT(State *s, const ref<InstValue> &ir) {
Reg DR = ir->dr();
setReg(s, DR, builder->Not(getReg(s, ir->sr1(), ir)), ir);
setCC(s, DR, ir);
}
void Executor::executeLEA(State *s, const ref<InstValue> &ir) {
Reg DR = ir->dr();
setReg(s, DR, s->getPC() + ir->imm9(), ir); // note: not masking 0xFFFF for now
setCC(s, DR, ir);
}
void Executor::executeJSR(State *s, const ref<InstValue> &ir) {
setReg(s, R_R7, s->getPC(), ir);
setReg(s, R_PC, s->getPC() + ir->imm11(), ir); // auto wrap 0xFFFF
}
void Executor::executeTRAP(State *s, const ref<InstValue> &ir) {
if (ir->sourceContent == "INSTANT_HALT") {
s->status = State::HALTED;
return;
}
setReg(s, R_R7, s->getPC(), ir);
ref<Expr> newPC;
memReadData(s, ir->vec8(), newPC, ir, -1); // the vector table given by LC3OS must be constant
if (s->status != State::NORMAL) return;
setReg(s, R_PC, castConstant(newPC), ir);
}
Issue::Type Executor::memReadData(State *s, uint16_t addr, ref<Expr> &result, const ref<InstValue> &ir, int dr) const {
Issue::Type ret = Issue::NO_ISSUE;
ref<MemValue> value = s->mem.read(addr);
if (value.isNull()) { // this is nullptr MemValue, which means the memory is never wrote
if (auto issueInfo = s->newStateIssue(Issue::WARN_POSSIBLE_WILD_READ, ir)) {
issueInfo->setNote("reading addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_POSSIBLE_WILD_READ;
}
// State status is set by newStateIssue
result = buildConstant(0); // upper level no longer need to handle null value
} else {
if (value->type == MemValue::MEM_DATA && dyn_cast<DataValue>(value)->forWrite) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_READ_UNINITIALIZED_MEMORY, ir)) {
issueInfo->setNote("reading addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_READ_UNINITIALIZED_MEMORY;
}
// State status is set by newStateIssue
} else if (value->type == MemValue::MEM_INST) {
// InstValue *inst = dyn_cast<InstValue>(value);
if (auto issueInfo = s->newStateIssue(Issue::WARN_READ_INST_AS_DATA, ir)) {
issueInfo->setNote("reading addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_READ_INST_AS_DATA;
}
// State status is set by newStateIssue
}
if (value->e.isNull()) { // this is the nullptr value, while the MemValue is not nullptr
if (s->memStoringUninitReg.find(addr) != s->memStoringUninitReg.end()) {
if (dr != -1 &&
dr == s->memStoringUninitReg[addr].first) { // loading data into original register
result = nullptr; // still store nullptr back
} else {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote(
"Using value of: R" + llvm::Twine(s->memStoringUninitReg[addr].first) + "\n" +
" Stored uninitialized reg value into memory at: " +
reportFormatter->formattedContext(s->memStoringUninitReg[addr].second) + ".\n");
ret = Issue::WARN_USE_UNINITIALIZED_REGISTER;
}
// State status is set by newStateIssue
s->memStoringUninitReg.erase(addr); // one warning is enough
result = buildConstant(0); // upper level no longer need to handle null value
}
} else { // otherwise, the warning may have been already generated
result = buildConstant(0); // upper level no longer need to handle null value
}
} else {
result = value->e;
}
}
return ret;
}
Issue::Type Executor::memWriteData(State *s, uint16_t addr, const ref<Expr> &value, const ref<InstValue> &ir) {
Issue::Type ret = Issue::NO_ISSUE;
ref<MemValue> oldVal = s->mem.read(addr);
if (oldVal.isNull()) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_POSSIBLE_WILD_WRITE, ir)) {
issueInfo->setNote("writing to unspecified addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_POSSIBLE_WILD_WRITE;
}
// State status is set by newStateIssue
} else {
if (oldVal->type == MemValue::MEM_DATA && dyn_cast<DataValue>(oldVal)->forRead) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_WRITE_READ_ONLY_DATA, ir)) {
issueInfo->setNote("overwriting read-only data at addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_WRITE_READ_ONLY_DATA;
}
// State status is set by newStateIssue
} else if (oldVal->type == MemValue::MEM_INST) {
// We don't allow overwriting inst since it makes changes to the flow graph
ref<InstValue> oldInst = dyn_cast<InstValue>(oldVal);
if (auto issueInfo = s->newStateIssue(Issue::ERR_OVERWRITE_INST, ir)) {
issueInfo->setNote("writing to addr " + toLC3Hex(addr) + ", original: " +
reportFormatter->formattedContext(oldInst) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
ret = Issue::ERR_OVERWRITE_INST;
return ret;
}
}
/**
* @note About WARN_READ_UNINITIALIZED_REGISTER at ST/STI/STR
* ST/STI/STR can be used to store registers. In that case we don't want to give warning immediately. And if the
* value is simply loaded back to the original register, we would consider these as the storing-loading registers
* and give no warning. But if the value stored into memory now is loaded into another register or used by other
* instructions, we will report WARN_READ_UNINITIALIZED_REGISTER at that time.
*
* This function memWriteData() is called only by ST/STI/STR, and null value of register will get passed through to
* here.
*/
if (value.isNull()) { // is storing uninitialized register into memory
s->memStoringUninitReg[addr] = {ir->sr(), ir}; // All ST/STR/STI are using ir->sr() field
// Continue to write nullptr into memory
} else {
if (s->memStoringUninitReg.find(addr) != s->memStoringUninitReg.end()) {
s->memStoringUninitReg.erase(addr); // no longer storing an uninitialized value
}
}
MemoryManager::WriteResult result = s->mem.writeData(addr, value);
switch (result) {
case MemoryManager::WRITE_SUCCESS:
return ret;
case MemoryManager::WRITE_HALT:
s->status = State::HALTED;
if (s->latestNonOSInst[0]->instID() != InstValue::TRAP) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_MANUAL_HALT, s->latestNonOSInst[0])) {
issueInfo->setNote("last executed instruction: " +
reportFormatter->formattedContext(s->latestNonOSInst[0]) + ".\n");
}
}
return ret;
case MemoryManager::WRITE_DDR:
if (value.isNull()) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
// Here I just don't border to report which register
ret = Issue::WARN_USE_UNINITIALIZED_REGISTER;
}
s->lc3Out.emplace_back(buildConstant(0));
} else {
s->lc3Out.push_back(value);
}
return ret;
default:
assert(!"Unknown return value from mem->writeData()");
}
}
ref<Expr> Executor::getReg(State *s, Reg r, const ref<InstValue> &ir, bool bypassUninitialized) {
ref<Expr> ret = s->getReg(r);
if (ret.isNull()) {
if (!bypassUninitialized) {
if (!ir->belongsToOS) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) r) + ".\n");
}
}
s->setReg(r, 0); // write back to warn only once, but do not change regChangeLocation
ret = buildConstant(0);
} // Otherwise, bypass the null value to upper level
}
return ret;
}
void Executor::setReg(State *s, Reg r, const ref<Expr> &value, const ref<InstValue> &ir) {
switch (r) {
case R_PC:
assert(value->getKind() == klee::Expr::Constant);
s->setPC(castConstant(value));
case R_IR:
s->setIR(value);
break;
default:
s->setReg(r, value);
break;
}
s->regChangeLocation[r] = ir;
}
void Executor::setReg(State *s, Reg r, uint16_t value, const ref<InstValue> &ir) {
switch (r) {
case R_PC:
s->setPC(value);
break;
case R_IR:
s->setIR(buildConstant(value));
break;
default:
s->setReg(r, value);
break;
}
s->regChangeLocation[r] = ir;
}
void Executor::setCC(State *s, Reg r, const ref<InstValue> &ir) {
s->setCC(r);
s->ccChangeLocation = ir;
}
ref<Expr> Executor::getCCExpr(State *s, const ref<InstValue> &ir) {
ref<Expr> ret = s->getCCExpr();
if (ret.isNull()) {
Reg r = s->getCCSrcReg();
if (r == NUM_REGS) {
s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_CC, ir);
} else {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) r) + " (through CC code).\n");
}
// Write back to warn only once, but do not change regChangeLocation and ccChangeLocation
s->setReg(r, 0);
s->setCC(r);
}
ret = buildConstant(0);
}
return ret;
}
}
| 37.269694
| 120
| 0.560501
|
liuzikai
|
7cbfc7ce81026348266e9ae8ec20990e911e02ea
| 13,300
|
cpp
|
C++
|
packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 10
|
2019-11-14T19:58:30.000Z
|
2021-04-04T17:44:09.000Z
|
packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 43
|
2020-03-03T19:59:20.000Z
|
2021-09-08T03:36:08.000Z
|
packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 6
|
2020-02-12T17:37:07.000Z
|
2020-09-08T18:59:51.000Z
|
//---------------------------------------------------------------------------//
//!
//! \file tstHDF5ArchiveTupleTypes.cpp
//! \author Alex Robinson
//! \brief HDF5 archive tuple type unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <sstream>
// FRENSIE Includes
#include "Utility_HDF5IArchive.hpp"
#include "Utility_HDF5OArchive.hpp"
#include "Utility_Tuple.hpp"
#include "Utility_ArrayView.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
//---------------------------------------------------------------------------//
// Template Types
//---------------------------------------------------------------------------//
typedef std::tuple<bool,
char, unsigned char, signed char,
short, unsigned short,
int, unsigned int,
long, unsigned long,
long long, unsigned long long,
float, double, long double> BasicTestTypes;
template<typename... Types>
struct PairTypes;
template<typename T, typename... Types>
struct PairTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::pair<T,T> >(), typename PairTypes<Types...>::type())) type;
};
template<typename T>
struct PairTypes<T>
{
typedef std::pair<T,T> type;
};
template<typename... Types>
struct PairTypes<std::tuple<Types...> > : public PairTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct OneElementTupleTypes;
template<typename T, typename... Types>
struct OneElementTupleTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::tuple<T> >(), typename OneElementTupleTypes<Types...>::type())) type;
};
template<typename T>
struct OneElementTupleTypes<T>
{
typedef std::tuple<std::tuple<T> > type;
};
template<typename... Types>
struct OneElementTupleTypes<std::tuple<Types...> > : public OneElementTupleTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct TwoElementTupleTypes;
template<typename T, typename... Types>
struct TwoElementTupleTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::tuple<T,T> >(), typename TwoElementTupleTypes<Types...>::type())) type;
};
template<typename T>
struct TwoElementTupleTypes<T>
{
typedef std::tuple<T,T> type;
};
template<typename... Types>
struct TwoElementTupleTypes<std::tuple<Types...> > : public TwoElementTupleTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct ThreeElementTupleTypes;
template<typename T, typename... Types>
struct ThreeElementTupleTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::tuple<T,T,T> >(), typename ThreeElementTupleTypes<Types...>::type())) type;
};
template<typename T>
struct ThreeElementTupleTypes<T>
{
typedef std::tuple<std::tuple<T,T,T> > type;
};
template<typename... Types>
struct ThreeElementTupleTypes<std::tuple<Types...> > : public ThreeElementTupleTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct MergeTypeLists;
template<typename T, typename... Types>
struct MergeTypeLists<T,Types...>
{
typedef decltype(std::tuple_cat( T(), typename MergeTypeLists<Types...>::type())) type;
};
template<typename T>
struct MergeTypeLists<T>
{
typedef T type;
};
typedef typename MergeTypeLists<typename PairTypes<BasicTestTypes>::type,typename OneElementTupleTypes<BasicTestTypes>::type,typename TwoElementTupleTypes<BasicTestTypes>::type,typename ThreeElementTupleTypes<BasicTestTypes>::type>::type BasicTupleTestTypes;
//---------------------------------------------------------------------------//
// Testing functions
//---------------------------------------------------------------------------//
template<typename T>
inline T zero( T )
{ return T(0); }
template<typename T1, typename T2>
inline std::pair<T1,T2> zero( std::pair<T1,T2> )
{
return std::make_pair( zero<T1>( T1() ), zero<T2>( T2() ) );
}
template<typename... Types>
inline std::tuple<Types...> zero( std::tuple<Types...> )
{
return std::make_tuple( zero<Types>( Types() )... );
}
template<typename T>
inline T one( T )
{ return T(1); }
template<typename T1, typename T2>
inline std::pair<T1,T2> one( std::pair<T1,T2> )
{
return std::make_pair( one<T1>( T1() ), one<T2>( T2() ) );
}
template<typename... Types>
inline std::tuple<Types...> one( std::tuple<Types...> )
{
return std::make_tuple( one<Types>( Types() )... );
}
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Check that tuple composed of basic types can be archived
FRENSIE_UNIT_TEST_TEMPLATE( HDF5Archive,
archive_tuple_basic_types,
BasicTupleTestTypes )
{
FETCH_TEMPLATE_PARAM( 0, T );
std::string archive_name( "test_tuple_basic_types.h5a" );
const T tuple_a = zero(T());
const T tuple_b = one(T());
const T array_a[8] = {one(T()), one(T()), one(T()), one(T()), one(T()), one(T()), one(T()), one(T())};
const T array_b[2][3] = {{one(T()), one(T()), one(T())},{one(T()), one(T()), one(T())}};
std::array<T,10> array_c;
array_c.fill( one(T()) );
{
Utility::HDF5OArchive archive( archive_name, Utility::HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_a", tuple_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_b", tuple_b ) );
// Array optimization should be used with this type
FRENSIE_REQUIRE( Utility::HDF5OArchive::use_array_optimization::apply<T>::type::value );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_a", array_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_b", array_b ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_c", array_c ) );
}
{
Utility::HDF5IArchive archive( archive_name );
T extracted_tuple;
T extracted_array_a[8];
T extracted_array_b[2][3];
std::array<T,10> extracted_array_c;
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_a", extracted_tuple ) );
FRENSIE_CHECK_EQUAL( extracted_tuple, tuple_a );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_b", extracted_tuple ) );
FRENSIE_CHECK_EQUAL( extracted_tuple, tuple_b );
// Array optimization should be used with this type
FRENSIE_REQUIRE( Utility::HDF5IArchive::use_array_optimization::apply<T>::type::value );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_a", extracted_array_a ) );
FRENSIE_CHECK_EQUAL( Utility::ArrayView<const T>( array_a, array_a+8 ),
Utility::ArrayView<const T>( extracted_array_a, extracted_array_a+8 ) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_b", extracted_array_b ) );
FRENSIE_CHECK_EQUAL( Utility::ArrayView<const T>( &array_b[0][0], &array_b[0][0]+6 ),
Utility::ArrayView<const T>( &extracted_array_b[0][0], &extracted_array_b[0][0]+6 ) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_c", extracted_array_c ) );
FRENSIE_CHECK_EQUAL( array_c, extracted_array_c );
}
}
//---------------------------------------------------------------------------//
// Check that tuple composed of advanced types can be archived
FRENSIE_UNIT_TEST_TEMPLATE( HDF5Archive,
archive_tuple_advanced_types,
BasicTestTypes )
{
FETCH_TEMPLATE_PARAM( 0, T );
std::string archive_name( "test_tuple_advanced_types.h5a" );
const std::pair<T,std::string> pair_a =
std::make_pair( one(T()), std::string("Test message a") );
const std::pair<std::string,T> pair_b =
std::make_pair( std::string("Test message b"), one(T()) );
const std::pair<std::string,std::string> pair_c =
std::make_pair( std::string("Test message c-0"), std::string("Test message c-1") );
const std::tuple<T,std::string> tuple_a =
std::make_tuple( one(T()), std::string("Test message a") );
const std::tuple<std::string,T> tuple_b =
std::make_tuple( std::string("Test message b"), one(T()) );
const std::tuple<std::string,std::string> tuple_c =
std::make_tuple( std::string("Test message c-0"), std::string("Test message c-1") );
const std::pair<T,std::string> array_a[2][3] =
{{std::make_pair(one(T()), std::string("Test message a-00")),
std::make_pair(one(T()), std::string("Test message a-01")),
std::make_pair(one(T()), std::string("Test message a-02"))},
{std::make_pair(zero(T()), std::string("Test message a-10")),
std::make_pair(zero(T()), std::string("Test message a-11")),
std::make_pair(zero(T()), std::string("Test message a-12"))}};
const std::tuple<std::string,T> array_b[6] =
{std::make_tuple(std::string("Test message b-00"), zero(T())),
std::make_tuple(std::string("Test message b-01"), zero(T())),
std::make_tuple(std::string("Test message b-02"), zero(T())),
std::make_tuple(std::string("Test message b-10"), one(T())),
std::make_tuple(std::string("Test message b-11"), one(T())),
std::make_tuple(std::string("Test message b-12"), one(T()))};
{
Utility::HDF5OArchive archive( archive_name, Utility::HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_a", pair_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_b", pair_b ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_c", pair_c ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_a", tuple_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_b", tuple_b ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_c", tuple_c ) );
// Array optimization should be used with these types
FRENSIE_REQUIRE( (Utility::HDF5OArchive::use_array_optimization::apply<std::pair<T,std::string> >::type::value) );
FRENSIE_REQUIRE( (Utility::HDF5OArchive::use_array_optimization::apply<std::tuple<std::string,T> >::type::value) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_a", array_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_b", array_b ) );
}
{
Utility::HDF5IArchive archive( archive_name );
std::pair<T,std::string> extracted_pair_a;
std::pair<std::string,T> extracted_pair_b;
std::pair<std::string,std::string> extracted_pair_c;
std::tuple<T,std::string> extracted_tuple_a;
std::tuple<std::string,T> extracted_tuple_b;
std::tuple<std::string,std::string> extracted_tuple_c;
std::pair<T,std::string> extracted_array_a[2][3];
std::tuple<std::string,T> extracted_array_b[6];
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_a", extracted_pair_a ) );
FRENSIE_CHECK_EQUAL( extracted_pair_a, pair_a );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_b", extracted_pair_b ) );
FRENSIE_CHECK_EQUAL( extracted_pair_b, pair_b );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_c", extracted_pair_c ) );
FRENSIE_CHECK_EQUAL( extracted_pair_c, pair_c );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_a", extracted_tuple_a ) );
FRENSIE_CHECK_EQUAL( extracted_tuple_a, tuple_a );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_b", extracted_tuple_b ) );
FRENSIE_CHECK_EQUAL( extracted_tuple_b, tuple_b );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_c", extracted_tuple_c ) );
FRENSIE_CHECK_EQUAL( extracted_tuple_c, tuple_c );
// Array optimization should not be used with these types
FRENSIE_REQUIRE( (Utility::HDF5IArchive::use_array_optimization::apply<std::pair<T,std::string> >::type::value) );
FRENSIE_REQUIRE( (Utility::HDF5IArchive::use_array_optimization::apply<std::tuple<std::string,T> >::type::value) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_a", extracted_array_a ) );
FRENSIE_CHECK_EQUAL( (Utility::ArrayView<const std::pair<T,std::string> >( &array_a[0][0], &array_a[0][0]+6 )),
(Utility::ArrayView<const std::pair<T,std::string> >( &extracted_array_a[0][0], &extracted_array_a[0][0]+6 )) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_b", extracted_array_b ) );
FRENSIE_CHECK_EQUAL( (Utility::ArrayView<const std::tuple<std::string,T> >( array_b, array_b+6 )),
(Utility::ArrayView<const std::tuple<std::string,T> >( extracted_array_b, extracted_array_b+6 )) );
}
}
//---------------------------------------------------------------------------//
// end tstHDF5ArchiveTupleTypes.cpp
//---------------------------------------------------------------------------//
| 40.060241
| 258
| 0.635338
|
bam241
|
7cc25b5cc7f475ba8cd715a85093f9e839f362d0
| 15,286
|
cpp
|
C++
|
src/src/tests/suites/mutation_test_bad.cpp
|
geneial/geneial
|
5e525c32b7c1e1e88788644e448e9234c93b55e2
|
[
"MIT"
] | 5
|
2015-08-25T15:40:09.000Z
|
2020-03-15T19:33:22.000Z
|
src/src/tests/suites/mutation_test_bad.cpp
|
geneial/geneial
|
5e525c32b7c1e1e88788644e448e9234c93b55e2
|
[
"MIT"
] | null | null | null |
src/src/tests/suites/mutation_test_bad.cpp
|
geneial/geneial
|
5e525c32b7c1e1e88788644e448e9234c93b55e2
|
[
"MIT"
] | 3
|
2019-01-24T13:14:51.000Z
|
2022-01-03T07:30:20.000Z
|
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE operations/mutation
#include <boost/test/unit_test.hpp>
#include <geneial/algorithm/BaseGeneticAlgorithm.h>
#include <geneial/core/fitness/Fitness.h>
#include <geneial/core/fitness/FitnessEvaluator.h>
#include <geneial/core/population/PopulationSettings.h>
#include <geneial/core/population/builder/ContinousMultiValueBuilderSettings.h>
#include <geneial/core/population/builder/ContinousMultiValueChromosomeFactory.h>
#include <geneial/core/operations/mutation/MutationSettings.h>
#include <geneial/core/operations/mutation/NonUniformMutationOperation.h>
#include <geneial/core/operations/mutation/UniformMutationOperation.h>
#include <geneial/core/operations/choosing/ChooseRandom.h>
#include "mocks/MockFitnessEvaluator.h"
#include <memory>
using namespace geneial;
using namespace geneial::population::management;
using namespace geneial::operation::choosing;
using namespace geneial::operation::mutation;
using namespace test_mock;
BOOST_AUTO_TEST_SUITE( TESTSUITE_UniformMutationOperation )
//TODO (bewo): Separate Uniform and Nonuniform into separate testcases
//TODO (bewo): Use more mock objects / helper here to avoid tedious duplicate gluecode?
BOOST_AUTO_TEST_CASE( UNIFORM_TEST__basicMutation )
{
/*
* 100% Chance of mutation
* Tests if Chromosomes are actually mutated
*
* Test for Uniform and NonUniform Mutation
*/
MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>());
ContinousMultiValueBuilderSettings<int, double> builderSettings (evaluator, 10, 130, 0, true, 20, 5);
ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory(builderSettings);
BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory));
BOOST_TEST_MESSAGE("Checking Mutation at 100% probability");
for (double i = 0; i <= 1; i = i + 0.1)
{
MutationSettings mutationSettings(1, i, 0);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform(1000,
0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform (mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(
BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform;
inputSet.push_back(_newChromosome);
resultSet_NonUniform.push_back(_newChromosome);
resultSet_Uniform.push_back(_newChromosome);
resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager);
resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager);
BOOST_TEST_MESSAGE("Checking at amount of Mutation = "<< i);
BOOST_CHECK(inputSet != resultSet_NonUniform);
BOOST_CHECK(inputSet != resultSet_Uniform);
}
// BOOST_TEST_MESSAGE ("");
// BOOST_TEST_MESSAGE ("Checking Mutation at 0% probability");
for (double i = 0; i <= 1; i = i + 0.1)
{
MutationSettings mutationSettings(0, i, 0);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform (1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform (mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(
BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform;
inputSet.push_back(_newChromosome);
resultSet_NonUniform.push_back(_newChromosome);
resultSet_Uniform.push_back(_newChromosome);
resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager);
resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager);
BOOST_TEST_MESSAGE("Checking at amount of Mutation = "<< i);
BOOST_CHECK(inputSet == resultSet_NonUniform);
BOOST_CHECK(inputSet == resultSet_Uniform);
}
}
BOOST_AUTO_TEST_CASE( UNIFORM_TEST__Mutation_probability )
{
/*
* Testing Mutation probability for 10000 Testcases
* Checking UNIFOM and NONUNIFORM mutation
*
*/
MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>());
ContinousMultiValueBuilderSettings<int, double> builderSettings(evaluator, 10, 130, 0, true, 20, 5);
ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory(builderSettings);
BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory));
//TODO (bewo): Constantify magic numbers...
for (double probability = 0.0; probability <= 1.0; probability = probability + 0.1)
{
// BaseChromosome<double>::ptr _newChromosome = chromosomeFactory->createChromosome(true);
// BaseMutationOperation<double>::mutation_result_set inputSet;
// BaseMutationOperation<double>::mutation_result_set resultSet[10000];
MutationSettings mutationSettings(probability, 1, 5);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform(1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform(mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform[10000];
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform[10000];
inputSet.push_back(_newChromosome);
int mutationCounter_NonUniform = 0;
int mutationCounter_Uniform = 0;
for (int i = 0; i < 10000; i++)
{
resultSet_NonUniform[i].push_back(_newChromosome);
resultSet_NonUniform[i] = mutationOperation_NonUniform.doMutate(inputSet, manager);
if (inputSet != resultSet_NonUniform[i])
{
mutationCounter_NonUniform++;
}
resultSet_Uniform[i].push_back(_newChromosome);
resultSet_Uniform[i] = mutationOperation_Uniform.doMutate(inputSet, manager);
if (inputSet != resultSet_Uniform[i])
{
mutationCounter_Uniform++;
}
}
if (probability < 0)
{
//Checking for NON-UNIFORM Mutation
BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform);
BOOST_CHECK(mutationCounter_NonUniform == 0);
//Checking for UNIFORM Mutation
BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform);
BOOST_CHECK(mutationCounter_Uniform == 0);
}
else if (probability > 1)
{
//Checking for NON-UNIFORM Mutation
BOOST_CHECK(mutationCounter_NonUniform = 10000);
BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform);
//Checking for UNIFORM Mutation
BOOST_CHECK(mutationCounter_Uniform = 10000);
BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform);
}
else
{
//Checking for NON-UNIFORM Mutation
BOOST_CHECK(mutationCounter_NonUniform > (10000 * probability - 200));
BOOST_CHECK(mutationCounter_NonUniform < (10000 * probability + 200));
BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform);
//Checking for UNIFORM Mutation
BOOST_CHECK(mutationCounter_Uniform > (10000 * probability - 200));
BOOST_CHECK(mutationCounter_Uniform < (10000 * probability + 200));
BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform);
}
}
}
BOOST_AUTO_TEST_CASE ( UNIFORM_TEST__points_of_mutation )
{
/*
* Checking if as many points are mutated as set in Mutation settings
*/
MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>());
ContinousMultiValueBuilderSettings<int, double> builderSettings (evaluator, 100, 130, 0, true, 20, 5);
ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory (builderSettings);
BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory));
for (unsigned int pointsOfMutation = 0; pointsOfMutation <= 102; pointsOfMutation++)
{
MutationSettings mutationSettings(1, 1, pointsOfMutation);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform (1000,
0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform(mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(
BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform;
inputSet.push_back(_newChromosome);
resultSet_NonUniform.push_back(_newChromosome);
resultSet_Uniform.push_back(_newChromosome);
resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager);
resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager);
//getting Chromosome from resultSet:
MultiValueChromosome<int, double>::ptr mvcMutant_NonUniform = std::dynamic_pointer_cast<
MultiValueChromosome<int, double> >(*resultSet_NonUniform.begin());
MultiValueChromosome<int, double>::ptr mvcMutant_Uniform = std::dynamic_pointer_cast<
MultiValueChromosome<int, double> >(*resultSet_Uniform.begin());
MultiValueChromosome<int, double>::ptr mvcOriginal = std::dynamic_pointer_cast<
MultiValueChromosome<int, double> >(*inputSet.begin());
//getting ValueContainer from Chromosome:
MultiValueChromosome<int, double>::value_container &mvcMutant_NonUniform_valueContainer =
mvcMutant_NonUniform->getContainer();
MultiValueChromosome<int, double>::value_container &mvcMutant_Uniform_valueContainer =
mvcMutant_Uniform->getContainer();
MultiValueChromosome<int, double>::value_container &mvcOriginal_valueContainer = mvcOriginal->getContainer();
//setting Iterators
MultiValueChromosome<int, double>::value_container::iterator original_it = mvcOriginal_valueContainer.begin();
unsigned int nunUniformdiffCounter = 0;
for (MultiValueChromosome<int, double>::value_container::iterator nonUniformMutant_it =
mvcMutant_NonUniform_valueContainer.begin();
nonUniformMutant_it != mvcMutant_NonUniform_valueContainer.end(); ++nonUniformMutant_it)
{
//BOOST_TEST_MESSAGE(original_it);
if (*original_it != *nonUniformMutant_it)
{
nunUniformdiffCounter++;
}
++original_it;
}
BOOST_TEST_MESSAGE("");
BOOST_TEST_MESSAGE(
"Check if as many points were Mutated as specified in MutationSettings: "<< pointsOfMutation);
BOOST_TEST_MESSAGE("NON-UNIFORM: "<< nunUniformdiffCounter);
if (pointsOfMutation != 0)
{
BOOST_CHECK(
(nunUniformdiffCounter <= pointsOfMutation + 5 && pointsOfMutation <= 100)
|| (nunUniformdiffCounter <= 100 && pointsOfMutation > 100));
}
else
{
BOOST_CHECK(nunUniformdiffCounter >= 90);
}
unsigned int uniformdiffCounter = 0;
original_it = mvcOriginal_valueContainer.begin();
for (MultiValueChromosome<int, double>::value_container::iterator uniformMutant_it =
mvcMutant_Uniform_valueContainer.begin(); uniformMutant_it != mvcMutant_Uniform_valueContainer.end();
++uniformMutant_it)
{
if (*original_it != *uniformMutant_it)
uniformdiffCounter++;
++original_it;
}
BOOST_TEST_MESSAGE("UNIFORM: "<< uniformdiffCounter);
if (pointsOfMutation != 0)
{
BOOST_CHECK(
(uniformdiffCounter <= pointsOfMutation + 5 && pointsOfMutation <= 100)
|| (uniformdiffCounter <= 100 && pointsOfMutation > 100));
}
else
{
BOOST_CHECK(uniformdiffCounter >= 90);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE( TESTSUITE_SmoothingMutation )
//Checks whether the smoothing mutation destroys chromosome's smoothness
BOOST_AUTO_TEST_CASE ( SMOOTHING_TEST__ensure_nonviolated_smoothness )
{
}
//Test whether mutation generates values above/below minmax
BOOST_AUTO_TEST_CASE ( SMOOTHING_TEST__ensure_adherence_min_max )
{
}
//Test Peak at chromosome borders.
BOOST_AUTO_TEST_SUITE_END()
| 45.766467
| 171
| 0.715753
|
geneial
|
7cc4d6366a91a8a61ad3decd9b770103ff9db9c1
| 172
|
cpp
|
C++
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
#include <touchgfx/hal/Types.hpp>
FONT_LOCATION_FLASH_PRAGMA
KEEP extern const uint8_t unicodes_Asap_Regular_13_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = {
0 // No glyphs
};
| 24.571429
| 91
| 0.819767
|
ramkumarkoppu
|
7cc6263b91af91347ca89106b29f0e127c9f61b6
| 2,524
|
cpp
|
C++
|
windows/cpp/samples/CameraToDVD/MuxedStream.cpp
|
dvdbuilder/dvdbuilder-samples
|
8d2b472bd0af899fa342437bb41b33ef8603e0aa
|
[
"MIT"
] | null | null | null |
windows/cpp/samples/CameraToDVD/MuxedStream.cpp
|
dvdbuilder/dvdbuilder-samples
|
8d2b472bd0af899fa342437bb41b33ef8603e0aa
|
[
"MIT"
] | null | null | null |
windows/cpp/samples/CameraToDVD/MuxedStream.cpp
|
dvdbuilder/dvdbuilder-samples
|
8d2b472bd0af899fa342437bb41b33ef8603e0aa
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "MuxedStream.h"
using namespace primo::dvdbuilder::VR;
MuxedStreamCB::MuxedStreamCB()
{
filename[0] = L'\0';
file = NULL;
MainWindow = NULL;
Reset();
}
MuxedStreamCB::~MuxedStreamCB()
{
Reset();
}
void MuxedStreamCB::Reset()
{
if (file)
{
fclose(file);
file = NULL;
}
writeCounter = 0;
pVideoRecorder = NULL;
bProcess = true;
}
bool MuxedStreamCB::WriteData(uint8_t *pBuf, uint32_t bufSize)
{
if (!bProcess)
return false;
++writeCounter;
bool fileResult = true;
if (file)
{
size_t size = fwrite(pBuf,1,bufSize,file);
fileResult = (size == bufSize);
}
bool dvdResult = true;
int stopReason = -1;
if (pVideoRecorder && !pVideoRecorder->write(pBuf, bufSize))
{
ATLTRACE(L"VideoRecorder::Write() failed");
DumpErrorState(pVideoRecorder);
int activeCount, failedCount, noSpaceCount;
CheckRecorderDevices(pVideoRecorder, &activeCount, &failedCount, &noSpaceCount);
ATLASSERT((activeCount + failedCount + noSpaceCount) == pVideoRecorder->devices()->count());
if (0 == activeCount)
{
dvdResult = false;
if (0 == failedCount && noSpaceCount > 0)
stopReason = -2;
}
}
if (fileResult && dvdResult)
return true;
//STOP_CAPTURE
PostMessage(MainWindow, WM_STOP_CAPTURE, stopReason, 0);
bProcess = false;
return false;
}
bool MuxedStreamCB::SetOutputFile(PCWSTR filename)
{
if (file)
{
fclose(file);
file = NULL;
}
if (!filename)
{
this->filename[0] = L'\0';
return true;
}
wcscpy_s(this->filename,256, filename);
file = _wfopen(this->filename, L"wb");
return file != NULL;
}
// primo::Stream
bool_t MuxedStreamCB::open()
{
return TRUE;
}
void MuxedStreamCB::close()
{
}
bool_t MuxedStreamCB::isOpen() const
{
return TRUE;
}
bool_t MuxedStreamCB::canRead() const
{
return FALSE;
}
bool_t MuxedStreamCB::canWrite() const
{
return TRUE;
}
bool_t MuxedStreamCB::canSeek() const
{
return FALSE;
}
bool_t MuxedStreamCB::read(void* buffer, int32_t bufferSize, int32_t* totalRead)
{
return FALSE;
}
bool_t MuxedStreamCB::write(const void* buffer, int32_t dataSize)
{
return WriteData((uint8_t*)buffer, dataSize);
}
int64_t MuxedStreamCB::size() const
{
return -1;
}
int64_t MuxedStreamCB::position() const
{
return -1;
}
bool_t MuxedStreamCB::seek(int64_t position)
{
return FALSE;
}
| 16.496732
| 95
| 0.633914
|
dvdbuilder
|
7cc88522847226392bd3715ead508683b3047088
| 1,666
|
cc
|
C++
|
PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.cc
|
pasmuss/cmssw
|
566f40c323beef46134485a45ea53349f59ae534
|
[
"Apache-2.0"
] | null | null | null |
PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.cc
|
pasmuss/cmssw
|
566f40c323beef46134485a45ea53349f59ae534
|
[
"Apache-2.0"
] | null | null | null |
PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.cc
|
pasmuss/cmssw
|
566f40c323beef46134485a45ea53349f59ae534
|
[
"Apache-2.0"
] | null | null | null |
#include "PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "PhysicsTools/CandUtils/interface/Thrust.h"
EventShapeVarsProducer::EventShapeVarsProducer(const edm::ParameterSet& cfg)
{
srcToken_ = consumes<edm::View<reco::Candidate> >(cfg.getParameter<edm::InputTag>("src"));
r_ = cfg.exists("r") ? cfg.getParameter<double>("r") : 2.;
produces<double>("thrust");
//produces<double>("oblateness");
produces<double>("isotropy");
produces<double>("circularity");
produces<double>("sphericity");
produces<double>("aplanarity");
produces<double>("C");
produces<double>("D");
}
void put(edm::Event& evt, double value, const char* instanceName)
{
evt.put(std::make_unique<double>(value), instanceName);
}
void EventShapeVarsProducer::produce(edm::Event& evt, const edm::EventSetup&)
{
//std::cout << "<EventShapeVarsProducer::produce>:" << std::endl;
edm::Handle<edm::View<reco::Candidate> > objects;
evt.getByToken(srcToken_, objects);
Thrust thrustAlgo(objects->begin(), objects->end());
put(evt, thrustAlgo.thrust(), "thrust");
//put(evt, thrustAlgo.oblateness(), "oblateness");
EventShapeVariables eventShapeVarsAlgo(*objects);
put(evt, eventShapeVarsAlgo.isotropy(), "isotropy");
put(evt, eventShapeVarsAlgo.circularity(), "circularity");
put(evt, eventShapeVarsAlgo.sphericity(r_), "sphericity");
put(evt, eventShapeVarsAlgo.aplanarity(r_), "aplanarity");
put(evt, eventShapeVarsAlgo.C(r_), "C");
put(evt, eventShapeVarsAlgo.D(r_), "D");
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(EventShapeVarsProducer);
| 32.666667
| 92
| 0.728091
|
pasmuss
|
7ccab8672dba2e6cc86748ba2213e2e6c7a12468
| 2,115
|
hpp
|
C++
|
src/mbgl/renderer/bucket.hpp
|
zxlee618/mapbox-gl-native
|
04c70f55a534ca7cb4bb5358da3217329643a0f0
|
[
"BSL-1.0",
"Apache-2.0"
] | 6
|
2019-06-17T05:41:03.000Z
|
2022-01-20T13:16:14.000Z
|
src/mbgl/renderer/bucket.hpp
|
zxlee618/mapbox-gl-native
|
04c70f55a534ca7cb4bb5358da3217329643a0f0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
src/mbgl/renderer/bucket.hpp
|
zxlee618/mapbox-gl-native
|
04c70f55a534ca7cb4bb5358da3217329643a0f0
|
[
"BSL-1.0",
"Apache-2.0"
] | 4
|
2019-08-30T07:40:17.000Z
|
2022-01-13T09:36:55.000Z
|
#pragma once
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
#include <mbgl/style/layer_type.hpp>
#include <mbgl/style/image_impl.hpp>
#include <mbgl/renderer/image_atlas.hpp>
#include <atomic>
namespace mbgl {
namespace gl {
class Context;
} // namespace gl
class RenderLayer;
class PatternDependency;
using PatternLayerMap = std::unordered_map<std::string, PatternDependency>;
class Bucket : private util::noncopyable {
public:
Bucket(style::LayerType layerType_)
: layerType(layerType_) {
}
virtual ~Bucket() = default;
// Check whether this bucket is of the given subtype.
template <class T>
bool is() const;
// Dynamically cast this bucket to the given subtype.
template <class T>
T* as() {
return is<T>() ? reinterpret_cast<T*>(this) : nullptr;
}
template <class T>
const T* as() const {
return is<T>() ? reinterpret_cast<const T*>(this) : nullptr;
}
// Feature geometries are also used to populate the feature index.
// Obtaining these is a costly operation, so we do it only once, and
// pass-by-const-ref the geometries as a second parameter.
virtual void addFeature(const GeometryTileFeature&,
const GeometryCollection&,
const ImagePositions&,
const PatternLayerMap&) {};
virtual void populateFeatureBuffers(const ImagePositions&) {};
virtual void addPatternDependencies(const std::vector<const RenderLayer*>&, ImageDependencies&) {};
// As long as this bucket has a Prepare render pass, this function is getting called. Typically,
// this only happens once when the bucket is being rendered for the first time.
virtual void upload(gl::Context&) = 0;
virtual bool hasData() const = 0;
virtual float getQueryRadius(const RenderLayer&) const {
return 0;
};
bool needsUpload() const {
return hasData() && !uploaded;
}
protected:
style::LayerType layerType;
std::atomic<bool> uploaded { false };
};
} // namespace mbgl
| 28.581081
| 103
| 0.665248
|
zxlee618
|
7ccf6d8cd7e5457a4ff6c7e03c2a5a56cf69237e
| 809
|
cpp
|
C++
|
q206-Reverse-Linked-List-recursive-optimized.cpp
|
risyomei/leetcode
|
bd0eba2d31eca48c182fc328fab02aac61c15366
|
[
"MIT"
] | null | null | null |
q206-Reverse-Linked-List-recursive-optimized.cpp
|
risyomei/leetcode
|
bd0eba2d31eca48c182fc328fab02aac61c15366
|
[
"MIT"
] | null | null | null |
q206-Reverse-Linked-List-recursive-optimized.cpp
|
risyomei/leetcode
|
bd0eba2d31eca48c182fc328fab02aac61c15366
|
[
"MIT"
] | null | null | null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL){
return NULL;
}
if(head -> next == NULL) {
return head;
}
// Cache p in recursive stack
ListNode* p = head;
// Always return t, as that's the last node.
ListNode *t = reverseList(head->next);
// Reverse
p -> next -> next = p;
p -> next = NULL;
return t;
}
};
| 22.472222
| 62
| 0.454883
|
risyomei
|
7cd2b544adf16108232c989a22345f250bc5d1f6
| 4,440
|
cpp
|
C++
|
src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp
|
erinloy/GraphEngine
|
1a913c18043192c597d48e0b4e77b0a62cd6a10e
|
[
"MIT"
] | 370
|
2019-05-08T07:40:52.000Z
|
2022-03-28T15:29:18.000Z
|
src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp
|
qingzhu521/GraphEngine
|
56d98c09b8e9a55b4397823f20cf29263c8857b5
|
[
"MIT"
] | 55
|
2019-05-20T09:01:48.000Z
|
2022-03-31T23:05:23.000Z
|
src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp
|
qingzhu521/GraphEngine
|
56d98c09b8e9a55b4397823f20cf29263c8857b5
|
[
"MIT"
] | 83
|
2019-05-15T14:16:23.000Z
|
2022-03-06T07:04:10.000Z
|
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "Storage/MTHash/MTHash.h"
#include "Storage/MemoryTrunk/MemoryTrunk.h"
using namespace Trinity::IO;
namespace Storage
{
bool MTHash::Save(const String& output_file)
{
BinaryWriter bw(output_file);
bool success = true;
success = success && bw.Write((char)VERSION); // 1B
success = success && bw.Write(ExtendedInfo->NonEmptyEntryCount); // 4B
success = success && bw.Write(ExtendedInfo->FreeEntryCount); // 4B
success = success && bw.Write(ExtendedInfo->FreeEntryList); // 4B
success = success && bw.Write(BucketCount); // 4B
success = success && bw.Write(ExtendedInfo->EntryCount); // 4B
int32_t mtentry_array_length = (int32_t)ExtendedInfo->EntryCount * szMTEntry();
int32_t cellentry_array_length = (int32_t)ExtendedInfo->EntryCount * szCellEntry();
int32_t bucket_array_length = (int32_t)BucketCount * szBucket();
// Write buckets array
success = success && bw.Write((char*)Buckets, 0, bucket_array_length); // note here we write more
// Write entry array
char* buff = new char[cellentry_array_length];
memcpy(buff, CellEntries, cellentry_array_length);
#pragma region Modify the offset in the entries
char* p = buff;
if (memory_trunk->committed_tail < memory_trunk->head.committed_head ||
(memory_trunk->committed_tail == memory_trunk->head.committed_head && memory_trunk->committed_tail == 0)
)//one segment
{
CellEntry* entryPtr = (CellEntry*)p;
CellEntry* entryEndPtr = entryPtr + ExtendedInfo->NonEmptyEntryCount;
for (; entryPtr != entryEndPtr; ++entryPtr)
{
if (entryPtr->offset > 0 && entryPtr->size > 0)
{
entryPtr->offset -= (int32_t)memory_trunk->committed_tail;
}
}
}
else//two segments
{
CellEntry* entryPtr = (CellEntry*)p;
CellEntry* entryEndPtr = entryPtr + ExtendedInfo->NonEmptyEntryCount;
for (; entryPtr != entryEndPtr; ++entryPtr)
{
if (entryPtr->offset >= (int32_t)memory_trunk->head.committed_head && entryPtr->size > 0)
{
entryPtr->offset -=
((int32_t)memory_trunk->committed_tail - (int32_t)memory_trunk->head.append_head);
}
}
}
#pragma endregion
success = success && bw.Write(buff, 0, cellentry_array_length);
delete[] buff;
success = success && bw.Write((char*)MTEntries, 0, mtentry_array_length);
return success;
}
bool MTHash::Reload(const String& input_file)
{
BinaryReader br(input_file);
if (!br.Good())
return false;
DeallocateMTHash();
/*********** Read meta data ************/
int32_t version = (int32_t)br.ReadChar();
if (version != VERSION)
{
Trinity::Diagnostics::FatalError("The Trinity disk image version does not match.");
}
ExtendedInfo->NonEmptyEntryCount = br.ReadInt32();
ExtendedInfo->FreeEntryCount = br.ReadInt32();
ExtendedInfo->FreeEntryList = br.ReadInt32();
if (BucketCount != br.ReadUInt32())
{
Trinity::Diagnostics::FatalError("The Trinity disk image is invalid.");
}
ExtendedInfo->EntryCount = br.ReadUInt32();
int32_t mtentry_array_length = (int32_t)ExtendedInfo->EntryCount * szMTEntry();
int32_t cellentry_array_length = (int32_t)ExtendedInfo->EntryCount * szCellEntry();
int32_t bucket_array_length = (int32_t)BucketCount * szBucket();
/////////////////////////////////////////////////////////
AllocateMTHash();
bool read_success = true;
read_success = read_success && br.Read((char*)Buckets, 0, bucket_array_length);
read_success = read_success && br.Read((char*)CellEntries, 0, cellentry_array_length);
read_success = read_success && br.Read((char*)MTEntries, 0, mtentry_array_length);
return read_success;
}
}
| 38.608696
| 116
| 0.592568
|
erinloy
|
7cd6712e6afe46868512b116b3c323f376e8e193
| 2,240
|
cpp
|
C++
|
code/engine.vc2008/xrGame/items/WeaponDispersion.cpp
|
Rikoshet-234/xray-oxygen
|
eaac3fa4780639152684f3251b8b4452abb8e439
|
[
"Apache-2.0"
] | 7
|
2018-03-27T12:36:07.000Z
|
2020-06-26T11:31:52.000Z
|
code/engine.vc2008/xrGame/items/WeaponDispersion.cpp
|
Rikoshet-234/xray-oxygen
|
eaac3fa4780639152684f3251b8b4452abb8e439
|
[
"Apache-2.0"
] | 2
|
2018-05-26T23:17:14.000Z
|
2019-04-14T18:33:27.000Z
|
code/engine.vc2008/xrGame/items/WeaponDispersion.cpp
|
Rikoshet-234/xray-oxygen
|
eaac3fa4780639152684f3251b8b4452abb8e439
|
[
"Apache-2.0"
] | 3
|
2019-10-20T19:35:34.000Z
|
2022-02-28T01:42:10.000Z
|
// WeaponDispersion.cpp: разбос при стрельбе
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "items/Weapon.h"
#include "inventoryowner.h"
#include "actor.h"
#include "inventory_item_impl.h"
#include "actoreffector.h"
#include "effectorshot.h"
//возвращает 1, если оружие в отличном состоянии и >1 если повреждено
float CWeapon::GetConditionDispersionFactor() const
{
return (1.f + fireDispersionConditionFactor*(1.f-GetCondition()));
}
float CWeapon::GetFireDispersion (bool with_cartridge, bool for_crosshair)
{
if (!with_cartridge) return GetFireDispersion(1.0f, for_crosshair);
if (!m_magazine.empty()) m_fCurrentCartirdgeDisp = m_magazine.back().param_s.kDisp;
return GetFireDispersion (m_fCurrentCartirdgeDisp, for_crosshair);
}
float CWeapon::GetBaseDispersion(float cartridge_k)
{
return fireDispersionBase * cur_silencer_koef.fire_dispersion * cartridge_k * GetConditionDispersionFactor();
}
//текущая дисперсия (в радианах) оружия с учетом используемого патрона
float CWeapon::GetFireDispersion (float cartridge_k, bool for_crosshair)
{
//учет базовой дисперсии, состояние оружия и влияение патрона
float fire_disp = GetBaseDispersion(cartridge_k);
//вычислить дисперсию, вносимую самим стрелком
if(H_Parent())
{
const CInventoryOwner* pOwner = smart_cast<const CInventoryOwner*>(H_Parent());
float parent_disp = pOwner->GetWeaponAccuracy();
fire_disp += parent_disp;
}
return fire_disp;
}
//////////////////////////////////////////////////////////////////////////
// Для эффекта отдачи оружия
void CWeapon::AddShotEffector ()
{
inventory_owner().on_weapon_shot_start (this);
}
void CWeapon::RemoveShotEffector ()
{
CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent());
if (pInventoryOwner)
pInventoryOwner->on_weapon_shot_remove (this);
}
void CWeapon::ClearShotEffector ()
{
CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent());
if (pInventoryOwner)
pInventoryOwner->on_weapon_hide (this);
}
void CWeapon::StopShotEffector ()
{
CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent());
if (pInventoryOwner)
pInventoryOwner->on_weapon_shot_stop();
}
| 28.35443
| 110
| 0.725446
|
Rikoshet-234
|
7cd69f6f66570ee16e0dfc4a00208ac3e4fce49a
| 1,924
|
cpp
|
C++
|
Algorithms/Implementation/The_Bomberman_Game/main.cpp
|
ugurcan-sonmez-95/HackerRank_Problems
|
187d83422128228c241f279096386df5493d539d
|
[
"MIT"
] | null | null | null |
Algorithms/Implementation/The_Bomberman_Game/main.cpp
|
ugurcan-sonmez-95/HackerRank_Problems
|
187d83422128228c241f279096386df5493d539d
|
[
"MIT"
] | null | null | null |
Algorithms/Implementation/The_Bomberman_Game/main.cpp
|
ugurcan-sonmez-95/HackerRank_Problems
|
187d83422128228c241f279096386df5493d539d
|
[
"MIT"
] | null | null | null |
// The Bomberman Game - Solution
#include <iostream>
#include <vector>
std::vector<std::string> bomberMan(const int r, const int c, const int n, const std::vector<std::string> &grid) {
std::vector<std::string> finalGrid1 = grid, finalGrid2, finalGrid3;
for (int i{}; i < r; i++)
for (int j{}; j < c; j++)
finalGrid1[i][j] = 'O';
finalGrid3 = finalGrid2 = finalGrid1;
for (int k{}; k < r; k++) {
for (int l{}; l < c; l++) {
if (grid[k][l] == 'O') {
finalGrid2[k][l] = '.';
if (k > 0)
finalGrid2[k-1][l] = '.';
if (l > 0)
finalGrid2[k][l-1] = '.';
if (l < c-1)
finalGrid2[k][l+1] = '.';
if (k < r-1)
finalGrid2[k+1][l] = '.';
}
}
}
for (int m{}; m < r; m++) {
for (int p{}; p < c; p++) {
if (finalGrid2[m][p] == 'O') {
finalGrid3[m][p] = '.';
if (m > 0)
finalGrid3[m-1][p] = '.';
if (p > 0)
finalGrid3[m][p-1] = '.';
if (p < c-1)
finalGrid3[m][p+1] = '.';
if (m < r-1)
finalGrid3[m+1][p] = '.';
}
}
}
if (n == 1 || n == 0)
return grid;
if (n % 2 == 0)
return finalGrid1;
if (n % 4 == 3)
return finalGrid2;
return finalGrid3;
}
int main() {
int r, c, n;
std::cin >> r >> c >> n;
std::vector<std::string> grid(r);
char ch;
for (int i{}; i < r; i++) {
for (int j{}; j < c; j++) {
std::cin >> ch;
grid[i].push_back(ch);
}
}
const std::vector<std::string> result = bomberMan(r, c, n, grid);
for (auto &el: result)
std::cout << el << '\n';
return 0;
}
| 28.716418
| 113
| 0.37526
|
ugurcan-sonmez-95
|
7cd798d6286c3458b708f1391f6a55e9c9d78390
| 27,815
|
hpp
|
C++
|
common/cmdline.hpp
|
Mainvooid/common
|
fd8f966ba283cb8df619166b41c76fb0cfc6a4c7
|
[
"MIT"
] | null | null | null |
common/cmdline.hpp
|
Mainvooid/common
|
fd8f966ba283cb8df619166b41c76fb0cfc6a4c7
|
[
"MIT"
] | null | null | null |
common/cmdline.hpp
|
Mainvooid/common
|
fd8f966ba283cb8df619166b41c76fb0cfc6a4c7
|
[
"MIT"
] | null | null | null |
/*
@brief a simple command line parser
@author guobao.v@gmail.com
*/
#ifndef _COMMON_CMDLINE_HPP_
#define _COMMON_CMDLINE_HPP_
#include <common/precomm.hpp>
#include <algorithm>
#ifdef __GNUC__
#include <cxxabi.h>
#endif
/**
@addtogroup common
@{
@defgroup cmdline cmdline - command line parser
@{
@defgroup detail detail
@}
@}
*/
namespace common {
/// @addtogroup common
/// @{
namespace cmdline {
/// @addtogroup cmdline
/// @{
static const std::string _TAG = "cmdline";
namespace detail {
/// @addtogroup detail
/// @{
/**
*@brief 获取类型
*/
static inline std::string demangle(const std::string &name) noexcept
{
#ifdef _MSC_VER
return name;
#elif defined(__GNUC__)
int status = 0;
char *p = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
std::string ret(p);
free(p);
return ret;
#else
#error unexpected c complier (msc/gcc), Need to implement this method for demangle
#endif
}
/**
*@brief 获取类型
*/
template <typename T>
std::string readable_typename() noexcept
{
return demangle(typeid(T).name());
}
template <>
inline std::string readable_typename<std::string>() noexcept { return "string"; }
template <>
inline std::string readable_typename<std::wstring>() noexcept { return "wstring"; }
/**
*@brief T -> string
*/
template <typename T>
std::string default_value(T def) noexcept
{
return convert_to_string<char>(def);
}
/// @}
} // detail --------------------------------------------------
/**
*@brief 模块异常类
*/
class[[deprecated("unnecessary")]]cmdline_error : public std::exception
{
public:
cmdline_error(const std::string msg) : m_msg(std::move(msg)) {}
~cmdline_error() {}
const char *what() const { return m_msg.c_str(); }
private:
std::string m_msg;
};
/**
*@brief string -> T
*/
template <typename T>
class default_reader
{
public:
T operator()(const std::string &str) noexcept(false)
{
return convert_from_string<T>(str);
}
};
/**
*@brief 参数范围检查器
*/
template <typename T>
class range_reader
{
public:
range_reader(const T &low, const T &high) : m_low(low), m_high(high) {}
T operator()(const std::string &s) const noexcept(false)
{
T ret = default_reader<T>()(s);
if (!(ret >= m_low && ret <= m_high)) {
std::ostringstream msg;
msg << _TAG << "..range error";
throw std::range_error(msg.str());
}
return ret;
}
private:
T m_low, m_high;
};
/**
*@brief 返回一个参数范围检查器
*/
template <typename T>
range_reader<T> range(const T &low, const T &high) noexcept
{
return range_reader<T>(low, high);
}
/**
*@brief 可选值检查器
*/
template <typename T>
class oneof_reader
{
public:
oneof_reader() {}
oneof_reader(const std::initializer_list<T> &list) noexcept
{
for (T item : list) {
m_values.push_back(item);
}
}
template <typename ...Values>
oneof_reader(const T& v, const Values&...vs) noexcept
{
add(v, vs...);
}
T operator=(const std::initializer_list<T> &list) noexcept
{
for (T item : list) {
m_values.push_back(item);
}
};
T operator()(const std::string &s) noexcept(false)
{
T ret = default_reader<T>()(s);
if (std::find(m_values.begin(), m_values.end(), ret) == m_values.end()) {
std::ostringstream msg;
msg << _TAG << "..oneof error";
throw std::invalid_argument(msg.str());
}
return ret;
}
template <typename ...Values>
void add(const T& v, const Values&...vs) noexcept
{
m_values.push_back(v);
add(vs...);
}
private:
void add(const T& v) noexcept
{
m_values.push_back(v);
}
private:
std::vector<T> m_values;
};
/**
*@brief 返回一个可选值检查器
*/
template <typename T, typename ...Values>
oneof_reader<T> oneof(const T& a1, const Values&... a2) noexcept
{
return oneof_reader<T>(a1, a2...);
}
/**
*@brief 返回一个可选值检查器
*/
template <typename T>
oneof_reader<T> oneof(const std::initializer_list<T> &list) noexcept
{
return oneof_reader<T>(list);
}
/**
*@brief 命令行解析类
*/
class parser
{
public:
parser() {}
~parser()
{
for (std::map<std::string, option_base*>::iterator p = options.begin(); p != options.end(); p++) {
delete_s(p->second);
}
}
/**
*@brief 添加指定类型的参数
*@param name 长名称
*@param short_name 短名称(\0:表示没有短名称)
*@param desc 描述
*/
void add(const std::string &name, char short_name = 0, const std::string &desc = "") noexcept(false)
{
if (options.count(name)) {
std::ostringstream msg;
msg << _TAG << "..multiple definition:" << name;
throw std::invalid_argument(msg.str());
}
options[name] = new option_without_value(name, short_name, desc);
ordered.push_back(options[name]);
}
/**
*@brief 添加指定类型的参数
*@param name 长名称
*@param short_name 短名称(\0:表示没有短名称)
*@param desc 描述
*@param need 是否必需(可选)
*@param def 默认值(可选,当不必需时使用)
*/
template <typename T>
void add(const std::string &name, char short_name = 0, const std::string &desc = "",
bool need = true, const T def = T()) noexcept(false)
{
add(name, short_name, desc, need, def, default_reader<T>());
}
/**
*@brief 添加指定类型的参数
*@param name 长名称
*@param short_name 短名称(\0:表示没有短名称)
*@param desc 描述
*@param need 是否必需(可选)
*@param def 默认值(可选,当不必需时使用)
*@param reader 解析类型
*/
template <class T, class F>
void add(const std::string &name, char short_name = 0, const std::string &desc = "",
bool need = true, const T def = T(), F reader = F()) noexcept(false)
{
if (options.count(name)) {
std::ostringstream msg;
msg << _TAG << "..multiple definition:" << name;
throw std::invalid_argument(msg.str());
}
options[name] = new option_with_value_with_reader<T, F>(name, short_name, need, def, desc, reader);
ordered.push_back(options[name]);
}
/**
*@brief usage尾部添加说明(如果需要解析未指定参数)
*@param f 补充说明
*/
void footer(std::string f) noexcept { ftr = std::move(f); }
/**
*@brief 设置usage程序名,默认由argv[0]确定
*@param name usage程序名
*/
void set_program_name(std::string name) noexcept { prog_name = std::move(name); }
/**
*@brief 判断bool参数是否被指定
*@param name bool参数名
*/
bool exist(const std::string &name) const noexcept(false)
{
if (options.count(name) == 0) {
std::ostringstream msg;
msg << _TAG << "..there is no flag: --" << name;
throw std::invalid_argument(msg.str());
}
return options.find(name)->second->has_set();
}
/**
*@brief 获取参数的值
*@param name 参数名
*@return 返回相应类型参数值
*/
template <class T>
const T &get(const std::string &name) const noexcept(false)
{
if (options.count(name) == 0) {
std::ostringstream msg;
msg << _TAG << "..there is no flag: --" << name;
throw std::invalid_argument(msg.str());
}
const option_with_value<T> *p = dynamic_cast<const option_with_value<T>*>(options.find(name)->second);
if (p == nullptr) {
std::ostringstream msg;
msg << _TAG << "..type mismatch flag '" << name << "'";
throw std::invalid_argument(msg.str());
}
return p->get();
}
/**
*@brief 获取未指定的参数的值
*/
const std::vector<std::string> &rest() const noexcept { return others; }
/**
*@brief 解析一行命令
*@param arg 参数
*@return 是否解析成功
*/
bool parse(const std::string &arg) noexcept
{
std::vector<std::string> args;
std::string buf;
bool in_quote = false;//是否有""
for (std::string::size_type i = 0; i < arg.length(); i++) {
if (arg[i] == '\"') {
in_quote = !in_quote;
continue;
}
if (arg[i] == ' ' && !in_quote) {
args.push_back(buf);
buf = "";
continue;
}
if (arg[i] == '\\') { //跳过'\'
i++;
if (i >= arg.length()) {
errors.push_back("unexpected occurrence of '\\' at end of string");
return false;
}
}
buf += arg[i];
}
if (in_quote) {
errors.push_back("quote is not closed");
return false;
}
if (buf.length() > 0) {
args.push_back(buf);
}
for (size_t i = 0; i < args.size(); i++) {
std::cout << "\"" << args[i] << "\"" << std::endl;
}
return parse(args);
}
/**
*@brief 解析参数数组
*@param args 参数数组
*@return 是否解析成功
*/
bool parse(const std::vector<std::string> &args) noexcept
{
int argc = static_cast<int>(args.size());
std::vector<const char*> argv(argc);
for (int i = 0; i < argc; i++) {
argv[i] = args[i].c_str();
}
return parse(argc, &argv[0]);
}
/**
*@brief 解析参数数组
*@param argc 参数数量(+程序名)
*@param argv 参数值([0]为程序名)
*@return 是否解析成功
*/
bool parse(int argc, const char * const argv[]) noexcept
{
errors.clear();
others.clear();
if (argc < 1) {
errors.push_back("argument number must be bigger than 0");
return false;
}
if (prog_name == "") { prog_name = argv[0]; }
std::map<char, std::string> lookup;
for (std::map<std::string, option_base*>::iterator p = options.begin(); p != options.end(); p++) {
if (p->first.length() == 0) {
continue;//key不存在
}
char initial = p->second->short_name();
if (initial) {
if (lookup.count(initial) > 0) {
lookup[initial] = "";
errors.push_back(std::string("short option '") + initial + "' is ambiguous");
return false;
}
else {
lookup[initial] = p->first;
}
}
}
for (int i = 1; i < argc; i++) {
if (strncmp(argv[i], "--", 2) == 0) {//长名称
const char *p = strchr(argv[i] + 2, '=');
if (p) {
std::string name(argv[i] + 2, p);
std::string val(p + 1);
set_option(name, val);
}
else {
std::string name(argv[i] + 2);
if (options.count(name) == 0) {
errors.push_back("undefined option: --" + name);
continue;
}
if (options[name]->has_value()) {
if (i + 1 >= argc) {
errors.push_back("option needs value: --" + name);
continue;
}
else {
i++;
set_option(name, argv[i]);
}
}
else {
set_option(name); //bool
}
}
}
else if (strncmp(argv[i], "-", 1) == 0) {//短名称
if (!argv[i][1]) {//若'-'后无值
continue;
}
char last = argv[i][1];
for (int j = 2; argv[i][j]; j++) {
last = argv[i][j];
if (lookup.count(argv[i][j - 1]) == 0) {
errors.push_back(std::string("undefined short option: -") + argv[i][j - 1]);
continue;
}
if (lookup[argv[i][j - 1]] == "") {
errors.push_back(std::string("ambiguous short option: -") + argv[i][j - 1]);
continue;
}
set_option(lookup[argv[i][j - 1]]);
}
if (lookup.count(last) == 0) {
errors.push_back(std::string("undefined short option: -") + last);
continue;
}
if (lookup[last] == "") {
errors.push_back(std::string("ambiguous short option: -") + last);
continue;
}
if (i + 1 < argc && options[lookup[last]]->has_value()) {
set_option(lookup[last], argv[i + 1]);
i++;
}
else {
set_option(lookup[last]);
}
}
else {
others.push_back(argv[i]);
}
}
for (std::map<std::string, option_base*>::iterator p = options.begin(); p != options.end(); p++) {
if (!p->second->valid()) {
errors.push_back("need option: --" + std::string(p->first));
}
}
return errors.size() == 0;
}
/**
*@brief 包装parse并做检查
*@param arg 一行命令
*/
void parse_check(const std::string &arg) noexcept(false)
{
if (!options.count("help")) {
add("help", '?', "print this message");
}
check(0, parse(arg));
}
/**
*@brief 包装parse并做检查
*@param args 参数数组
*/
void parse_check(const std::vector<std::string> &args) noexcept(false)
{
if (!options.count("help")) {
add("help", '?', "print this message");
}
check(args.size(), parse(args));
}
/**
*@brief 运行解析器(包装parse并做检查)
*@param argc 参数数量(+程序名)
*@param argv 参数值([0]为程序名)
*@note 仅当命令行参数有效时才返回
如果参数无效,解析器输出错误消息然后退出程序
如果指定了help flag('-help'或'-?')或空命令,则解析器输出用法消息然后退出程序
*/
void parse_check(int argc, char *argv[]) noexcept(false)
{
if (!options.count("help")) {
add("help", '?', "print this message");
}
check(argc, parse(argc, argv));
}
/**
*@brief 返回第一条错误消息
*/
std::string error() const { return errors.size() > 0 ? errors[0] : ""; }
/**
*@brief 返回所有错误消息
*/
std::string error_full() const noexcept
{
std::ostringstream oss;
for (size_t i = 0; i < errors.size(); i++) {
oss << errors[i] << std::endl;
}
return oss.str();
}
/**
*@brief 返回使用方法说明
*/
std::string usage() const noexcept
{
std::ostringstream oss;
oss << "usage: " << prog_name << " ";
for (size_t i = 0; i < ordered.size(); i++) {
if (ordered[i]->must()) {
oss << ordered[i]->short_description() << " ";
}
}
oss << "[options] ... " << ftr << std::endl;
oss << "options:" << std::endl;
size_t max_width = 0;
for (size_t i = 0; i < ordered.size(); i++) {
max_width = std::max(max_width, ordered[i]->name().length());
}
for (size_t i = 0; i < ordered.size(); i++) {
if (ordered[i]->short_name()) {
oss << " -" << ordered[i]->short_name() << ", ";
}
else {
oss << " ";
}
oss << "--" << ordered[i]->name();
for (size_t j = ordered[i]->name().length(); j < max_width + 4; j++) {
oss << ' ';
}
oss << ordered[i]->description() << std::endl;
}
return oss.str();
}
private:
/**
*@brief parse检查
*@param argc 参数数量
*@param ok 是否解析成功
*/
void check(size_t argc, bool ok) noexcept
{
if ((argc == 1 && !ok) || exist("help")) {
std::cerr << usage();
exit(0);
}
if (!ok) {
std::cerr << error() << std::endl << usage();
exit(1);
}
}
/**
*@brief 设置参数选项
*@param name 参数名
*/
void set_option(const std::string &name) noexcept
{
if (options.count(name) == 0) {
errors.push_back("undefined option: --" + name);
return;
}
if (!options[name]->set()) {
errors.push_back("option needs value: --" + name);
return;
}
}
/**
*@brief 设置参数选项
*@param name 参数名
*@param value 参数值
*/
void set_option(const std::string &name, const std::string &value) noexcept {
if (options.count(name) == 0) {
errors.push_back("undefined option: --" + name);
return;
}
if (!options[name]->set(value)) {
errors.push_back("option value is invalid: --" + name + "=" + value);
return;
}
}
/**
*@brief 参数选项基础接口类
*/
class option_base {
public:
virtual ~option_base() {}
virtual bool has_value() const = 0;
virtual bool set() = 0;
virtual bool set(const std::string &value) = 0;
virtual bool has_set() const = 0;
virtual bool valid() const = 0;
virtual bool must() const = 0;
virtual const std::string &name() const = 0;
virtual char short_name() const = 0;
virtual const std::string &description() const = 0;
virtual std::string short_description() const = 0;
};
/**
*@brief 参数选项派生类(无值参数:bool)
*/
class option_without_value : public option_base {
public:
option_without_value(const std::string &name, char short_name, const std::string &desc)
:m_name(name), m_short_name(short_name), m_desc(desc), m_has(false) {}
~option_without_value() {}
bool has_value() const noexcept { return false; }
bool set() noexcept { m_has = true; return true; }
bool set(const std::string &) noexcept { return false; }
bool has_set() const noexcept { return m_has; }
bool valid() const noexcept { return true; }
bool must() const noexcept { return false; }
const std::string &name() const noexcept { return m_name; }
char short_name() const noexcept { return m_short_name; }
const std::string &description() const noexcept { return m_desc; }
std::string short_description() const noexcept { return "--" + m_name; }
private:
std::string m_name;
char m_short_name;
std::string m_desc;
bool m_has;
};
/**
*@brief 参数选项派生类(有值参数)
*/
template <class T>
class option_with_value : public option_base {
public:
/**
*@brief 参数选项派生类(有值参数)
*@param name 长名称
*@param short_name 短名称
*@param need 是否必需
*@param def 默认值
*@param desc 描述
*/
option_with_value(const std::string &name, char short_name, bool need, const T &def, const std::string &desc)
: m_name(name), m_short_name(short_name), m_need(need), m_has(false), m_def(def), m_actual(def)
{
this->desc = full_description(desc);
}
~option_with_value() {}
const T &get() const { return m_actual; }
bool has_value() const { return true; }
bool set() { return false; }
bool set(const std::string &value) noexcept
{
try {
m_actual = read(value);
m_has = true;
}
catch (const std::exception &) {
return false;
}
return true;
}
bool has_set() const { return m_has; }
bool valid() const { return (m_need && !m_has) ? false : true; }
bool must() const { return m_need; }
const std::string &name() const { return m_name; }
char short_name() const { return m_short_name; }
const std::string &description() const { return desc; }
std::string short_description() const noexcept
{
return "--" + m_name + "=" + detail::readable_typename<T>();
}
protected:
std::string full_description(const std::string &desc) noexcept
{
return
desc + " (" + detail::readable_typename<T>() +
(m_need ? "" : " [=" + detail::default_value<T>(m_def) + "]")
+ ")";
}
virtual T read(const std::string &s) = 0;
protected:
std::string m_name;
char m_short_name;
bool m_need;
std::string desc;
bool m_has;
T m_def;///< 默认值
T m_actual;///< 实际值
};
/**
*@brief 有值参数选项派生类
*/
template <class T, class F>
class option_with_value_with_reader : public option_with_value<T>
{
public:
/**
*@brief 有值参数选项派生类
*@param name 长名称
*@param short_name 短名称
*@param need 是否必需
*@param def 默认值
*@param desc 描述
*@param reader 可读包装类型string->T
*/
option_with_value_with_reader(const std::string &name,
char short_name,
bool need,
const T def,
const std::string &desc,
F reader)
: option_with_value<T>(name, short_name, need, def, desc), reader(reader) {}
private:
//string -> T
T read(const std::string &s) noexcept { return reader(s); }
private:
F reader;
};
private:
std::map<std::string, option_base*> options;///< 参数选项map(长名称,一个选项)
std::vector<option_base*> ordered; ///< 有序的参数选项(add时push)
std::string ftr; ///< usage尾部添加说明
std::string prog_name; ///< 程序名
std::vector<std::string> others; ///< 其他为指定参数
std::vector<std::string> errors; ///< 错误消息
};
/// @}
} // cmdline
/// @}
} // common
#endif // _COMMON_CMDLINE_HPP_
| 34.595771
| 125
| 0.39112
|
Mainvooid
|
7cd96b7b5d529d013f3d3766f874b5fdcbf4943c
| 196
|
cpp
|
C++
|
samplers/src/simple_sampler.cpp
|
ton/lightbox
|
d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb
|
[
"MIT"
] | null | null | null |
samplers/src/simple_sampler.cpp
|
ton/lightbox
|
d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb
|
[
"MIT"
] | null | null | null |
samplers/src/simple_sampler.cpp
|
ton/lightbox
|
d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb
|
[
"MIT"
] | null | null | null |
#include "samplers/itf/simple_sampler.h"
using namespace lb;
SimpleSampler::SimpleSampler(
const Point2d& upperLeft, const Point2d& bottomRight):
Sampler(upperLeft, bottomRight)
{
}
| 19.6
| 62
| 0.744898
|
ton
|
7cd9cb30ae181e4ce06afb3e9ea850af4f1ed71d
| 6,242
|
cc
|
C++
|
mysql-server/storage/ndb/plugin/ndb_schema_result_table.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/storage/ndb/plugin/ndb_schema_result_table.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/storage/ndb/plugin/ndb_schema_result_table.cc
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Implements the interface defined in
#include "storage/ndb/plugin/ndb_schema_result_table.h"
#include <sstream>
#include "storage/ndb/plugin/ndb_thd_ndb.h"
const std::string Ndb_schema_result_table::DB_NAME = "mysql";
const std::string Ndb_schema_result_table::TABLE_NAME = "ndb_schema_result";
const char *Ndb_schema_result_table::COL_NODEID = "nodeid";
const char *Ndb_schema_result_table::COL_SCHEMA_OP_ID = "schema_op_id";
const char *Ndb_schema_result_table::COL_PARTICIPANT_NODEID =
"participant_nodeid";
const char *Ndb_schema_result_table::COL_RESULT = "result";
const char *Ndb_schema_result_table::COL_MESSAGE = "message";
Ndb_schema_result_table::Ndb_schema_result_table(Thd_ndb *thd_ndb)
: Ndb_util_table(thd_ndb, DB_NAME, TABLE_NAME, true) {}
Ndb_schema_result_table::~Ndb_schema_result_table() {}
bool Ndb_schema_result_table::check_schema() const {
// nodeid
// unsigned int
if (!(check_column_exist(COL_NODEID) && check_column_unsigned(COL_NODEID))) {
return false;
}
// schema_op_id
// unsigned int
if (!(check_column_exist(COL_SCHEMA_OP_ID) &&
check_column_unsigned(COL_SCHEMA_OP_ID))) {
return false;
}
// participant_nodeid
// unsigned int
if (!(check_column_exist(COL_PARTICIPANT_NODEID) &&
check_column_unsigned(COL_PARTICIPANT_NODEID))) {
return false;
}
// Check that nodeid + schema_op_id + participant_nodeid is the primary key
if (!check_primary_key(
{COL_NODEID, COL_SCHEMA_OP_ID, COL_PARTICIPANT_NODEID})) {
return false;
}
// result
// unsigned int
if (!(check_column_exist(COL_RESULT) && check_column_unsigned(COL_RESULT))) {
return false;
}
// message
// varbinary, at least 255 bytes long
if (!(check_column_exist(COL_MESSAGE) &&
check_column_varbinary(COL_MESSAGE) &&
check_column_minlength(COL_MESSAGE, 255))) {
return false;
}
return true;
}
bool Ndb_schema_result_table::define_table_ndb(NdbDictionary::Table &new_table,
unsigned mysql_version) const {
// Allow later online add column
new_table.setForceVarPart(true);
// Allow table to be read+write also in single user mode
new_table.setSingleUserMode(NdbDictionary::Table::SingleUserModeReadWrite);
{
// nodeid UNSIGNED NOT NULL
NdbDictionary::Column col_nodeid(COL_NODEID);
col_nodeid.setType(NdbDictionary::Column::Unsigned);
col_nodeid.setNullable(false);
col_nodeid.setPrimaryKey(true);
if (!define_table_add_column(new_table, col_nodeid)) return false;
}
{
// schema_op_id UNSIGNED NOT NULL
NdbDictionary::Column col_schema_op_id(COL_SCHEMA_OP_ID);
col_schema_op_id.setType(NdbDictionary::Column::Unsigned);
col_schema_op_id.setNullable(false);
col_schema_op_id.setPrimaryKey(true);
if (!define_table_add_column(new_table, col_schema_op_id)) return false;
}
{
// participant_nodeid UNSIGNED NOT NULL
NdbDictionary::Column col_participant_nodeid(COL_PARTICIPANT_NODEID);
col_participant_nodeid.setType(NdbDictionary::Column::Unsigned);
col_participant_nodeid.setNullable(false);
col_participant_nodeid.setPrimaryKey(true);
if (!define_table_add_column(new_table, col_participant_nodeid))
return false;
}
{
// result UNSIGNED NOT NULL
NdbDictionary::Column col_result(COL_RESULT);
col_result.setType(NdbDictionary::Column::Unsigned);
col_result.setNullable(false);
if (!define_table_add_column(new_table, col_result)) return false;
}
{
// message VARBINARY(255) NOT NULL
NdbDictionary::Column col_message(COL_MESSAGE);
col_message.setType(NdbDictionary::Column::Varbinary);
col_message.setLength(255);
col_message.setNullable(false);
if (!define_table_add_column(new_table, col_message)) return false;
}
(void)mysql_version; // Only one version can be created
return true;
}
bool Ndb_schema_result_table::need_upgrade() const { return false; }
std::string Ndb_schema_result_table::define_table_dd() const {
std::stringstream ss;
ss << "CREATE TABLE " << db_name() << "." << table_name() << "(\n";
ss << "nodeid INT UNSIGNED NOT NULL,"
"schema_op_id INT UNSIGNED NOT NULL,"
"participant_nodeid INT UNSIGNED NOT NULL,"
"result INT UNSIGNED NOT NULL,"
"message VARBINARY(255) NOT NULL,"
"PRIMARY KEY(nodeid, schema_op_id, participant_nodeid)"
<< ") ENGINE=ndbcluster";
return ss.str();
}
bool Ndb_schema_result_table::drop_events_in_NDB() const {
// Drop the default event
if (!drop_event_in_NDB("REPL$mysql/ndb_schema_result")) return false;
return true;
}
void Ndb_schema_result_table::pack_message(const char *message, char *buf) {
pack_varbinary(Ndb_schema_result_table::COL_MESSAGE, message, buf);
}
std::string Ndb_schema_result_table::unpack_message(
const std::string &packed_message) {
if (!open()) {
return std::string("");
}
return unpack_varbinary(Ndb_schema_result_table::COL_MESSAGE,
packed_message.c_str());
}
| 34.10929
| 79
| 0.73422
|
silenc3502
|
7cdad3ebcc2bf57b9787e69f1a92a256c4646439
| 990
|
cpp
|
C++
|
engine/src/engine/core/layers_stack.cpp
|
DmitryK579/Tank-Assault
|
f20cee73fdaa1e1d34f24cc681d781a26a7311a1
|
[
"MIT"
] | null | null | null |
engine/src/engine/core/layers_stack.cpp
|
DmitryK579/Tank-Assault
|
f20cee73fdaa1e1d34f24cc681d781a26a7311a1
|
[
"MIT"
] | null | null | null |
engine/src/engine/core/layers_stack.cpp
|
DmitryK579/Tank-Assault
|
f20cee73fdaa1e1d34f24cc681d781a26a7311a1
|
[
"MIT"
] | 2
|
2021-12-16T13:04:18.000Z
|
2022-01-07T14:06:06.000Z
|
#include "pch.h"
#include "layers_stack.h"
engine::layers_stack::~layers_stack()
{
for(auto* layer : m_layers)
{
layer->on_detach();
delete layer;
}
}
void engine::layers_stack::push_layer(layer* layer)
{
m_layers.emplace(m_layers.begin() + m_layers_insert_index, layer);
m_layers_insert_index++;
layer->on_attach();
}
void engine::layers_stack::push_overlay(layer* overlay)
{
m_layers.emplace_back(overlay);
overlay->on_attach();
}
void engine::layers_stack::pop_layer(layer* layer)
{
auto it = std::find(m_layers.begin(), m_layers.end(), layer);
if(it != m_layers.begin() + m_layers_insert_index)
{
layer->on_detach();
m_layers.erase(it);
--m_layers_insert_index;
}
}
void engine::layers_stack::pop_overlay(layer* overlay)
{
auto it = std::find(m_layers.begin(), m_layers.end(), overlay);
if(it != m_layers.end())
{
overlay->on_detach();
m_layers.erase(it);
}
}
| 21.521739
| 70
| 0.638384
|
DmitryK579
|
7cdf425a0f02d64151bfcb78567242dbbd288976
| 431
|
hpp
|
C++
|
splayer_ios/splayer_ios/native/Person.hpp
|
biezhihua/splayer
|
82f5b160b30c2d99ba400f5b676dd23795e081c7
|
[
"Apache-2.0"
] | 4
|
2019-08-14T08:57:05.000Z
|
2019-11-16T18:22:23.000Z
|
splayer_ios/splayer_ios/native/Person.hpp
|
biezhihua/SPlayer
|
82f5b160b30c2d99ba400f5b676dd23795e081c7
|
[
"Apache-2.0"
] | null | null | null |
splayer_ios/splayer_ios/native/Person.hpp
|
biezhihua/SPlayer
|
82f5b160b30c2d99ba400f5b676dd23795e081c7
|
[
"Apache-2.0"
] | 1
|
2019-11-16T18:22:24.000Z
|
2019-11-16T18:22:24.000Z
|
#ifndef Person_hpp
#define Person_hpp
#include <stdio.h>
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
bool sex;
public:
//默认构造函数,相当于init
Person();
//带参数的构造函数,相当于带参数的init
Person(const char* name , const int age , const bool sex);
//析构函数,用来释放资源,相当于deinit
~Person();
//自我介绍
void introduceMySelf();
};
#endif /* Person_hpp */
| 13.903226
| 62
| 0.617169
|
biezhihua
|
7ce02368bf5c246ef5364a904b9f1feac6faefc4
| 1,855
|
cpp
|
C++
|
flashlight/dataset/ResampleDataset.cpp
|
josephmisiti/flashlight
|
a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273
|
[
"MIT"
] | 2
|
2020-12-27T18:38:44.000Z
|
2021-09-10T20:55:25.000Z
|
flashlight/dataset/ResampleDataset.cpp
|
josephmisiti/flashlight
|
a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273
|
[
"MIT"
] | null | null | null |
flashlight/dataset/ResampleDataset.cpp
|
josephmisiti/flashlight
|
a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273
|
[
"MIT"
] | null | null | null |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ResampleDataset.h"
#include <algorithm>
#include <numeric>
namespace {
std::vector<int64_t> makeIdentityPermutation(int64_t size) {
std::vector<int64_t> perm(size);
std::iota(perm.begin(), perm.end(), 0);
return perm;
}
std::vector<int64_t> makePermutationFromFn(
int64_t size,
const fl::Dataset::PermutationFunction& fn) {
FL_ASSERT(fn, "Permutation function shouldn't be a nullptr");
auto perm = makeIdentityPermutation(size);
std::transform(perm.begin(), perm.end(), perm.begin(), fn);
return perm;
}
} // namespace
namespace fl {
ResampleDataset::ResampleDataset(std::shared_ptr<const Dataset> dataset)
: ResampleDataset(dataset, makeIdentityPermutation(dataset->size())) {}
ResampleDataset::ResampleDataset(
std::shared_ptr<const Dataset> dataset,
std::vector<int64_t> resamplevec)
: dataset_(dataset) {
FL_ASSERT(dataset_, "Dataset shouldn't be a nullptr");
resample(std::move(resamplevec));
}
ResampleDataset::ResampleDataset(
std::shared_ptr<const Dataset> dataset,
const PermutationFunction& fn)
: ResampleDataset(dataset, makePermutationFromFn(dataset->size(), fn)) {}
void ResampleDataset::resample(std::vector<int64_t> resamplevec) {
FL_ASSERT(
size() == resamplevec.size(), "Incorrect vector size for `resample`");
resampleVec_ = std::move(resamplevec);
}
std::vector<af::array> ResampleDataset::get(const int64_t idx) const {
FL_ASSERT(
idx >= 0 && idx < size(),
"Invalid value of idx. idx should be in [0, size())");
return dataset_->get(resampleVec_[idx]);
}
int64_t ResampleDataset::size() const {
return dataset_->size();
}
} // namespace fl
| 27.279412
| 77
| 0.709434
|
josephmisiti
|
7ce095b7f6667f84a76d62e0e9023d433e372d20
| 7,051
|
cpp
|
C++
|
src/RSL/UnitTest/RslMigration/TestHarness/main.cpp
|
nkindberg/RSL
|
f5907fb694c00ebcc6d6ad54e72e9f8a9b66ff0a
|
[
"MIT"
] | 58
|
2018-03-21T09:55:08.000Z
|
2022-03-25T07:21:42.000Z
|
src/RSL/UnitTest/RslMigration/TestHarness/main.cpp
|
nkindberg/RSL
|
f5907fb694c00ebcc6d6ad54e72e9f8a9b66ff0a
|
[
"MIT"
] | 2
|
2019-01-29T05:56:48.000Z
|
2019-05-23T04:44:28.000Z
|
src/RSL/UnitTest/RslMigration/TestHarness/main.cpp
|
nkindberg/RSL
|
f5907fb694c00ebcc6d6ad54e72e9f8a9b66ff0a
|
[
"MIT"
] | 17
|
2018-03-21T12:10:47.000Z
|
2022-03-20T03:24:37.000Z
|
#define _WINSOCKAPI_
#include <windows.h>
#include <stdio.h>
#include <list>
#include "libfuncs.h"
#include "logging.h"
using namespace std;
using namespace RSLibImpl;
#define NUM_REPLICAS 5
#define MAX_CMD_LEN 256
char procTitles[NUM_REPLICAS][256];
volatile bool endTest;
volatile bool endTestCompleted;
bool StartProcess(char * programName, int replicaId, HANDLE *processHandlePtr)
{
_snprintf_s(procTitles[replicaId-1], MAX_CMD_LEN, "%s %d", programName, replicaId);
printf("%s\n", procTitles[replicaId-1]);
STARTUPINFOA startupInfo;
GetStartupInfoA(&startupInfo);
startupInfo.lpTitle = procTitles[replicaId-1];
PROCESS_INFORMATION processInfo;
if (!CreateProcessA(NULL,
procTitles[replicaId-1],
NULL, // no process security attributes
NULL, // no thread security attributes
FALSE, // inherit handles? no
CREATE_NEW_CONSOLE,
NULL, // no special environment
NULL, //directoryPath,
&startupInfo,
&processInfo)) {
return false;
}
*processHandlePtr = processInfo.hProcess;
CloseHandle(processInfo.hThread);
return true;
}
BOOL CtrlHandler(DWORD ctrlType)
{
if (ctrlType == CTRL_C_EVENT ||
ctrlType == CTRL_BREAK_EVENT)
{
endTest = true;
while (endTestCompleted == false)
{
Sleep(100);
}
}
return FALSE;
}
void ReadNextCommand(int *timeToWaitPtr, list<int> *membersPtr)
{
*timeToWaitPtr = 0;
membersPtr->clear();
char line[1024];
if (fgets(line, 1024, stdin) == NULL) {
return;
}
char *curPos = line, *nextPos;
long timeToWait = strtol(curPos, &nextPos, 10);
if (nextPos == curPos) {
return;
}
curPos = nextPos;
*timeToWaitPtr = (int) timeToWait;
for (;;) {
long memberId = strtol(curPos, &nextPos, 10);
if (nextPos == curPos) {
break;
}
curPos = nextPos;
membersPtr->push_back((int) memberId);
}
}
bool SetConfiguration(int configurationNumber, const list<int>& membersInNextConfiguration)
{
list<int>::const_iterator it;
printf("Setting configuration to:\n");
for (it = membersInNextConfiguration.begin();
it != membersInNextConfiguration.end();
++it) {
printf(" %d", *it);
}
printf("\n");
FILE *fp;
if (fopen_s(&fp, "members.txt", "w")) {
fprintf(stderr, "Could not open members.txt for writing.\n");
return false;
}
fprintf(fp, "%d\n%d\n", configurationNumber, (int)membersInNextConfiguration.size());
for (it = membersInNextConfiguration.begin();
it != membersInNextConfiguration.end();
++it) {
fprintf(fp, "%d\n", *it);
}
fclose(fp);
return true;
}
int GetLastReportedConfigurationNumber ()
{
FILE *fp;
if (fopen_s(&fp, "CurrentConfig.txt", "r")) {
return 0;
}
int lastReportedConfigurationNumber = 0;
fscanf_s(fp, "%d", &lastReportedConfigurationNumber);
fclose(fp);
return lastReportedConfigurationNumber;
}
int __cdecl main(int argc, char **argv)
{
char * programName = "RSLNetTest.exe";
if (argc == 2)
{
programName = argv[1];
}
if (GetFileAttributesA(programName) == INVALID_FILE_ATTRIBUTES)
{
printf("Program '%s' not found!\n", programName);
::ExitProcess(1);
}
if (Logger::Init(".\\") == FALSE)
{
printf("Logger::Init failed\n");
::ExitProcess(1);
}
system("cmd /c rmdir /s /q .\\data");
DeleteFileA("members.txt");
DeleteFileA("CurrentConfig.txt");
Sleep(1000);
int currentConfigurationNumber = 0;
int timeToWaitForConfigurationChange = 0;
list<int> membersInNextConfiguration;
printf("Type timeout and replica set:\n");
ReadNextCommand(&timeToWaitForConfigurationChange, &membersInNextConfiguration);
currentConfigurationNumber++;
SetConfiguration(currentConfigurationNumber, membersInNextConfiguration);
HANDLE processHandle[NUM_REPLICAS];
for (int processNumber = 0; processNumber < NUM_REPLICAS; ++processNumber) {
if (!StartProcess(programName, processNumber+1, &processHandle[processNumber])) {
fprintf(stderr, "ERROR - Could not start process #%d\n", processNumber+1);
return -1;
}
}
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE );
endTest = false;
endTestCompleted = false;
for (; endTest == false; ) {
DWORD waitResult = WaitForMultipleObjects(NUM_REPLICAS,
processHandle,
FALSE, // don't wait for all of them
1000); // time out after 1000 ms
if (waitResult < WAIT_OBJECT_0 + NUM_REPLICAS) {
int processNumber = waitResult - WAIT_OBJECT_0;
printf("Restarting server %d\n", processNumber+1);
CloseHandle(processHandle[processNumber]);
if (!StartProcess(programName, processNumber+1, &processHandle[processNumber])) {
fprintf(stderr, "ERROR - Could not start process #%d\n", processNumber+1);
break;
}
}
else if (waitResult == WAIT_TIMEOUT) {
--timeToWaitForConfigurationChange;
if (timeToWaitForConfigurationChange < 1) {
int lastReportedConfig = GetLastReportedConfigurationNumber();
if (currentConfigurationNumber != lastReportedConfig) {
fprintf(stderr, "ERROR - Configuration change failed (%d!=%d)!\n",
currentConfigurationNumber, lastReportedConfig);
break;
}
else {
printf("Configuration number check successful.\n");
}
if (membersInNextConfiguration.size() == 0) {
break;
}
ReadNextCommand(&timeToWaitForConfigurationChange, &membersInNextConfiguration);
if (membersInNextConfiguration.size() == 0)
{
break;
}
currentConfigurationNumber++;
if (!SetConfiguration(currentConfigurationNumber, membersInNextConfiguration)) {
break;
}
}
}
else {
printf("WARNING - Unexpected return value %d from WaitForMultipleObjects.\n", waitResult);
}
}
printf("Terminating all processes.\n");
for (int processNumber = 0; processNumber < NUM_REPLICAS; ++processNumber) {
TerminateProcess(processHandle[processNumber], 0);
CloseHandle(processHandle[processNumber]);
}
endTestCompleted = true;
printf("Test complete.\n");
return 0;
}
| 30.392241
| 102
| 0.584598
|
nkindberg
|
7ceae8a4f83a95e9ee841983fd42e6251bcedc57
| 8,606
|
hpp
|
C++
|
include/Mahi/Com/SocketSelector.hpp
|
chip5441/mahi-com
|
fc7efcc5d7e9ff995303bbc162e694f25f47d6dd
|
[
"MIT"
] | 1
|
2021-09-22T08:37:01.000Z
|
2021-09-22T08:37:01.000Z
|
include/Mahi/Com/SocketSelector.hpp
|
chip5441/mahi-com
|
fc7efcc5d7e9ff995303bbc162e694f25f47d6dd
|
[
"MIT"
] | 1
|
2020-11-16T04:05:47.000Z
|
2020-11-16T04:05:47.000Z
|
include/Mahi/Com/SocketSelector.hpp
|
chip5441/mahi-com
|
fc7efcc5d7e9ff995303bbc162e694f25f47d6dd
|
[
"MIT"
] | 2
|
2020-12-21T09:28:26.000Z
|
2021-09-17T03:08:19.000Z
|
// MIT License
//
// MEL - Mechatronics Engine & Library
// Copyright (c) 2019 Mechatronics and Haptic Interfaces Lab - Rice University
//
// 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.
//
// This particular source file includes code which has been adapted from the
// following open-source projects (all external licenses attached at bottom):
// SFML - Simple and Fast Multimedia Library
//
// Author(s): Evan Pezent (epezent@rice.edu)
#pragma once
#include <Mahi/Util/Timing/Time.hpp>
// #include <Mahi/Util.hpp>
namespace mahi {
namespace com {
class Socket;
/// Multiplexer that allows to read from multiple sockets
class SocketSelector {
public:
/// \brief Default constructor
SocketSelector();
/// \brief Copy constructor
///
/// \param copy Instance to copy
SocketSelector(const SocketSelector& copy);
/// \brief Destructor
~SocketSelector();
/// \brief Add a new socket to the selector
///
/// This function keeps a weak reference to the socket,
/// so you have to make sure that the socket is not destroyed
/// while it is stored in the selector.
/// This function does nothing if the socket is not valid.
///
/// \param socket Reference to the socket to add
///
/// \see remove, clear
void add(Socket& socket);
/// \brief Remove a socket from the selector
///
/// This function doesn't destroy the socket, it simply
/// removes the reference that the selector has to it.
///
/// \param socket Reference to the socket to remove
///
/// \see add, clear
void remove(Socket& socket);
/// \brief Remove all the sockets stored in the selector
///
/// This function doesn't destroy any instance, it simply
/// removes all the references that the selector has to
/// external sockets.
///
/// \see add, remove
void clear();
/// \brief Wait until one or more sockets are ready to receive
///
/// This function returns as soon as at least one socket has
/// some data available to be received. To know which sockets are
/// ready, use the is_ready function.
/// If you use a timeout and no socket is ready before the timeout
/// is over, the function returns false.
///
/// \param timeout Maximum time to wait, (use Time::Zero for infinity)
///
/// \return True if there are sockets ready, false otherwise
///
/// \see is_ready
bool wait(util::Time timeout = util::Time::Zero);
/// \brief Test a socket to know if it is ready to receive data
///
/// This function must be used after a call to Wait, to know
/// which sockets are ready to receive data. If a socket is
/// ready, a call to receive will never block because we know
/// that there is data available to read.
/// Note that if this function returns true for a TcpListener,
/// this means that it is ready to accept a new connection.
///
/// \param socket Socket to test
///
/// \return True if the socket is ready to read, false otherwise
///
/// \see is_ready
bool is_ready(Socket& socket) const;
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
SocketSelector& operator=(const SocketSelector& right);
private:
struct SocketSelectorImpl;
// Member data
SocketSelectorImpl* impl_; ///< Opaque pointer to the implementation (which
///< requires OS-specific types)
};
} // namespace mahi
} // namespace com
/// \class mel::SocketSelector
/// \ingroup communications
///
/// Socket selectors provide a way to wait until some data is
/// available on a set of sockets, instead of just one. This
/// is convenient when you have multiple sockets that may
/// possibly receive data, but you don't know which one will
/// be ready first. In particular, it avoids to use a thread
/// for each socket; with selectors, a single thread can handle
/// all the sockets.
///
/// All types of sockets can be used in a selector:
/// \li mel::TcpListener
/// \li mel::TcpSocket
/// \li mel::UdpSocket
///
/// A selector doesn't store its own copies of the sockets
/// (socket classes are not copyable anyway), it simply keeps
/// a reference to the original sockets that you pass to the
/// "add" function. Therefore, you can't use the selector as a
/// socket container, you must store them outside and make sure
/// that they are alive as long as they are used in the selector.
///
/// Using a selector is simple:
/// \li populate the selector with all the sockets that you want to observe
/// \li make it wait until there is data available on any of the sockets
/// \li test each socket to find out which ones are ready
///
/// Usage example:
/// \code
/// // Create a socket to listen to new connections
/// mel::TcpListener listener;
/// listener.listen(55001);
///
/// // Create a list to store the future clients
/// std::list<mel::TcpSocket*> clients;
///
/// // Create a selector
/// mel::SocketSelector selector;
///
/// // Add the listener to the selector
/// selector.add(listener);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
/// // Make the selector wait for data on any socket
/// if (selector.wait())
/// {
/// // Test the listener
/// if (selector.is_ready(listener))
/// {
/// // The listener is ready: there is a pending connection
/// mel::TcpSocket* client = new mel::TcpSocket;
/// if (listener.accept(*client) == mel::Socket::Done)
/// {
/// // Add the new client to the clients list
/// clients.push_back(client);
///
/// // Add the new client to the selector so that we will
/// // be notified when he sends something
/// selector.add(*client);
/// }
/// else
/// {
/// // Error, we won't get a new connection, delete the socket
/// delete client;
/// }
/// }
/// else
/// {
/// // The listener socket is not ready, test all other sockets (the
/// clients) for (std::list<mel::TcpSocket*>::iterator it =
/// clients.begin(); it != clients.end(); ++it)
/// {
/// mel::TcpSocket& client = **it;
/// if (selector.is_ready(client))
/// {
/// // The client has sent some data, we can receive it
/// mel::Packet packet;
/// if (client.receive(packet) == mel::Socket::Done)
/// {
/// ...
/// }
/// }
/// }
/// }
/// }
/// }
/// \endcode
///
/// \see mel::Socket
///
//==============================================================================
// LICENSES
//==============================================================================
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2017 Laurent Gomila (laurent@melml-dev.org)
//
// 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.
| 35.415638
| 80
| 0.617128
|
chip5441
|
7cee48ebae861eb413998922865af85c7c97f2c7
| 1,119
|
cpp
|
C++
|
uva/10855.cpp
|
btjanaka/competitive-programming-solutions
|
e3df47c18451802b8521ebe61ca71ee348e5ced7
|
[
"MIT"
] | 3
|
2020-06-25T21:04:02.000Z
|
2021-05-12T03:33:19.000Z
|
uva/10855.cpp
|
btjanaka/competitive-programming-solutions
|
e3df47c18451802b8521ebe61ca71ee348e5ced7
|
[
"MIT"
] | null | null | null |
uva/10855.cpp
|
btjanaka/competitive-programming-solutions
|
e3df47c18451802b8521ebe61ca71ee348e5ced7
|
[
"MIT"
] | 1
|
2020-06-25T21:04:06.000Z
|
2020-06-25T21:04:06.000Z
|
// Author: btjanaka (Bryon Tjanaka)
// Problem: (UVa) 10855
#include <bits/stdc++.h>
#define GET(x) scanf("%d", &x)
#define GED(x) scanf("%lf", &x)
typedef long long ll;
using namespace std;
#define SZ 5000
int b, s;
char big[SZ][SZ];
char small[SZ][SZ];
char small2[SZ][SZ];
void rotate() {
for (int i = 0; i < s; ++i)
for (int j = 0; j < s; ++j) small2[j][s - i - 1] = small[i][j];
for (int i = 0; i < s; ++i)
for (int j = 0; j < s; ++j) small[i][j] = small2[i][j];
}
int count_match() {
int matched = 0;
for (int i = 0; i <= b - s; ++i) {
for (int j = 0; j <= b - s; ++j) {
bool ok = true;
for (int r = 0; r < s; ++r) {
for (int c = 0; c < s; ++c) {
ok &= small[r][c] == big[r + i][c + j];
}
}
if (ok) ++matched;
}
}
return matched;
}
int main() {
while (GET(b) && GET(s) && !(!b && !s)) {
for (int i = 0; i < b; ++i) scanf("%s", big[i]);
for (int i = 0; i < s; ++i) scanf("%s", small[i]);
for (int i = 0; i < 4; ++i) {
printf("%d%c", count_match(), i == 3 ? '\n' : ' ');
rotate();
}
}
return 0;
}
| 21.941176
| 67
| 0.446828
|
btjanaka
|
7cf0c63a6872c694335811d2bd24174c58e5614b
| 415
|
hpp
|
C++
|
tests/thread/tests.hpp
|
cppfw/nitki
|
c567c1b60755491bc0c9c53321d175c4df00fc89
|
[
"MIT"
] | null | null | null |
tests/thread/tests.hpp
|
cppfw/nitki
|
c567c1b60755491bc0c9c53321d175c4df00fc89
|
[
"MIT"
] | 1
|
2021-04-09T07:35:37.000Z
|
2021-04-09T07:35:37.000Z
|
tests/thread/tests.hpp
|
cppfw/nitki
|
c567c1b60755491bc0c9c53321d175c4df00fc89
|
[
"MIT"
] | 1
|
2020-12-15T01:38:09.000Z
|
2020-12-15T01:38:09.000Z
|
#pragma once
namespace TestJoinBeforeAndAfterThreadHasFinished{
void Run();
}//~namespace
//====================
//Test many threads
//====================
namespace TestManyThreads{
void Run();
}//~namespace
//==========================
//Test immediate thread exit
//==========================
namespace TestImmediateExitThread{
void Run();
}//~namespace
namespace TestNestedJoin{
void Run();
}//~namespace
| 15.961538
| 50
| 0.575904
|
cppfw
|
7cf265d3489293daa331751f47b69f65516d8386
| 698
|
cpp
|
C++
|
Big Number/Division.cpp
|
MrinmoiHossain/Algorithms
|
d29a10316219f320b0116ef3b412457a1c1aea26
|
[
"MIT"
] | 2
|
2017-06-29T14:04:14.000Z
|
2020-03-21T12:48:21.000Z
|
Big Number/Division.cpp
|
MrinmoiHossain/Algorithms
|
d29a10316219f320b0116ef3b412457a1c1aea26
|
[
"MIT"
] | null | null | null |
Big Number/Division.cpp
|
MrinmoiHossain/Algorithms
|
d29a10316219f320b0116ef3b412457a1c1aea26
|
[
"MIT"
] | 2
|
2020-03-31T15:45:19.000Z
|
2021-09-15T15:51:06.000Z
|
#include <bits/stdc++.h>
#define LL long long int
using namespace std;
string division(string a, LL b);
int main(void)
{
int T;
cin >> T;
for(int i = 1; i <= T; i++){
string a;
LL b;
cin >> a >> b;
cout << division(a, b) << endl;
}
return 0;
}
string division(string a, LL b)
{
string s;
LL sum = 0, d;
bool flag = 0;
for(int i = 0; i < a.length(); i++){
sum = sum * 10 + (a[i] - '0');
d = sum / b;
if(d == 0 && !flag)
continue;
else{
s += (d + '0');
flag = 1;
sum = (sum % b);
}
}
if(!flag)
s = "0";
return s;
}
| 15.173913
| 40
| 0.395415
|
MrinmoiHossain
|
7cf4fc1fa673ecf24f4cfb082943b0eb8ec5af76
| 520
|
cpp
|
C++
|
src/modules/osg/generated_code/ApplicationUsageProxy.pypp.cpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 17
|
2015-06-01T12:19:46.000Z
|
2022-02-12T02:37:48.000Z
|
src/modules/osg/generated_code/ApplicationUsageProxy.pypp.cpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 7
|
2015-07-04T14:36:49.000Z
|
2015-07-23T18:09:49.000Z
|
src/modules/osg/generated_code/ApplicationUsageProxy.pypp.cpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 7
|
2015-11-28T17:00:31.000Z
|
2020-01-08T07:00:59.000Z
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "applicationusageproxy.pypp.hpp"
namespace bp = boost::python;
void register_ApplicationUsageProxy_class(){
bp::class_< osg::ApplicationUsageProxy >( "ApplicationUsageProxy", bp::init< osg::ApplicationUsage::Type, std::string const &, std::string const & >(( bp::arg("type"), bp::arg("option"), bp::arg("explanation") ), " register an explanation of commandline/environmentvariable/keyboard mouse usage.") );
}
| 37.142857
| 304
| 0.728846
|
JaneliaSciComp
|
7cf7478851f0f1e06af485d309aab570636be6a8
| 1,842
|
cpp
|
C++
|
da/min/OPTI/Solvers/Source/scip/scipeventmex.cpp
|
Heliot7/open-set-da
|
cd3c8c9a2491dd7165259e8fde769046f735a5b8
|
[
"BSD-3-Clause"
] | 83
|
2017-11-21T00:50:05.000Z
|
2022-03-18T00:54:25.000Z
|
da/min/OPTI/Solvers/Source/scip/scipeventmex.cpp
|
Heliot7/open-set-da
|
cd3c8c9a2491dd7165259e8fde769046f735a5b8
|
[
"BSD-3-Clause"
] | 6
|
2017-11-21T00:50:44.000Z
|
2021-09-07T13:43:14.000Z
|
da/min/OPTI/Solvers/Source/scip/scipeventmex.cpp
|
Heliot7/open-set-da
|
cd3c8c9a2491dd7165259e8fde769046f735a5b8
|
[
"BSD-3-Clause"
] | 15
|
2018-03-06T00:01:29.000Z
|
2021-07-28T05:18:16.000Z
|
/* SCIPMEX - A MATLAB MEX Interface to SCIP
* Released Under the BSD 3-Clause License:
* http://www.i2c2.aut.ac.nz/Wiki/OPTI/index.php/DL/License
*
* Copyright (C) Jonathan Currie 2013
* www.i2c2.aut.ac.nz
*/
#include "scipmex.h"
#include "mex.h"
#include <signal.h>
//Ctrl-C Detection
#ifdef __cplusplus
extern "C" bool utIsInterruptPending();
extern "C" void utSetInterruptPending(bool);
#else
extern bool utIsInterruptPending();
extern void utSetInterruptPending(bool);
#endif
//Executed when adding the event
static SCIP_DECL_EVENTINIT(eventInitCtrlC)
{
//Notify SCIP to add event
SCIP_CALL( SCIPcatchEvent(scip, SCIP_EVENTTYPE_NODESOLVED, eventhdlr, NULL, NULL) );
//Return
return SCIP_OKAY;
}
//Executed when removing the event
static SCIP_DECL_EVENTEXIT(eventExitCtrlC)
{
//Notify SCIP to drop event
SCIP_CALL( SCIPdropEvent(scip, SCIP_EVENTTYPE_NODESOLVED, eventhdlr, NULL, -1) );
//Return
return SCIP_OKAY;
}
//Executed when event occurs
static SCIP_DECL_EVENTEXEC(eventExecCtrlC)
{
//Check for Ctrl-C
if (utIsInterruptPending()) {
utSetInterruptPending(false); /* clear Ctrl-C status */
mexPrintf("\nCtrl-C Detected. Exiting SCIP...\n\n");
raise(SIGINT);
}
return SCIP_OKAY; //always OK - otherwise we don't get intermediate answer
}
//Called from scipmex to include our event
SCIP_RETCODE SCIPincludeCtrlCEventHdlr(SCIP* scip)
{
SCIP_EVENTHDLR* eventhdlr = NULL;
//Create Event Handler
SCIP_CALL( SCIPincludeEventhdlrBasic(scip, &eventhdlr, "CtrlCMatlab", "Catching Ctrl-C From Matlab", eventExecCtrlC, NULL) );
//Setup callbacks
SCIP_CALL( SCIPsetEventhdlrInit(scip, eventhdlr, eventInitCtrlC) );
SCIP_CALL( SCIPsetEventhdlrExit(scip, eventhdlr, eventExitCtrlC) );
return SCIP_OKAY;
}
| 28.338462
| 129
| 0.716069
|
Heliot7
|
7cfb7c135873789f76c032b27d40dd046117f774
| 1,163
|
hpp
|
C++
|
src/has_cycle.hpp
|
deepgrace/giant
|
4070c79892957c8e9244eb7a3d7690a25970f769
|
[
"BSL-1.0"
] | 6
|
2019-04-02T07:47:37.000Z
|
2021-05-31T08:01:04.000Z
|
src/has_cycle.hpp
|
deepgrace/giant
|
4070c79892957c8e9244eb7a3d7690a25970f769
|
[
"BSL-1.0"
] | null | null | null |
src/has_cycle.hpp
|
deepgrace/giant
|
4070c79892957c8e9244eb7a3d7690a25970f769
|
[
"BSL-1.0"
] | 4
|
2019-04-15T08:52:17.000Z
|
2022-03-25T10:29:57.000Z
|
//
// Copyright (c) 2016-present DeepGrace (complex dot invoke at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/deepgrace/giant
//
#include <memory>
using namespace std;
template <typename T>
struct node
{
T data;
shared_ptr<node<T>> next;
};
template <typename T>
shared_ptr<node<T>> has_cycle(const shared_ptr<node<T>>& head)
{
auto fast = head;
auto slow = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
int len = 0;
do
{
++len;
fast = fast->next;
}
while (slow != fast);
auto pos = head;
while (len--)
pos = pos->next;
auto start = head;
while (start != pos)
{
pos = pos->next;
start = start->next;
}
return start;
}
}
return nullptr;
}
| 22.365385
| 90
| 0.505589
|
deepgrace
|
cfb052a4599f1d20f940cc7b246840a20022dac9
| 3,922
|
cpp
|
C++
|
source/x86/source_moss/kernel/input/devices/interface_mouse_ps2.cpp
|
imallett/MOSS
|
5ab7bc9c6b1669e2c99aa797d7091c6b52a0ea38
|
[
"MIT"
] | 2
|
2020-04-02T14:00:33.000Z
|
2021-06-29T05:50:30.000Z
|
source/x86/source_moss/kernel/input/devices/interface_mouse_ps2.cpp
|
imallett/MOSS
|
5ab7bc9c6b1669e2c99aa797d7091c6b52a0ea38
|
[
"MIT"
] | null | null | null |
source/x86/source_moss/kernel/input/devices/interface_mouse_ps2.cpp
|
imallett/MOSS
|
5ab7bc9c6b1669e2c99aa797d7091c6b52a0ea38
|
[
"MIT"
] | null | null | null |
#include "interface_mouse_ps2.hpp"
#include "../../../mossc/_misc.hpp"
#include "../../graphics/vesa/controller.hpp"
#include "../../io/io.hpp"
#include "../../kernel.hpp"
#include "../mouse.hpp"
#include "controller_ps2.hpp"
namespace MOSS { namespace Input { namespace Devices {
//TODO: timeouts for all this!
InterfaceDevicePS2Mouse::InterfaceDevicePS2Mouse(ControllerPS2* controller, int device_index, const DeviceType& device_type) : InterfaceDevicePS2Base(controller,device_index,device_type) {
mouse_cycle = 0;
x = last_x = 0;
y = last_y = 0;
for (int i=0;i<5;++i) buttons[i]=false;
}
InterfaceDevicePS2Mouse::~InterfaceDevicePS2Mouse(void) {
}
bool InterfaceDevicePS2Mouse::handle_irq(void) /*override*/ {
if (!InterfaceDevicePS2Base::handle_irq()) return false;
//http://forum.osdev.org/viewtopic.php?t=10247
//http://www.computer-engineering.org/ps2mouse/
uint8_t byte;
controller->recv_data(&byte);
switch (mouse_cycle) {
case 0:
received_data.byte1 = byte;
++mouse_cycle;
//if ((received_data.byte1&0x08)!=0) {
// ++mouse_cycle; //Only accept this as the first byte if the "must be 1" bit is set
//}
break;
case 1:
received_data.byte2 = byte;
++mouse_cycle;
break;
case 2:
received_data.byte3 = byte;
_handle_current_packet();
mouse_cycle = 0;
break;
}
return true;
}
void InterfaceDevicePS2Mouse::set_position(int x, int y) {
assert_term(kernel->graphics!=nullptr&&kernel->graphics->current_mode!=nullptr,"Mouse pointer can only be operated in a graphics mode!"); //But only because we need to check where to not move it.
if (x < 0) x= 0;
else if (x>=kernel->graphics-> width) x=kernel->graphics-> width-1;
if (y < 0) y= 0;
else if (y>=kernel->graphics->height) y=kernel->graphics->height-1;
int dx = x - this->x;
int dy = y - this->y;
if (dx!=0 || dy!=0) {
last_x = this->x;
last_y = this->y;
this->x += dx;
this->y += dy;
kernel->handle_mouse_move(Mouse::EventMouseMove(this->x,this->y,dx,dy));
}
}
void InterfaceDevicePS2Mouse:: click(int button_index) {
kernel->handle_mouse_click(Mouse::EventMouseClick(button_index));
}
void InterfaceDevicePS2Mouse::unclick(int button_index) {
kernel->handle_mouse_unclick(Mouse::EventMouseUnclick(button_index));
}
void InterfaceDevicePS2Mouse::set_sample_rate(int hz) {
#ifdef MOSS_DEBUG
switch (hz) {
case 10: case 20: case 40: case 60: case 80: case 100: case 200: break;
default:
assert_term(false,"Invalid samping rate %d (must be one of 10, 20, 40, 60, 80, 100, 200)!",hz);
}
#endif
//kernel->write(">>Sending 0xF3\n");
send_command_device(0xF3);
//kernel->write(">>Waiting\n");
wait_response();
//kernel->write(">>Sending Hz\n");
//controller->send_data(hz);
send_command_device(hz); //works for some reason? See http://forum.osdev.org/viewtopic.php?f=1&t=26899
//controller->send_data(hz);
//kernel->write(">>Waiting\n");
wait_response();
//kernel->write(">>Done!\n");
}
void InterfaceDevicePS2Mouse::_handle_current_packet(void) {
//http://wiki.osdev.org/PS/2_Mouse
if (received_data.dx_overflowed || received_data.dy_overflowed) return; //Just give up.
int dx = (int)(received_data.dx) - (int)((received_data.byte1<<4)&0x100);
int dy = (int)(received_data.dy) - (int)((received_data.byte1<<3)&0x100);
set_position(x+dx,y+dy);
#define HANDLE_BUTTON(NAME,INDEX)\
if (received_data.NAME && !buttons[INDEX]) {\
buttons[INDEX] = true;\
click(INDEX);\
} else if (!received_data.NAME && buttons[INDEX]) {\
buttons[INDEX] = false;\
unclick(INDEX);\
}
HANDLE_BUTTON( button_left,0)
HANDLE_BUTTON(button_middle,1)
HANDLE_BUTTON( button_right,2)
#undef HANDLE_BUTTON
}
}}}
| 29.051852
| 197
| 0.652728
|
imallett
|
cfb74c5f61e72e167965cd3b6a4877121efebe2c
| 2,131
|
cpp
|
C++
|
KEditor/Entity/KEEntityNamePool.cpp
|
King19931229/KApp
|
f7f855b209348f835de9e5f57844d4fb6491b0a1
|
[
"MIT"
] | 13
|
2019-10-19T17:41:19.000Z
|
2021-11-04T18:50:03.000Z
|
KEditor/Entity/KEEntityNamePool.cpp
|
King19931229/KApp
|
f7f855b209348f835de9e5f57844d4fb6491b0a1
|
[
"MIT"
] | 3
|
2019-12-09T06:22:43.000Z
|
2020-05-28T09:33:44.000Z
|
KEditor/Entity/KEEntityNamePool.cpp
|
King19931229/KApp
|
f7f855b209348f835de9e5f57844d4fb6491b0a1
|
[
"MIT"
] | null | null | null |
#include "KEEntityNamePool.h"
#include "KEditorGlobal.h"
KEEntityNamePool::KEEntityNamePool()
{
}
KEEntityNamePool::~KEEntityNamePool()
{
ASSERT_RESULT(m_Pool.empty());
}
bool KEEntityNamePool::Init()
{
UnInit();
return true;
}
bool KEEntityNamePool::UnInit()
{
m_Pool.clear();
return true;
}
std::string KEEntityNamePool::NamePoolElement::AllocName()
{
assert(m_FreedName.size() == m_ReservedNameStack.size());
if (!m_ReservedNameStack.empty())
{
std::string oldName = m_ReservedNameStack.top();
m_ReservedNameStack.pop();
ASSERT_RESULT(m_FreedName.erase(oldName));
ASSERT_RESULT(m_AllocatedName.insert(oldName).second);
return oldName;
}
else
{
std::string newName = prefix + "_" + std::to_string(m_NameCounter++);
ASSERT_RESULT(m_AllocatedName.insert(newName).second);
return newName;
}
}
bool KEEntityNamePool::NamePoolElement::FreeName(const std::string& name)
{
auto it = m_AllocatedName.find(name);
if (it != m_AllocatedName.end())
{
bool notInFreeName = m_FreedName.find(name) == m_FreedName.end();
ASSERT_RESULT(notInFreeName);
if (notInFreeName)
{
ASSERT_RESULT(m_FreedName.insert(name).second);
m_ReservedNameStack.push(name);
assert(m_FreedName.size() == m_ReservedNameStack.size());
}
m_AllocatedName.erase(it);
return true;
}
return false;
}
bool KEEntityNamePool::GetBaseName(const std::string& name, std::string& baseName)
{
auto pos = name.find_last_of('_');
if (pos == std::string::npos || pos == name.length() - 1)
{
return false;
}
baseName = name.substr(0, pos);
return true;
}
void KEEntityNamePool::FreeName(const std::string& name)
{
std::string baseName;
if (GetBaseName(name, baseName))
{
auto poolIt = m_Pool.find(baseName);
if (poolIt != m_Pool.end())
{
NamePoolElement& element = poolIt->second;
element.FreeName(name);
}
}
}
std::string KEEntityNamePool::AllocName(const std::string& prefix)
{
auto poolIt = m_Pool.find(prefix);
if (poolIt == m_Pool.end())
{
poolIt = m_Pool.insert({ prefix, NamePoolElement(prefix) }).first;
}
NamePoolElement& element = poolIt->second;
return element.AllocName();
}
| 21.525253
| 82
| 0.712342
|
King19931229
|
cfb7c3be207d4d876b2478472d249000d3e74726
| 9,931
|
cpp
|
C++
|
jigtest/src/framework/sdlapplicationbase.cpp
|
Ludophonic/JigLib
|
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
|
[
"Zlib"
] | 10
|
2016-06-01T12:54:45.000Z
|
2021-09-07T17:34:37.000Z
|
jigtest/src/framework/sdlapplicationbase.cpp
|
Ludophonic/JigLib
|
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
|
[
"Zlib"
] | null | null | null |
jigtest/src/framework/sdlapplicationbase.cpp
|
Ludophonic/JigLib
|
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
|
[
"Zlib"
] | 4
|
2017-05-03T14:03:03.000Z
|
2021-01-04T04:31:15.000Z
|
//==============================================================
// Copyright (C) 2004 Danny Chapman
// danny@rowlhouse.freeserve.co.uk
//--------------------------------------------------------------
//
/// @file SDLApplicationbase.cpp
//
//==============================================================
#include "sdlapplicationbase.hpp"
#include "graphics.hpp"
#include <stdio.h>
using namespace std;
using namespace JigLib;
void tSDLApplicationBase::LoadConfig(int & argc, char * argv[],
string configFileName)
{
// setup config/tracing
bool configFileOk;
if (argc > 1)
configFileName = string(argv[1]);
mConfigFile = new tConfigFile(configFileName, configFileOk);
if (!configFileOk)
TRACE("Warning: Unable to open main config file: %s\n", configFileName.c_str());
// initialise trace
// set up tracing properly
bool traceEnabled = true;
int traceLevel = 3;
bool traceAllStrings = true;
vector<string> traceStrings;
mConfigFile->GetValue("trace_enabled", traceEnabled);
mConfigFile->GetValue("trace_level", traceLevel);
mConfigFile->GetValue("trace_all_strings", traceAllStrings);
mConfigFile->GetValues("trace_strings", traceStrings);
EnableTrace(traceEnabled);
SetTraceLevel(traceLevel);
EnableTraceAllStrings(traceAllStrings);
AddTraceStrings(traceStrings);
TRACE_FILE_IF(ONCE_1)
TRACE("Logging set up\n");
}
//==============================================================
// tSDLApplicationBase
//==============================================================
tSDLApplicationBase::tSDLApplicationBase(int & argc, char * argv[],
string configFileName,
void (* licenseFn)(void))
{
TRACE_METHOD_ONLY(ONCE_1);
LoadConfig(argc, argv, configFileName);
if (licenseFn)
(*licenseFn)();
else
DisplayLicense();
}
//==============================================================
// ~tSDLApplicationBase
//==============================================================
tSDLApplicationBase::~tSDLApplicationBase()
{
TRACE_METHOD_ONLY(ONCE_1);
}
//==============================================================
// Initialise
//==============================================================
bool tSDLApplicationBase::Initialise(const std::string app_name)
{
TRACE_METHOD_ONLY(ONCE_1);
// intialise some vars
mStartOfFrameTime = tTime(0.0f);
mOldStartOfFrameTime = tTime(0.0f);
mFPSInterval = tTime(1.0f);
mLastStoredTime = tTime(0.0f);
mFPSCounter = 0;
mFPS = 1.0f;
mNewFPS = true;
TRACE_FILE_IF(ONCE_2)
TRACE("Initializing SDL.\n");
if((SDL_Init(SDL_INIT_VIDEO)==-1)) {
TRACE("Could not initialize SDL: %s.\n", SDL_GetError());
return false;
}
/* Clean up on exit */
atexit(SDL_Quit);
TRACE_FILE_IF(ONCE_2)
TRACE("SDL initialized.\n");
// Information about the current video settings.
const SDL_VideoInfo* info = NULL;
// get some video information.
info = SDL_GetVideoInfo( );
if( !info ) {
TRACE("Video query failed: %s\n",
SDL_GetError( ) );
return false;
}
mWindowWidth = 800;
mWindowHeight = 600;
mConfigFile->GetValue("window_width", mWindowWidth);
mConfigFile->GetValue("window_height", mWindowHeight);
int bpp = info->vfmt->BitsPerPixel;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
bool fullscreen = false;
mConfigFile->GetValue("fullscreen", fullscreen);
// don't allow resizing for now - textures etc get zapped
int flags = SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0);
SDL_Surface *screen = SDL_SetVideoMode( mWindowWidth,
mWindowHeight,
bpp,
flags );
if( screen == 0 )
{
TRACE("Video mode set failed: %s\n", SDL_GetError( ) );
return false;
}
return true;
}
//==============================================================
// GetTimeNow
//==============================================================
tTime tSDLApplicationBase::GetTimeNow() const
{
Uint32 millisec = SDL_GetTicks();
return millisec * 0.001f;
}
//==============================================================
// InternalHandleStartOfLoop
//==============================================================
void tSDLApplicationBase::InternalHandleStartOfLoop()
{
mOldStartOfFrameTime = mStartOfFrameTime;
mStartOfFrameTime = GetTimeNow();
if ( (mStartOfFrameTime > 0.0f) &&
(mStartOfFrameTime < mFPSInterval) )
{
mFPS = mFPSCounter / mStartOfFrameTime;
}
if (mStartOfFrameTime - mLastStoredTime >= mFPSInterval)
{
mFPS = (tScalar) mFPSCounter;
mLastStoredTime = mStartOfFrameTime;
mFPSCounter = 0;
mNewFPS = true;
}
else
{
++mFPSCounter;
mNewFPS = false;
}
}
//==============================================================
// StartMainLoop
//==============================================================
void tSDLApplicationBase::StartMainLoop()
{
mExitMainLoop = false;
while( false == mExitMainLoop )
{
InternalHandleStartOfLoop();
// do all the basic stuff like keyboard, mouse etc, callint the
// app.
ProcessEvents();
// get the app to do it's own stuff - e.g. physics, rendering
ProcessMainEvent();
}
}
//==============================================================
// InternalHandleResize
//==============================================================
void tSDLApplicationBase::InternalHandleResize(const SDL_ResizeEvent & event)
{
bool fullscreen = false;
mConfigFile->GetValue("fullscreen", fullscreen);
mWindowWidth = event.w;
mWindowHeight = event.h;
const SDL_VideoInfo* info = SDL_GetVideoInfo( );
if( !info ) {
TRACE("Video query failed: %s\n",
SDL_GetError( ) );
return;
}
int bpp = info->vfmt->BitsPerPixel;
int flags = SDL_RESIZABLE | SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0);
SDL_Surface *screen = SDL_SetVideoMode( mWindowWidth,
mWindowHeight,
bpp,
flags );
if( screen == 0 )
{
TRACE("Video mode set failed: %s\n", SDL_GetError( ) );
}
}
//==============================================================
// ProcessEvents
//==============================================================
void tSDLApplicationBase::ProcessEvents()
{
SDL_Event event;
while( SDL_PollEvent( &event ) )
{
switch( event.type ) {
case SDL_KEYDOWN:
HandleKeyDown( event.key.keysym );
break;
case SDL_KEYUP:
HandleKeyUp( event.key.keysym );
break;
case SDL_MOUSEMOTION:
HandleMouseMotion( event.motion );
break;
case SDL_MOUSEBUTTONDOWN:
HandleMouseButtonDown( event.button );
break;
case SDL_MOUSEBUTTONUP:
HandleMouseButtonUp( event.button );
break;
case SDL_VIDEORESIZE:
InternalHandleResize( event.resize );
break;
case SDL_QUIT:
/* Handle quit requests (like Ctrl-c). */
exit(0);
break;
}
}
}
//==============================================================
// HandleReShape
//==============================================================
void tSDLApplicationBase::HandleReShape(int newWidth, int newHeight)
{
}
//==============================================================
// DisplayLicense
//==============================================================
void tSDLApplicationBase::DisplayLicense()
{
TRACE("Application Copyright 2004 Danny Chapman: danny@rowlhouse.freeserve.co.uk\n");
TRACE("Application comes with ABSOLUTELY NO WARRANTY;\n");
TRACE("This is free software, and you are welcome to redistribute it\n");
TRACE("under certain conditions; see the GNU General Public License\n");
}
//===========================================================
// Code to write out screen shots
//==========================================================
static void FlipVertical(unsigned char *data, int w, int h)
{
int x, y, i1, i2;
unsigned char temp;
for (x=0;x<w;x++){
for (y=0;y<h/2;y++){
i1 = (y*w + x)*3; // this pixel
i2 = ((h - y - 1)*w + x)*3; // its opposite (across x-axis)
// swap pixels
temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
i1++; i2++;
temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
i1++; i2++;
temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
}
}
}
//==============================================================
// writeFrameBuffer
//==============================================================
static void WriteFrameBuffer(char *filename)
{
FILE *fp = fopen(filename, "wb");
int width, height;
GetWindowSize(width, height);
int data_size = width * height * 3;
unsigned char *framebuffer =
(unsigned char *) malloc(data_size * sizeof(unsigned char));
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, framebuffer);
FlipVertical(framebuffer, width, height);
fprintf(fp, "P6\n%d %d\n%d\n", width, height, 255);
fwrite(framebuffer, data_size, 1, fp);
fclose(fp);
free(framebuffer);
}
//==============================================================
// DoScreenshot
//==============================================================
void tSDLApplicationBase::DoScreenshot()
{
static int count = 0;
static char screen_file[] = "screenshot-00000.ppm";
sprintf(screen_file, "screenshot-%05d.ppm", count++);
// printf("%s\n", movie_file);
WriteFrameBuffer(screen_file);
}
| 28.133144
| 87
| 0.518578
|
Ludophonic
|
cfb7f0230a3dad9f838546d1c0b8a0a0989955ba
| 17,656
|
cpp
|
C++
|
Source/System/[Platforms]/Windows/Interface.Windows.cpp
|
jbatonnet/System
|
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
|
[
"MIT"
] | 3
|
2020-04-24T20:23:24.000Z
|
2022-01-06T22:27:01.000Z
|
Source/System/[Platforms]/Windows/Interface.Windows.cpp
|
jbatonnet/system
|
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
|
[
"MIT"
] | null | null | null |
Source/System/[Platforms]/Windows/Interface.Windows.cpp
|
jbatonnet/system
|
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
|
[
"MIT"
] | 1
|
2021-06-25T17:35:08.000Z
|
2021-06-25T17:35:08.000Z
|
#ifdef WINDOWS
#include <System/System.h>
using namespace System;
using namespace System::Runtime;
using namespace System::Objects;
using namespace System::Devices;
using namespace System::IO;
using namespace System::Interface;
using namespace System::Graphics;
#undef using
#define _INITIALIZER_LIST_
#include <Windows.h>
#include <Dwmapi.h>
#include <cstdlib>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX_WINDOWS_COUNT 32
using namespace std;
struct WindowInfo
{
Window* Window;
Surface* Surface;
HWND Hwnd;
};
struct PendingWindowInfo
{
Window* Window;
};
vector<WindowInfo> windowInfos;
queue<PendingWindowInfo> pendingWindowInfos;
Buttons virtualKeyMapping[0x100] = {
(Buttons)0x00, (Buttons)0x01, (Buttons)0x02, (Buttons)0x03, (Buttons)0x04, (Buttons)0x05, (Buttons)0x06, (Buttons)0x07, Buttons::Backspace, Buttons::Tab, (Buttons)0x0A, (Buttons)0x0B, (Buttons)0x0C, Buttons::Enter, (Buttons)0x0E, (Buttons)0x0F,
Buttons::Shift, Buttons::Control, Buttons::Alt, (Buttons)0x13, Buttons::CapsLock, (Buttons)0x15, (Buttons)0x16, (Buttons)0x17, (Buttons)0x18, (Buttons)0x19, (Buttons)0x1A, Buttons::Escape, (Buttons)0x1C, (Buttons)0x1D, (Buttons)0x1E, (Buttons)0x1F,
Buttons::Space, Buttons::PageUp, Buttons::PageDown, Buttons::End, Buttons::Origin, Buttons::Left, Buttons::Up, Buttons::Right, Buttons::Down, (Buttons)0x29, (Buttons)0x2A, (Buttons)0x2B, (Buttons)0x2C, Buttons::Insert, Buttons::Delete, (Buttons)0x2F,
Buttons::Digit0, Buttons::Digit1, Buttons::Digit2, Buttons::Digit3, Buttons::Digit4, Buttons::Digit5, Buttons::Digit6, Buttons::Digit7, Buttons::Digit8, Buttons::Digit9, (Buttons)0x3A, (Buttons)0x3B, (Buttons)0x3C, (Buttons)0x3D, (Buttons)0x3E, (Buttons)0x3F,
(Buttons)0x40, Buttons::A, Buttons::B, Buttons::C, Buttons::D, Buttons::E, Buttons::F, Buttons::G, Buttons::H, Buttons::I, Buttons::J, Buttons::K, Buttons::L, Buttons::M, Buttons::N, Buttons::O,
Buttons::P, Buttons::Q, Buttons::R, Buttons::S, Buttons::T, Buttons::U, Buttons::V, Buttons::W, Buttons::X, Buttons::Y, Buttons::Z, (Buttons)0x5B, (Buttons)0x5C, (Buttons)0x5D, (Buttons)0x5E, (Buttons)0x5F,
(Buttons)0x60, (Buttons)0x61, (Buttons)0x62, (Buttons)0x63, (Buttons)0x64, (Buttons)0x65, (Buttons)0x66, (Buttons)0x67, (Buttons)0x68, (Buttons)0x69, (Buttons)0x6A, (Buttons)0x6B, (Buttons)0x6C, (Buttons)0x6D, (Buttons)0x6E, (Buttons)0x6F,
Buttons::F1, Buttons::F2, Buttons::F3, Buttons::F4, Buttons::F5, Buttons::F6, Buttons::F7, Buttons::F8, Buttons::F9, Buttons::F10, Buttons::F11, Buttons::F12, (Buttons)0x7C, (Buttons)0x7D, (Buttons)0x7E, (Buttons)0x7F,
(Buttons)0x80, (Buttons)0x81, (Buttons)0x82, (Buttons)0x83, (Buttons)0x84, (Buttons)0x85, (Buttons)0x86, (Buttons)0x87, (Buttons)0x88, (Buttons)0x89, (Buttons)0x8A, (Buttons)0x8B, (Buttons)0x8C, (Buttons)0x8D, (Buttons)0x8E, (Buttons)0x8F,
Buttons::NumLock, (Buttons)0x91, (Buttons)0x92, (Buttons)0x93, (Buttons)0x94, (Buttons)0x95, (Buttons)0x96, (Buttons)0x97, (Buttons)0x98, (Buttons)0x99, (Buttons)0x9A, (Buttons)0x9B, (Buttons)0x9C, (Buttons)0x9D, (Buttons)0x9E, (Buttons)0x9F,
Buttons::LeftShift, Buttons::RightShift, Buttons::LeftControl, Buttons::RightControl, (Buttons)0xA4, (Buttons)0xA5, (Buttons)0xA6, (Buttons)0xA7, (Buttons)0xA8, (Buttons)0xA9, (Buttons)0xAA, (Buttons)0xAB, (Buttons)0xAC, (Buttons)0xAD, (Buttons)0xAE, (Buttons)0xAF,
(Buttons)0xB0, (Buttons)0xB1, (Buttons)0xB2, (Buttons)0xB3, (Buttons)0xB4, (Buttons)0xB5, (Buttons)0xB6, (Buttons)0xB7, (Buttons)0xB8, (Buttons)0xB9, (Buttons)0xBA, (Buttons)0xBB, (Buttons)0xBC, (Buttons)0xBD, (Buttons)0xBE, (Buttons)0xBF,
(Buttons)0xC0, (Buttons)0xC1, (Buttons)0xC2, (Buttons)0xC3, (Buttons)0xC4, (Buttons)0xC5, (Buttons)0xC6, (Buttons)0xC7, (Buttons)0xC8, (Buttons)0xC9, (Buttons)0xCA, (Buttons)0xCB, (Buttons)0xCC, (Buttons)0xCD, (Buttons)0xCE, (Buttons)0xCF,
(Buttons)0xD0, (Buttons)0xD1, (Buttons)0xD2, (Buttons)0xD3, (Buttons)0xD4, (Buttons)0xD5, (Buttons)0xD6, (Buttons)0xD7, (Buttons)0xD8, (Buttons)0xD9, (Buttons)0xDA, (Buttons)0xDB, (Buttons)0xDC, (Buttons)0xDD, (Buttons)0xDE, (Buttons)0xDF,
(Buttons)0xE0, (Buttons)0xE1, (Buttons)0xE2, (Buttons)0xE3, (Buttons)0xE4, (Buttons)0xE5, (Buttons)0xE6, (Buttons)0xE7, (Buttons)0xE8, (Buttons)0xE9, (Buttons)0xEA, (Buttons)0xEB, (Buttons)0xEC, (Buttons)0xED, (Buttons)0xEE, (Buttons)0xEF,
(Buttons)0xF0, (Buttons)0xF1, (Buttons)0xF2, (Buttons)0xF3, (Buttons)0xF4, (Buttons)0xF5, (Buttons)0xF6, (Buttons)0xF7, (Buttons)0xF8, (Buttons)0xF9, (Buttons)0xFA, (Buttons)0xFB, (Buttons)0xFC, (Buttons)0xFD, (Buttons)0xFE, (Buttons)0xFF
};
WNDCLASSEX windowClass;
POINT clientOffset, nonClientSize;
#define DOUBLE_BUFFER 0
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
auto result = find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Hwnd == hwnd; });
if (result == windowInfos.end())
return DefWindowProc(hwnd, msg, wParam, lParam);
WindowInfo& windowInfo = *result;
Window* window = windowInfo.Window;
Surface* surface = windowInfo.Surface;
int captionHeight = 23;
switch (msg)
{
#pragma region Mouse
case WM_MOUSEMOVE:
{
PointerPositionEvent pointerPositionEvent;
pointerPositionEvent.Index = 0;
pointerPositionEvent.X = LOWORD(lParam);
pointerPositionEvent.Y = HIWORD(lParam);
window->OnPointerMove(window, pointerPositionEvent);
break;
}
case WM_RBUTTONDOWN:
{
SendMessage(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, NULL);
break;
}
case WM_LBUTTONDOWN:
{
PointerEvent pointerEvent;
pointerEvent.Index = 0;
window->OnPointerDown(window, pointerEvent);
break;
}
case WM_RBUTTONUP:
{
break;
}
case WM_LBUTTONUP:
{
PointerEvent pointerEvent;
pointerEvent.Index = 0;
window->OnPointerUp(window, pointerEvent);
break;
}
case WM_MOUSELEAVE:
{
break;
}
case WM_MOUSEWHEEL:
{
PointerScrollEvent pointerScrollEvent;
pointerScrollEvent.Index = 0;
pointerScrollEvent.Delta = -GET_WHEEL_DELTA_WPARAM(wParam) / 120;
window->OnPointerScroll(window, pointerScrollEvent);
break;
}
#pragma endregion
#pragma region Keyboard
case WM_CHAR:
{
if (wParam < 32)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = Buttons::Unknown;
buttonEvent.Character = (char)wParam;
bool pressed = !(lParam >> 31);
if (pressed)
window->OnButtonDown(window, buttonEvent);
else
window->OnButtonUp(window, buttonEvent);
return 0;
}
case WM_KEYDOWN:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
u32 character = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
if (!character || character < 32)
{
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 0;
window->OnButtonDown(window, buttonEvent);
}
return 0;
}
case WM_KEYUP:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 'a';
window->OnButtonUp(window, buttonEvent);
return 0;
}
case WM_SYSKEYDOWN:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 0;
window->OnButtonDown(window, buttonEvent);
return 0;
}
case WM_SYSKEYUP:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 0;
window->OnButtonUp(window, buttonEvent);
return 0;
}
#pragma endregion
#pragma region Window
case WM_CREATE:
{
RECT rect;
rect.left = window->Position.X;
rect.top = window->Position.Y;
rect.right = window->Position.X + window->Size.X;
rect.bottom = window->Position.Y + window->Size.Y;
AdjustWindowRect(&rect, WS_POPUP, false);
SetWindowPos(hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOREPOSITION | SWP_NOMOVE);
BufferedPaintInit();
break;
}
case WM_CLOSE:
{
DestroyWindow(hwnd);
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
exit(0); // FIXME
break;
}
case WM_SIZE:
{
s16 width = LOWORD(lParam);
s16 height = HIWORD(lParam);
window->Size = Point2(width, height);
delete surface;
windowInfo.Surface = new Surface(window->Size.X, window->Size.Y);
InvalidateRect(hwnd, NULL, false);
UpdateWindow(hwnd);
break;
}
#pragma endregion
#pragma region Non-client
case WM_NCPAINT:
{
//DWMNCRENDERINGPOLICY policy = DWMNCRP_ENABLED;
//DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, (void*)&policy, sizeof(DWMNCRENDERINGPOLICY));
MARGINS margins = { 1, 1, 1, 1 };
DwmExtendFrameIntoClientArea(hwnd, &margins);
return DefWindowProc(hwnd, msg, wParam, lParam);
}
case WM_NCCALCSIZE:
break;
#pragma endregion
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc, hdcBuffer;
HGDIOBJ oldBitmap;
BITMAP bitmap;
HBITMAP hBitmap;
HPAINTBUFFER hPaintBuffer;
window->Redraw(surface, System::Graphics::Rectangle(Point2::Zero, window->Size));
#if DOUBLE_BUFFER
hdc = GetWindowDC(hwnd);
#else
hdc = BeginPaint(hwnd, &ps);
hdcBuffer = CreateCompatibleDC(hdc);
#endif
RECT rect;
GetClientRect(hwnd, &rect);
#if DOUBLE_BUFFER
hPaintBuffer = BeginBufferedPaint(hdc, &rect, BPBF_COMPATIBLEBITMAP, NULL, &hdcBuffer);
BufferedPaintMakeOpaque(hPaintBuffer, NULL);
#endif
hBitmap = CreateBitmap(window->Size.X, window->Size.Y, 1, 32, surface->Data);
oldBitmap = SelectObject(hdcBuffer, hBitmap);
GetObject(hBitmap, sizeof(bitmap), &bitmap);
BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcBuffer, 0, 0, SRCCOPY);
SelectObject(hdcBuffer, oldBitmap);
DeleteObject(hBitmap);
#if DOUBLE_BUFFER
BufferedPaintMakeOpaque(hPaintBuffer, NULL);
EndBufferedPaint(hPaintBuffer, TRUE);
ReleaseDC(hwnd, hdc);
#else
EndPaint(hwnd, &ps);
#endif
break;
}
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
HWND GetHwndByWindow(Window* window)
{
auto result = find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Window == window; });
if (result == windowInfos.end())
return NULL;
return result->Hwnd;
}
void Window_PositionChanged(void* origin, ChangeEventParameter<Point> args)
{
HWND hwnd = GetHwndByWindow((Window*)origin);
SetWindowPos(hwnd, NULL, args.NewValue.X, args.NewValue.Y, 0, 0, SWP_NOREPOSITION | SWP_NOSIZE);
}
void Window_SizeChanged(void* origin, ChangeEventParameter<Point> args)
{
HWND hwnd = GetHwndByWindow((Window*)origin);
SetWindowPos(hwnd, NULL, 0, 0, args.NewValue.X, args.NewValue.Y, SWP_NOREPOSITION | SWP_NOMOVE);
}
void Window_Refreshed(void* origin, System::Graphics::Rectangle rectangle)
{
Window* window = (Window*)origin;
HWND hwnd = GetHwndByWindow(window);
RECT rect = { 0 };
/*rect.left = rectangle.Position.X;
rect.top = rectangle.Position.Y;
rect.right = rectangle.Position.X + rectangle.Size.X;
rect.bottom = rectangle.Position.Y + rectangle.Size.Y;*/
rect.left = 0;
rect.top = 0;
rect.right = window->Size.X;
rect.bottom = window->Size.Y;
InvalidateRect(hwnd, &rect, true);
}
DWORD WINAPI WindowsManager_Loop(LPVOID parameter)
{
MSG msg;
for (;;)
{
// Handle window creation requests
while (!pendingWindowInfos.empty())
{
PendingWindowInfo pendingWindow = pendingWindowInfos.front();
pendingWindowInfos.pop();
// Create the Window
Window* window = pendingWindow.Window;
HWND hwnd = CreateWindow("myWindowClass", "", WS_OVERLAPPEDWINDOW, window->Position.X, window->Position.Y, window->Size.X, window->Size.Y, NULL, NULL, NULL, NULL);
Surface* surface = new Surface(window->Size.X, window->Size.Y);
// Register to window events
window->PositionChanged += Window_PositionChanged;
window->SizeChanged += Window_SizeChanged;
window->Refreshed += Window_Refreshed;
//window->Initialize();
// Adjust the newly created window
/*RECT rect;
rect.left = window->Position.X;
rect.top = window->Position.Y;
rect.right = window->Position.X + window->Size.X;
rect.bottom = window->Position.Y + window->Size.Y;
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, false);*/
// Register the new window
WindowInfo windowInfo;
windowInfo.Window = window;
windowInfo.Surface = surface;
windowInfo.Hwnd = hwnd;
windowInfos.push_back(windowInfo);
// Show window
SetWindowPos(hwnd, NULL, 0, 0, window->Size.X + nonClientSize.x, window->Size.Y + nonClientSize.y, SWP_NOREPOSITION | SWP_NOMOVE);
ShowWindow(hwnd, SW_SHOW);
// Force first draw
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
}
// Handle messages
if (!windowInfos.empty())
{
for (int i = 0; i < 1024; i++)
{
if (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
}
return 0;
}
void WindowsManager::Initialize()
{
// Compute non client sizes
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = 0;
rect.bottom = 0;
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, false);
clientOffset.x = -rect.left;
clientOffset.y = -rect.top;
nonClientSize.x = rect.right - rect.left;
nonClientSize.y = rect.bottom - rect.top;
// Register a new window class
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = 0;
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = NULL; // (HBRUSH)(COLOR_WINDOW + 1);
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = "myWindowClass";
windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&windowClass))
Exception::Assert("Could not register window class");
// Start the window loop thread
DWORD threadId;
HANDLE threadHandle = CreateThread(NULL, 0, WindowsManager_Loop, NULL, 0, &threadId);
}
void WindowsManager::Add(Window* window)
{
int index = 0;
// Check for existing window
if (find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Window == window; }) != windowInfos.end())
return;
// Push a new window creation request
PendingWindowInfo pendingWindow;
pendingWindow.Window = window;
pendingWindowInfos.push(pendingWindow);
// Wait for window creation
for (;;)
{
Sleep(20);
auto result = find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Window == window; });
if (result != windowInfos.end())
return;
}
}
void WindowsManager::Remove(Window* window)
{
HWND hwnd = GetHwndByWindow(window);
DestroyWindow(hwnd);
window->Closed(window, null);
}
void Mover::OnPointerMove(void* origin, PointerPositionEvent pointerPositionEvent)
{
}
void Mover::OnPointerIn(void* origin, PointerEvent pointerEvent)
{
}
void Mover::OnPointerOut(void* origin, PointerEvent pointerEvent)
{
}
void Mover::OnPointerDown(void* origin, PointerEvent pointerEvent)
{
HWND hwnd = GetHwndByWindow(window);
SendMessage(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, NULL);
}
void Mover::OnPointerUp(void* origin, PointerEvent pointerEvent)
{
}
#endif
| 33.06367
| 269
| 0.617864
|
jbatonnet
|
cfbaa3403fe6083a83b359001d88539239ef0d88
| 769
|
cpp
|
C++
|
WumbukDraw/line.cpp
|
YangPeihao1203/WumbukDraw
|
e0854e62cc050c99deda04a849d46824f458cbbc
|
[
"MIT"
] | null | null | null |
WumbukDraw/line.cpp
|
YangPeihao1203/WumbukDraw
|
e0854e62cc050c99deda04a849d46824f458cbbc
|
[
"MIT"
] | null | null | null |
WumbukDraw/line.cpp
|
YangPeihao1203/WumbukDraw
|
e0854e62cc050c99deda04a849d46824f458cbbc
|
[
"MIT"
] | null | null | null |
#include "line.h"
Line::Line()
{
setAdjustFlag(false);
}
void Line::startDraw(QGraphicsSceneMouseEvent * event)
{
QPen pen = this->pen();
pen.setWidth(this->width);
pen.setColor(this->color);
setPen(pen);
startPos=event->scenePos();
}
void Line::drawing(QGraphicsSceneMouseEvent * event)
{
EndPos=event->scenePos();
QLineF newLine(startPos,EndPos);
setLine(newLine);
}
void Line::endDraw(QGraphicsSceneMouseEvent *event)
{
}
bool Line::CheckIsContainsPoint(QPointF p)
{
return shape().contains(p);
}
void Line::setAdjustFlag(bool val)
{
setFlag(QGraphicsItem::ItemIsMovable, val);
setFlag(QGraphicsItem::ItemIsSelectable, val);
setFlag(QGraphicsItem::ItemIsFocusable, val);
}
| 18.756098
| 55
| 0.6671
|
YangPeihao1203
|
cfbc414efa03b4d00846bddacc360efa3e6b71df
| 16,075
|
cpp
|
C++
|
diffsim_torch3d/arcsim/src/simulation.cpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
diffsim_torch3d/arcsim/src/simulation.cpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
diffsim_torch3d/arcsim/src/simulation.cpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "simulation.hpp"
#include "collision.hpp"
#include "dynamicremesh.hpp"
#include "geometry.hpp"
#include "magic.hpp"
#include "nearobs.hpp"
#include "physics.hpp"
#include "plasticity.hpp"
#include "popfilter.hpp"
#include "proximity.hpp"
#include "separate.hpp"
#include "obstacle.hpp"
#include <iostream>
#include <fstream>
using namespace std;
using torch::Tensor;
static const bool verbose = false;
static const int proximity = Simulation::Proximity,
physics = Simulation::Physics,
strainlimiting = Simulation::StrainLimiting,
collision = Simulation::Collision,
remeshing = Simulation::Remeshing,
separation = Simulation::Separation,
popfilter = Simulation::PopFilter,
plasticity = Simulation::Plasticity;
void physics_step (Simulation &sim, const vector<Constraint*> &cons);
void plasticity_step (Simulation &sim);
void strainlimiting_step (Simulation &sim, const vector<Constraint*> &cons);
void strainzeroing_step (Simulation &sim);
void equilibration_step (Simulation &sim);
void collision_step (Simulation &sim);
void remeshing_step (Simulation &sim, bool initializing=false);
void validate_handles (const Simulation &sim);
void prepare (Simulation &sim) {
sim.step = 0;
sim.frame = 0;
sim.cloth_meshes.resize(sim.cloths.size());
for (int c = 0; c < sim.cloths.size(); c++) {
compute_masses(sim.cloths[c]);
sim.cloth_meshes[c] = &sim.cloths[c].mesh;
update_x0(*sim.cloth_meshes[c]);
}
sim.obstacle_meshes.resize(sim.obstacles.size());
for (int o = 0; o < sim.obstacles.size(); o++) {
obs_compute_masses(sim.obstacles[o]);
sim.obstacle_meshes[o] = &sim.obstacles[o].get_mesh();
update_x0(*sim.obstacle_meshes[o]);
}
}
void relax_initial_state (Simulation &sim) {
validate_handles(sim);
return;
if (::magic.preserve_creases)
for (int c = 0; c < sim.cloths.size(); c++)
reset_plasticity(sim.cloths[c]);
bool equilibrate = true;
if (equilibrate) {
equilibration_step(sim);
remeshing_step(sim, true);
equilibration_step(sim);
} else {
remeshing_step(sim, true);
strainzeroing_step(sim);
remeshing_step(sim, true);
strainzeroing_step(sim);
}
if (::magic.preserve_creases)
for (int c = 0; c < sim.cloths.size(); c++)
reset_plasticity(sim.cloths[c]);
::magic.preserve_creases = false;
if (::magic.fixed_high_res_mesh)
sim.enabled[remeshing] = false;
}
void validate_handles (const Simulation &sim) {
for (int h = 0; h < sim.handles.size(); h++) {
vector<Node*> nodes = sim.handles[h]->get_nodes();
for (int n = 0; n < nodes.size(); n++) {
if (!nodes[n]->preserve) {
cout << "Constrained node " << nodes[n]->index << " will not be preserved by remeshing" << endl;
abort();
}
}
}
}
vector<Constraint*> get_constraints (Simulation &sim, bool include_proximity);
void delete_constraints (const vector<Constraint*> &cons);
void update_obstacles (Simulation &sim, bool update_positions=true);
void advance_step (Simulation &sim);
void advance_frame (Simulation &sim) {
for (int s = 0; s < sim.frame_steps; s++)
advance_step(sim);
}
void advance_step (Simulation &sim) {
Timer ti;
ti.tick();
sim.time = sim.time + sim.step_time;
sim.step++;
// cout << "\t\tstep=" << sim.step << endl;
update_obstacles(sim, false);
vector<Constraint*> cons = get_constraints(sim, true);
physics_step(sim, cons);
//plasticity_step(sim);
//strainlimiting_step(sim, cons);
collision_step(sim);
if (sim.step % sim.frame_steps == 0) {
remeshing_step(sim);
sim.frame++;
// cout << "\t\t\tframe="<<sim.frame<<endl;
}
delete_constraints(cons);
ti.tock();
// cout << "\t\ttime= "<< ti.last << endl;
}
vector<Constraint*> get_constraints (Simulation &sim, bool include_proximity) {
// cout << "get_constraints" << endl;
vector<Constraint*> cons;
for (int h = 0; h < sim.handles.size(); h++)
append(cons, sim.handles[h]->get_constraints(sim.time));
// PRIYA
if (include_proximity && sim.enabled[proximity]) {
sim.timers[proximity].tick();
append(cons, proximity_constraints(sim.cloth_meshes,
sim.obstacle_meshes,
sim.friction, sim.obs_friction));
sim.timers[proximity].tock();
}
return cons;
}
void delete_constraints (const vector<Constraint*> &cons) {
for (int c = 0; c < cons.size(); c++)
delete cons[c];
}
// Steps
void update_velocities (vector<Mesh*> &meshes, vector<Tensor> &xold, Tensor dt);
void step_mesh (Mesh &mesh, Tensor dt);
void step_obstacle (Obstacle &obstacle, Tensor dt);
void physics_step (Simulation &sim, const vector<Constraint*> &cons) {
// cout << "physics_step" << endl;
if (!sim.enabled[physics])
return;
sim.timers[physics].tick();
for (int c = 0; c < sim.cloths.size(); c++) {
int nn = sim.cloths[c].mesh.nodes.size();
Tensor fext = torch::zeros({nn,3}, TNOPT)*0;
Tensor Jext = torch::zeros({nn,3,3}, TNOPT);
add_external_forces(sim.cloths[c], sim.gravity, sim.wind, fext, Jext);
for (int m = 0; m < sim.morphs.size(); m++)
if (sim.morphs[m].mesh == &sim.cloths[c].mesh)
add_morph_forces(sim.cloths[c], sim.morphs[m], sim.time,
sim.step_time, fext, Jext);
implicit_update(sim.cloths[c], fext, Jext, cons, sim.step_time, false);
}
for (int o = 0; o < sim.obstacles.size(); o++) {
int nn = 2;
Tensor fext = torch::zeros({nn,3}, TNOPT);
Tensor Jext = torch::zeros({nn,3,3}, TNOPT);
// just for test
obs_add_external_forces(sim.obstacles[o], sim.gravity, sim.wind, fext, Jext);
//fext = fext;
//cout << "obs fext = " << fext << endl;
obs_implicit_update(sim.obstacles[o], sim.obstacle_meshes, fext, Jext, cons, sim.step_time, false);
}
for (int c = 0; c < sim.cloth_meshes.size(); c++)
step_mesh(*sim.cloth_meshes[c], sim.step_time);
//for (int o = 0; o < sim.obstacle_meshes.size(); o++)
// step_mesh(*sim.obstacle_meshes[o], sim.step_time);
for (int o = 0; o < sim.obstacles.size(); o++)
step_obstacle(sim.obstacles[o], sim.step_time);
sim.timers[physics].tock();
}
void step_mesh (Mesh &mesh, Tensor dt) {
for (int n = 0; n < mesh.nodes.size(); n++) {
mesh.nodes[n]->x = mesh.nodes[n]->x + mesh.nodes[n]->v*dt;
mesh.nodes[n]->xold = mesh.nodes[n]->x;
}
}
// void apply_transformation (Mesh& mesh, const Transformation& tr) {
// apply_transformation_onto(mesh, mesh, tr);
//}
void step_obstacle (Obstacle &obstacle, Tensor dt) {
Node *dummy_node = obstacle.curr_state_mesh.dummy_node;
//cout << "velocity -------------" << endl;
////cout << dummy_node->x0 ;
//cout << dummy_node->x ;
if (dummy_node->movable)
dummy_node->x = dummy_node->v * dt + dummy_node->x;
dummy_node->xold = dummy_node->x;
//cout << dummy_node->x0 ;
Tensor euler = dummy_node->x.slice(0, 0, 3);
Tensor trans = dummy_node->x.slice(0, 3, 6);
Transformation tr;
tr.rotation = Quaternion::from_euler(euler);
tr.translation = trans;
tr.scale = dummy_node->scale;
//cout << tr.rotation << endl;
//cout << tr.translation << endl;
//cout << tr.scale << endl;
//cout << "step_obstacle" << endl;
apply_transformation_onto(obstacle.base_mesh, obstacle.curr_state_mesh, tr);
Mesh &mesh = obstacle.curr_state_mesh;
for (int n = 0; n < mesh.nodes.size(); n++) {
mesh.nodes[n]->xold = mesh.nodes[n]->x;
}
}
void plasticity_step (Simulation &sim) {
if (!sim.enabled[plasticity])
return;
// cout << "plasticity_step" << endl;
sim.timers[plasticity].tick();
for (int c = 0; c < sim.cloths.size(); c++) {
plastic_update(sim.cloths[c]);
optimize_plastic_embedding(sim.cloths[c]);
}
sim.timers[plasticity].tock();
}
void strainlimiting_step (Simulation &sim, const vector<Constraint*> &cons) {
// cout << "strainlimiting_step" << endl;
}
void equilibration_step (Simulation &sim) {
sim.timers[remeshing].tick();
vector<Constraint*> cons;// = get_constraints(sim, true);
// double stiff = 1;
// swap(stiff, ::magic.handle_stiffness);
for (int c = 0; c < sim.cloths.size(); c++) {
Mesh &mesh = sim.cloths[c].mesh;
for (int n = 0; n < mesh.nodes.size(); n++)
mesh.nodes[n]->acceleration = ZERO3;
apply_pop_filter(sim.cloths[c], cons, 1);
}
// swap(stiff, ::magic.handle_stiffness);
sim.timers[remeshing].tock();
delete_constraints(cons);
cons = get_constraints(sim, false);
if (sim.enabled[collision]) {
sim.timers[collision].tick();
collision_response(sim, sim.cloth_meshes, cons, sim.obstacle_meshes);
sim.timers[collision].tock();
}
delete_constraints(cons);
}
void strainzeroing_step (Simulation &sim) {
}
void collision_step (Simulation &sim) {
if (!sim.enabled[collision])
return;
// cout << "collision_step" << endl;
sim.timers[collision].tick();
vector<Tensor> xold = node_positions(sim.cloth_meshes);
vector<Constraint*> cons = get_constraints(sim, false);
collision_response(sim, sim.cloth_meshes, cons, sim.obstacle_meshes);
delete_constraints(cons);
update_velocities(sim.cloth_meshes, xold, sim.step_time);
sim.timers[collision].tock();
}
void remeshing_step (Simulation &sim, bool initializing) {
if (!sim.enabled[remeshing])
return;
// copy old meshes
vector<Mesh> old_meshes(sim.cloths.size());
vector<Mesh*> old_meshes_p(sim.cloths.size()); // for symmetry in separate()
for (int c = 0; c < sim.cloths.size(); c++) {
old_meshes[c] = deep_copy(sim.cloths[c].mesh);
old_meshes_p[c] = &old_meshes[c];
}
// back up residuals
typedef vector<Residual> MeshResidual;
vector<MeshResidual> res;
if (sim.enabled[plasticity] && !initializing) {
sim.timers[plasticity].tick();
res.resize(sim.cloths.size());
for (int c = 0; c < sim.cloths.size(); c++)
res[c] = back_up_residuals(sim.cloths[c].mesh);
sim.timers[plasticity].tock();
}
// remesh
sim.timers[remeshing].tick();
for (int c = 0; c < sim.cloths.size(); c++) {
if (::magic.fixed_high_res_mesh)
static_remesh(sim.cloths[c]);
else {
vector<Plane> planes = nearest_obstacle_planes(sim.cloths[c].mesh,
sim.obstacle_meshes);
dynamic_remesh(sim.cloths[c], planes, sim.enabled[plasticity]);
}
}
sim.timers[remeshing].tock();
// restore residuals
if (sim.enabled[plasticity] && !initializing) {
sim.timers[plasticity].tick();
for (int c = 0; c < sim.cloths.size(); c++)
restore_residuals(sim.cloths[c].mesh, old_meshes[c], res[c]);
sim.timers[plasticity].tock();
}
// separate
if (sim.enabled[separation]) {
sim.timers[separation].tick();
separate(sim.cloth_meshes, old_meshes_p, sim.obstacle_meshes);
sim.timers[separation].tock();
}
// apply pop filter
if (sim.enabled[popfilter] && !initializing) {
sim.timers[popfilter].tick();
vector<Constraint*> cons = get_constraints(sim, true);
for (int c = 0; c < sim.cloths.size(); c++)
apply_pop_filter(sim.cloths[c], cons);
delete_constraints(cons);
sim.timers[popfilter].tock();
}
// delete old meshes
for (int c = 0; c < sim.cloths.size(); c++)
delete_mesh(old_meshes[c]);
}
void update_velocities (vector<Mesh*> &meshes, vector<Tensor> &xold, Tensor dt) {
Tensor inv_dt = 1/dt;
#pragma omp parallel for
for (int n = 0; n < xold.size(); n++) {
Node *node = get<Node>(n, meshes);
node->v = node->v + (node->x - xold[n])*inv_dt;
}
}
void update_obstacles (Simulation &sim, bool update_positions) {
// cout << "update_obstacles" << endl;
for (int o = 0; o < sim.obstacles.size(); o++) {
sim.obstacles[o].get_mesh(sim.time);
// sim.obstacles[o].blend_with_previous(sim.time, sim.step_time, blend);
if (!update_positions) {
// put positions back where they were
Mesh &mesh = sim.obstacles[o].get_mesh();
for (int n = 0; n < mesh.nodes.size(); n++) {
Node *node = mesh.nodes[n];
node->v = (node->x - node->x0)/sim.step_time;
node->x = node->x0;
}
}
}
}
// Helper functions
template <typename Prim> int size (const vector<Mesh*> &meshes) {
int np = 0;
for (int m = 0; m < meshes.size(); m++) np += get<Prim>(*meshes[m]).size();
return np;
}
template int size<Vert> (const vector<Mesh*>&);
template int size<Node> (const vector<Mesh*>&);
template int size<Edge> (const vector<Mesh*>&);
template int size<Face> (const vector<Mesh*>&);
template <typename Prim> int get_index (const Prim *p,
const vector<Mesh*> &meshes) {
int i = 0;
for (int m = 0; m < meshes.size(); m++) {
const vector<Prim*> &ps = get<Prim>(*meshes[m]);
if (p->index < ps.size() && p == ps[p->index])
return i + p->index;
else i += ps.size();
}
return -1;
}
template int get_index (const Vert*, const vector<Mesh*>&);
template int get_index (const Node*, const vector<Mesh*>&);
template int get_index (const Edge*, const vector<Mesh*>&);
template int get_index (const Face*, const vector<Mesh*>&);
template <typename Prim> Prim *get (int i, const vector<Mesh*> &meshes) {
for (int m = 0; m < meshes.size(); m++) {
const vector<Prim*> &ps = get<Prim>(*meshes[m]);
if (i < ps.size())
return ps[i];
else
i -= ps.size();
}
return NULL;
}
template Vert *get (int, const vector<Mesh*>&);
template Node *get (int, const vector<Mesh*>&);
template Edge *get (int, const vector<Mesh*>&);
template Face *get (int, const vector<Mesh*>&);
vector<Tensor> node_positions (const vector<Mesh*> &meshes) {
vector<Tensor> xs(size<Node>(meshes));
for (int n = 0; n < xs.size(); n++)
xs[n] = get<Node>(n, meshes)->x;
return xs;
}
| 34.869848
| 112
| 0.612877
|
priyasundaresan
|
cfbc9166cf99ff55eb9d15aacb24a713551f7d21
| 2,707
|
hpp
|
C++
|
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/queue_blocks.hpp
|
yklishevich/RubetekIOS-CPP-releases
|
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
|
[
"MIT"
] | null | null | null |
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/queue_blocks.hpp
|
yklishevich/RubetekIOS-CPP-releases
|
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
|
[
"MIT"
] | null | null | null |
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/queue_blocks.hpp
|
yklishevich/RubetekIOS-CPP-releases
|
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
|
[
"MIT"
] | null | null | null |
#pragma once
#include <queue>
#include <msw/buffer.hpp>
namespace dawn
{
struct queue_blocks
{
typedef msw::range<msw::byte> block ;
typedef msw::range<msw::byte const> const_block ;
queue_blocks () ;
queue_blocks (queue_blocks&&) ;
bool empty () const ;
bool has_blocks () const ;
std::size_t count () const ;
msw::size<msw::byte> size () const ;
block front () ;
const_block front () const ;
block back () ;
const_block back () const ;
void push (const_block) ;
void pop () ;
msw::buffer<msw::byte> pull () ;
private:
std::queue<msw::buffer<msw::byte>> blocks_ ;
msw::size<msw::byte> size_ ;
};
}
namespace dawn
{
inline queue_blocks::queue_blocks()
{}
inline queue_blocks::queue_blocks(queue_blocks&& other)
: blocks_ (std::move(other.blocks_))
, size_ (std::move(other.size_ ))
{}
inline bool queue_blocks::empty() const
{
return blocks_.empty();
}
inline bool queue_blocks::has_blocks() const
{
return !empty();
}
inline std::size_t queue_blocks::count() const
{
return blocks_.size();
}
inline msw::size<msw::byte> queue_blocks::size() const
{
return size_;
}
inline queue_blocks::block queue_blocks::front()
{
return blocks_.front().all();
}
inline queue_blocks::const_block queue_blocks::front() const
{
return blocks_.front().all();
}
inline queue_blocks::block queue_blocks::back()
{
return blocks_.back().all();
}
inline queue_blocks::const_block queue_blocks::back() const
{
return blocks_.back().all();
}
inline void queue_blocks::push(const_block blk)
{
blocks_.emplace(blk);
size_ += blk.size();
}
inline void queue_blocks::pop()
{
size_ -= front().size();
blocks_.pop();
}
inline msw::buffer<msw::byte> queue_blocks::pull()
{
size_ -= front().size();
msw::buffer<msw::byte> blk = std::move(blocks_.front());
blocks_.pop();
return std::move(blk);
}
}
| 27.07
| 67
| 0.461396
|
yklishevich
|
cfbe411ee255d884970fca91398de8142dd8ec8c
| 7,250
|
hpp
|
C++
|
math/rotation.hpp
|
melowntech/libmath
|
7a473801a93ba5e244d96e773b412a3abed4a400
|
[
"BSD-2-Clause"
] | 1
|
2021-09-02T08:42:59.000Z
|
2021-09-02T08:42:59.000Z
|
externals/browser/externals/browser/externals/libmath/math/rotation.hpp
|
HanochZhu/vts-browser-unity-plugin
|
32a22d41e21b95fb015326f95e401d87756d0374
|
[
"BSD-2-Clause"
] | 2
|
2020-06-09T12:06:16.000Z
|
2021-10-06T08:15:04.000Z
|
externals/browser/externals/browser/externals/libmath/math/rotation.hpp
|
HanochZhu/vts-browser-unity-plugin
|
32a22d41e21b95fb015326f95e401d87756d0374
|
[
"BSD-2-Clause"
] | 1
|
2019-09-25T05:20:17.000Z
|
2019-09-25T05:20:17.000Z
|
/**
* Copyright (c) 2017 Melown Technologies SE
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file rotation.hpp
* @author Jakub Cerveny <jakub.cerveny@ext.citationtech.net>
*
* Math related to rotations.
*/
#ifndef MATH_ROTATION_HPP
#define MATH_ROTATION_HPP
#include "geometry_core.hpp"
namespace math {
/** Converts a rotation vector (see below) to a rotation matrix.
*/
inline Matrix4 rotationMatrix(const Point3 & rvec)
{
Matrix4 m( ublas::identity_matrix<double>(4) );
double angle = ublas::norm_2(rvec);
if (std::abs(angle) < 1e-10) { return m; }
Point3 vec(rvec * (1.0 / angle));
double s = sin(angle),
c = cos(angle);
double xx = vec(0) * vec(0),
yy = vec(1) * vec(1),
zz = vec(2) * vec(2),
xy = vec(0) * vec(1),
yz = vec(1) * vec(2),
zx = vec(2) * vec(0);
double xs = vec(0) * s,
ys = vec(1) * s,
zs = vec(2) * s;
double one_c = 1.0 - c;
m(0, 0) = (one_c * xx) + c;
m(0, 1) = (one_c * xy) - zs;
m(0, 2) = (one_c * zx) + ys;
m(1, 0) = (one_c * xy) + zs;
m(1, 1) = (one_c * yy) + c;
m(1, 2) = (one_c * yz) - xs;
m(2, 0) = (one_c * zx) - ys;
m(2, 1) = (one_c * yz) + xs;
m(2, 2) = (one_c * zz) + c;
return m;
}
/** Converts a rotation matrix to a rotation vector, whose direction represents
* the axis of rotation and its magnitude represents the angle of rotation
* in radians.
*/
inline Point3 rotationVector(const Matrix4 & mat)
{
double angle = acos(0.5 * (mat(0,0) + mat(1,1) + mat(2,2) - 1.0));
Point3 axis(mat(2,1) - mat(1,2),
mat(0,2) - mat(2,0),
mat(1,0) - mat(0,1));
return angle / (2*sin(angle)) * axis;
}
/** Quaternion -- represents a rotation.
*/
class Quaternion
{
public:
Quaternion()
: x(0.0), y(0.0), z(0.0), w(1.0) {}
Quaternion(double x, double y, double z, double w)
: x(x), y(y), z(z), w(w) {}
Quaternion(const Quaternion& q)
{ x = q.x; y = q.y; z = q.z; w = q.w; }
Quaternion& operator=(const Quaternion& q)
{ x = q.x; y = q.y; z = q.z; w = q.w; return *this; }
Quaternion(const Matrix4& mat)
{ fromMatrix(mat); }
/// Converts a matrix to a quaternion.
void fromMatrix(const Matrix4& m);
/// Converts this quaternion to a matrix.
Matrix4 toMatrix() const;
Quaternion& normalize();
Quaternion operator+(const Quaternion& other) const;
Quaternion operator*(const Quaternion& other) const;
Quaternion operator*(double scalar) const;
Quaternion& operator*=(double scalar);
Quaternion& operator*=(const Quaternion& other);
double x, y, z; // imaginary part
double w; // real part
};
inline Quaternion Quaternion::operator*(double s) const
{
return Quaternion(s*x, s*y, s*z, s*w);
}
inline Quaternion& Quaternion::operator*=(double s)
{
x*=s; y*=s; z*=s; w*=s;
return *this;
}
inline Quaternion& Quaternion::operator*=(const Quaternion& other)
{
return (*this = other * (*this));
}
inline Quaternion Quaternion::operator+(const Quaternion& b) const
{
return Quaternion(x+b.x, y+b.y, z+b.z, w+b.w);
}
inline Quaternion Quaternion::operator*(const Quaternion& other) const
{
Quaternion tmp;
tmp.w = (other.w * w) - (other.x * x) - (other.y * y) - (other.z * z);
tmp.x = (other.w * x) + (other.x * w) + (other.y * z) - (other.z * y);
tmp.y = (other.w * y) + (other.y * w) + (other.z * x) - (other.x * z);
tmp.z = (other.w * z) + (other.z * w) + (other.x * y) - (other.y * x);
return tmp;
}
inline void Quaternion::fromMatrix(const Matrix4& m)
{
const double diag = m(0,0) + m(1,1) + m(2,2) + 1;
if (diag > 0.0)
{
const double scale = sqrt(diag) * 2.0; // get scale from diagonal
x = (m(2,1) - m(1,2)) / scale;
y = (m(0,2) - m(2,0)) / scale;
z = (m(1,0) - m(0,1)) / scale;
w = 0.25 * scale;
}
else
{
if (m(0,0) > m(1,1) && m(0,0) > m(2,2))
{
// 1st element of diag is greatest value
// find scale according to 1st element, and double it
const double scale = sqrt( 1.0 + m(0,0) - m(1,1) - m(2,2)) * 2.0;
x = 0.25 * scale;
y = (m(0,1) + m(1,0)) / scale;
z = (m(2,0) + m(0,2)) / scale;
w = (m(2,1) - m(1,2)) / scale;
}
else if (m(1,1) > m(2,2))
{
// 2nd element of diag is greatest value
// find scale according to 2nd element, and double it
const double scale = sqrt( 1.0 + m(1,1) - m(0,0) - m(2,2)) * 2.0;
x = (m(0,1) + m(1,0) ) / scale;
y = 0.25 * scale;
z = (m(1,2) + m(2,1) ) / scale;
w = (m(0,2) - m(2,0) ) / scale;
}
else
{
// 3rd element of diag is greatest value
// find scale according to 3rd element, and double it
const double scale = sqrt( 1.0 + m(2,2) - m(0,0) - m(1,1)) * 2.0;
x = (m(0,2) + m(2,0)) / scale;
y = (m(1,2) + m(2,1)) / scale;
z = 0.25 * scale;
w = (m(1,0) - m(0,1)) / scale;
}
}
normalize();
}
inline Quaternion& Quaternion::normalize()
{
double n = x*x + y*y + z*z + w*w;
*this *= 1.0 / sqrt(n);
return *this;
}
inline Matrix4 Quaternion::toMatrix() const
{
Matrix4 m = ublas::identity_matrix<double>(4);
m(0,0) = 1.0 - 2.0*y*y - 2.0*z*z;
m(1,0) = 2.0*x*y + 2.0*z*w;
m(2,0) = 2.0*x*z - 2.0*y*w;
m(3,0) = 0.0;
m(0,1) = 2.0*x*y - 2.0*z*w;
m(1,1) = 1.0 - 2.0*x*x - 2.0*z*z;
m(2,1) = 2.0*z*y + 2.0*x*w;
m(3,1) = 0.0;
m(0,2) = 2.0*x*z + 2.0*y*w;
m(1,2) = 2.0*z*y - 2.0*x*w;
m(2,2) = 1.0 - 2.0*x*x - 2.0*y*y;
m(3,2) = 0.0;
m(0,3) = 0.0;
m(1,3) = 0.0;
m(2,3) = 0.0;
m(3,3) = 1.0;
return m;
}
} // namespace math
#endif
| 27.358491
| 79
| 0.549379
|
melowntech
|
cfbf77748654b7c729a4e77abbb95f491baf1e66
| 1,934
|
cpp
|
C++
|
Scratch Pencil Photo/Main.cpp
|
bayudwiyansatria/computer-vision
|
1cfe27441b0c92ac23195ed3c574daef1677d18a
|
[
"MIT"
] | 1
|
2019-05-27T17:54:32.000Z
|
2019-05-27T17:54:32.000Z
|
Scratch Pencil Photo/Main.cpp
|
bayudwiyansatria/computer-vision
|
1cfe27441b0c92ac23195ed3c574daef1677d18a
|
[
"MIT"
] | null | null | null |
Scratch Pencil Photo/Main.cpp
|
bayudwiyansatria/computer-vision
|
1cfe27441b0c92ac23195ed3c574daef1677d18a
|
[
"MIT"
] | 1
|
2018-11-02T02:29:03.000Z
|
2018-11-02T02:29:03.000Z
|
#include <opencv/cv.h>
#include <opencv/highgui.h>
int main(int argc, char** argv)
{
int col_1, row_1;
uchar b_1, g_1, r_1, b_2, g_2, r_2, b_d, g_d, r_d;
IplImage* img = cvLoadImage("Theory/Scratch Pencil Photo/Input/lena.jpg");
IplImage* img1 = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels);
IplImage* img2 = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels);
IplImage* dst = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels);
IplImage* gray = cvCreateImage(cvGetSize(img), img->depth, 1);
cvNamedWindow("Input", CV_WINDOW_AUTOSIZE);
cvNamedWindow("Output", CV_WINDOW_AUTOSIZE);
cvShowImage("Input", img);
cvNot(img, img1);
// cvSmooth(img1, img2, CV_BLUR, 25,25,0,0);
cvSmooth(img, img2, CV_GAUSSIAN, 7, 7, 0, 0);
for (row_1 = 0; row_1 < img1->height; row_1++)
{
for (col_1 = 0; col_1 < img1->width; col_1++)
{
b_1 = CV_IMAGE_ELEM(img1, uchar, row_1, col_1 * 3);
g_1 = CV_IMAGE_ELEM(img1, uchar, row_1, col_1 * 3 + 1);
r_1 = CV_IMAGE_ELEM(img1, uchar, row_1, col_1 * 3 + 2);
b_2 = CV_IMAGE_ELEM(img2, uchar, row_1, col_1 * 3);
g_2 = CV_IMAGE_ELEM(img2, uchar, row_1, col_1 * 3 + 1);
r_2 = CV_IMAGE_ELEM(img2, uchar, row_1, col_1 * 3 + 2);
// b_d = b_1 + b_2;
// g_d = g_1 + g_2;
// r_d = r_1 + r_2;
b_d = std::min(255, b_1 + b_2);
g_d = std::min(255, g_1 + g_2);
r_d = std::min(255, r_1 + r_2);
dst->imageData[img1->widthStep * row_1 + col_1 * 3] = b_d;
dst->imageData[img1->widthStep * row_1 + col_1 * 3 + 1] = g_d;
dst->imageData[img1->widthStep * row_1 + col_1 * 3 + 2] = r_d;
}
}
cvCvtColor(dst, gray, CV_BGR2GRAY);
cvShowImage("Output", gray);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&img1);
cvReleaseImage(&img2);
cvReleaseImage(&dst);
cvReleaseImage(&gray);
cvDestroyWindow("Input");
cvDestroyWindow("Output");
}
| 32.233333
| 93
| 0.640641
|
bayudwiyansatria
|
cfc100bde1c5aae9d74ba6d1e7071f3bd1096362
| 3,215
|
cpp
|
C++
|
src/common/timer/timer_1ms.cpp
|
caozhiyi/quicX
|
46b486fc7786faf479b60c24da8ebdec783b3d5b
|
[
"BSD-3-Clause"
] | 1
|
2021-11-02T14:31:12.000Z
|
2021-11-02T14:31:12.000Z
|
src/common/timer/timer_1ms.cpp
|
caozhiyi/quicX
|
46b486fc7786faf479b60c24da8ebdec783b3d5b
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/timer/timer_1ms.cpp
|
caozhiyi/quicX
|
46b486fc7786faf479b60c24da8ebdec783b3d5b
|
[
"BSD-3-Clause"
] | 1
|
2021-09-30T08:23:58.000Z
|
2021-09-30T08:23:58.000Z
|
// Use of this source code is governed by a BSD 3-Clause License
// that can be found in the LICENSE file.
// Author: caozhiyi (caozhiyi5@gmail.com)
#include "timer_1ms.h"
namespace quicx {
static const TIMER_CAPACITY __timer_accuracy = TC_1MS; // 1 millisecond
static const TIMER_CAPACITY __timer_capacity = TC_50MS; // 50 millisecond
Timer1ms::Timer1ms() : _cur_index(0) {
_timer_wheel.resize(__timer_capacity);
_bitmap.Init(__timer_capacity);
}
Timer1ms::~Timer1ms() {
}
bool Timer1ms::AddTimer(std::weak_ptr<TimerSolt> t, uint32_t time, bool always) {
if (time >= __timer_capacity) {
return false;
}
auto ptr = t.lock();
if (!ptr) {
return false;
}
if (ptr->IsInTimer()) {
return true;
}
if (always) {
ptr->SetAlways(__timer_accuracy);
}
ptr->SetInterval(time);
time += _cur_index;
if (time > __timer_capacity) {
time %= __timer_capacity;
}
ptr->SetIndex(time);
ptr->SetTimer();
_timer_wheel[time].push_back(t);
return _bitmap.Insert(time);
}
bool Timer1ms::RmTimer(std::weak_ptr<TimerSolt> t) {
auto ptr = t.lock();
if (!ptr) {
return false;
}
auto index = ptr->GetIndex(__timer_accuracy);
bool ret = _bitmap.Remove(index);
ptr->RmTimer();
return ret;
}
int32_t Timer1ms::CurrentTimer() {
return _cur_index;
}
int32_t Timer1ms::MinTime() {
if (_bitmap.Empty()) {
return NO_TIMER;
}
int32_t next_setp = _bitmap.GetMinAfter(_cur_index);
if (next_setp >= 0) {
return next_setp - _cur_index;
}
if (_cur_index > 0) {
next_setp = _bitmap.GetMinAfter(0);
}
if (next_setp >= 0) {
return next_setp + __timer_capacity - _cur_index;
}
return NO_TIMER;
}
uint32_t Timer1ms::TimerRun(uint32_t time) {
time = time % __timer_capacity;
_cur_index += time;
uint32_t ret = 0;
if (_cur_index >= __timer_capacity) {
_cur_index %= __timer_capacity;
ret++;
}
auto& bucket = _timer_wheel[_cur_index];
if (bucket.size() > 0) {
for (auto iter = bucket.begin(); iter != bucket.end();) {
auto ptr = (iter)->lock();
if (ptr && ptr->IsInTimer()) {
ptr->OnTimer();
}
// remove from current bucket
iter = bucket.erase(iter);
_bitmap.Remove(ptr->GetIndex(__timer_accuracy));
if (!ptr->IsAlways(__timer_accuracy) || !ptr->IsInTimer()) {
ptr->RmTimer();
continue;
} else {
// add to timer again
uint16_t next_index = ptr->GetInterval() + _cur_index;
if (next_index >= __timer_capacity) {
next_index = next_index % __timer_capacity;
}
AddTimerByIndex(ptr, uint8_t(next_index));
}
}
}
return ret;
}
void Timer1ms::AddTimerByIndex(std::weak_ptr<TimerSolt> t, uint8_t index) {
auto ptr = t.lock();
if (!ptr) {
return;
}
ptr->SetIndex(index, TC_1MS);
_timer_wheel[index].push_back(t);
_bitmap.Insert(index);
}
}
| 22.640845
| 81
| 0.576361
|
caozhiyi
|
cfc56aecda2a23487b740604cb490928ac2a12b8
| 1,893
|
cpp
|
C++
|
src/v3/action_constants.cpp
|
siyuan0322/etcd-cpp-apiv3
|
1575c5b43a64f85f77897e9b5aad24e6523ea453
|
[
"BSD-3-Clause"
] | 139
|
2016-09-20T00:28:04.000Z
|
2020-09-27T15:05:11.000Z
|
src/v3/action_constants.cpp
|
siyuan0322/etcd-cpp-apiv3
|
1575c5b43a64f85f77897e9b5aad24e6523ea453
|
[
"BSD-3-Clause"
] | 85
|
2020-09-29T16:33:00.000Z
|
2022-03-30T01:23:23.000Z
|
src/v3/action_constants.cpp
|
siyuan0322/etcd-cpp-apiv3
|
1575c5b43a64f85f77897e9b5aad24e6523ea453
|
[
"BSD-3-Clause"
] | 63
|
2016-12-06T11:42:29.000Z
|
2020-09-24T06:15:49.000Z
|
#include "etcd/v3/action_constants.hpp"
char const * etcdv3::CREATE_ACTION = "create";
char const * etcdv3::COMPARESWAP_ACTION = "compareAndSwap";
char const * etcdv3::UPDATE_ACTION = "update";
char const * etcdv3::SET_ACTION = "set";
char const * etcdv3::GET_ACTION = "get";
char const * etcdv3::PUT_ACTION = "put";
char const * etcdv3::DELETE_ACTION = "delete";
char const * etcdv3::COMPAREDELETE_ACTION = "compareAndDelete";
char const * etcdv3::LOCK_ACTION = "lock";
char const * etcdv3::UNLOCK_ACTION = "unlock";
char const * etcdv3::TXN_ACTION = "txn";
char const * etcdv3::WATCH_ACTION = "watch";
char const * etcdv3::LEASEGRANT = "leasegrant";
char const * etcdv3::LEASEREVOKE = "leaserevoke";
char const * etcdv3::LEASEKEEPALIVE = "leasekeepalive";
char const * etcdv3::LEASETIMETOLIVE = "leasetimetolive";
char const * etcdv3::LEASELEASES = "leaseleases";
char const * etcdv3::CAMPAIGN_ACTION = "campaign";
char const * etcdv3::PROCLAIM_ACTION = "preclaim";
char const * etcdv3::LEADER_ACTION = "leader";
char const * etcdv3::OBSERVE_ACTION = "obverse";
char const * etcdv3::RESIGN_ACTION = "resign";
// see: noPrefixEnd in etcd, however c++ doesn't allows '\0' inside a string, thus we use
// the UTF-8 char U+0000 (i.e., "\xC0\x80").
char const * etcdv3::NUL = "\xC0\x80";
char const * etcdv3::KEEPALIVE_CREATE = "keepalive create";
char const * etcdv3::KEEPALIVE_WRITE = "keepalive write";
char const * etcdv3::KEEPALIVE_READ = "keepalive read";
char const * etcdv3::KEEPALIVE_DONE = "keepalive done";
char const * etcdv3::WATCH_CREATE = "watch create";
char const * etcdv3::WATCH_WRITE = "watch write";
char const * etcdv3::WATCH_WRITES_DONE = "watch writes done";
char const * etcdv3::ELECTION_OBSERVE_CREATE = "observe create";
const int etcdv3::ERROR_KEY_NOT_FOUND = 100;
const int etcdv3::ERROR_COMPARE_FAILED = 101;
const int etcdv3::ERROR_KEY_ALREADY_EXISTS = 105;
| 41.152174
| 89
| 0.733228
|
siyuan0322
|
cfc5afce8a871cbdf7809d3bd8833c1e30182e5b
| 4,823
|
cc
|
C++
|
src/Table.cc
|
mgonnav/flaviadb
|
af133b30ec97834753d4d24a682cb2691688a854
|
[
"Apache-2.0"
] | 1
|
2020-08-20T22:34:36.000Z
|
2020-08-20T22:34:36.000Z
|
src/Table.cc
|
mgonnav/flaviadb
|
af133b30ec97834753d4d24a682cb2691688a854
|
[
"Apache-2.0"
] | 1
|
2020-08-27T00:01:42.000Z
|
2020-11-27T17:18:58.000Z
|
src/Table.cc
|
mgonnav/flaviadb
|
af133b30ec97834753d4d24a682cb2691688a854
|
[
"Apache-2.0"
] | null | null | null |
#include "Where.hh"
#include "printutils.hh"
namespace ft = ftools;
namespace fs = std::filesystem;
namespace pu = printUtils;
Table::Table(std::string name)
{
this->name = name;
loadPaths(name);
checkTableExists();
load_metadata();
this->reg_count = ft::getRegCount(name);
this->indexes = new std::vector<Index*>;
loadIndexes();
}
void Table::loadPaths(std::string const& name)
{
this->path = ft::getTablePath(name);
this->regs_path = ft::getRegistersPath(name);
this->indexes_path = ft::getIndexesPath(name);
this->metadata_path = ft::getMetadataPath(name);
}
void Table::checkTableExists()
{
if (!ft::dirExists(this->path))
throw DBException{NON_EXISTING_TABLE, this->name};
}
bool Table::load_metadata()
{
openMetadataFile();
loadMetadataHeader();
for (auto& column : *this->columns)
loadColumnData(column);
return 1;
}
void Table::openMetadataFile()
{
this->metadata_file.open(this->metadata_path);
if (!this->metadata_file.is_open())
throw DBException{UNREADABLE_METADATA};
}
void Table::loadMetadataHeader()
{
loadTableName();
loadColumnCount();
loadRegSize();
}
void Table::loadTableName()
{
std::string metadata_table_name;
getline(this->metadata_file, metadata_table_name, '\t');
if (this->name != metadata_table_name)
throw DBException{DIFFERENT_METADATA_NAME};
}
void Table::loadColumnCount()
{
std::string column_count;
getline(this->metadata_file, column_count, '\t');
this->columns = new std::vector<hsql::ColumnDefinition*>(stoi(column_count));
}
void Table::loadRegSize()
{
std::string reg_size;
getline(this->metadata_file, reg_size, '\n');
this->reg_size = stoi(reg_size);
}
void Table::loadColumnData(hsql::ColumnDefinition*& column)
{
std::string data;
getline(this->metadata_file, data, '\t');
char* col_name = new char[data.size()];
strcpy(col_name, data.c_str());
hsql::ColumnType col_type = getColumnType();
getline(this->metadata_file, data, '\n');
bool col_nullable = stoi(data);
column = new hsql::ColumnDefinition(col_name, col_type, col_nullable);
}
void Table::loadIndexes()
{
for (const auto& reg : fs::directory_iterator(this->indexes_path))
{
std::string idx_name = reg.path().filename();
indexes->push_back(new Index(idx_name));
}
}
void Table::loadStoredRegisters()
{
this->registers =
std::make_unique<std::list<std::pair<std::string, RegisterData>>>();
for (const auto& reg : fs::directory_iterator(this->regs_path))
{
// Load data in file to reg_data
std::ifstream data_file(reg.path());
std::vector<std::string> reg_data;
// Load each piece of data into reg_data
std::string data;
for (size_t i = 0; i < this->columns->size(); i++)
{
getline(data_file, data, '\t');
reg_data.push_back(data);
}
this->registers->push_back({reg.path().filename(), RegisterData(reg_data)});
}
}
Table::Table(std::string name, std::vector<hsql::ColumnDefinition*>* cols)
{
this->name = name;
loadPaths(name);
this->indexes = new std::vector<Index*>;
createTableFolders();
this->columns = cols;
this->reg_size = calculateRegSize();
this->registers =
std::make_unique<std::list<std::pair<std::string, RegisterData>>>();
// Create medata.dat file for table
// and fill it with table's name & cols info
std::ofstream wMetadata(this->metadata_path);
wMetadata << this->name << "\t" << this->columns->size() << "\t"
<< this->reg_size << "\n";
for (const hsql::ColumnDefinition* col : *this->columns)
wMetadata << col->name << "\t" << (int)col->type.data_type << "\t"
<< col->type.length << "\t" << col->nullable << "\n";
wMetadata.close();
std::ofstream wCount(ft::getRegCountPath(this->name));
wCount << 0; // 0 regs when table is created
wCount.close();
std::cout << "Table " << this->name << " was created successfully.\n";
}
void Table::createTableFolders()
{
ft::createFolder(this->path);
ft::createFolder(this->regs_path);
ft::createFolder(this->indexes_path);
}
int Table::calculateRegSize()
{
int reg_size = 0;
for (const auto& col : *this->columns)
{
hsql::DataType data_type = col->type.data_type;
if (data_type == hsql::DataType::INT)
reg_size += 4;
else if (data_type == hsql::DataType::CHAR)
reg_size += col->type.length;
else if (data_type == hsql::DataType::DATE)
reg_size += 8;
}
return reg_size;
}
Table::~Table()
{
delete this->columns;
delete this->indexes;
}
hsql::ColumnType Table::getColumnType()
{
std::string data;
getline(this->metadata_file, data, '\t');
int col_enum = stoi(data);
getline(this->metadata_file, data, '\t');
int col_length = stoi(data);
hsql::ColumnType col_type((hsql::DataType)col_enum, col_length);
return col_type;
}
| 23.758621
| 80
| 0.667427
|
mgonnav
|
cfc723067d77b4f03d2ddc39c019224197156336
| 5,293
|
cpp
|
C++
|
SimulationsOMP/ParaUtilMSDRadix16Sort.cpp
|
COFS-UWA/MPM3D
|
1a0c5dc4e92dff3855367846002336ca5a18d124
|
[
"MIT"
] | null | null | null |
SimulationsOMP/ParaUtilMSDRadix16Sort.cpp
|
COFS-UWA/MPM3D
|
1a0c5dc4e92dff3855367846002336ca5a18d124
|
[
"MIT"
] | 2
|
2020-10-19T02:03:11.000Z
|
2021-03-19T16:34:39.000Z
|
SimulationsOMP/ParaUtilMSDRadix16Sort.cpp
|
COFS-UWA/MPM3D
|
1a0c5dc4e92dff3855367846002336ca5a18d124
|
[
"MIT"
] | 1
|
2020-04-28T00:33:14.000Z
|
2020-04-28T00:33:14.000Z
|
#include "SimulationsOMP_pcp.h"
#include "ParaUtil.h"
#include "ParaUtilSerialSort.h"
#include "ParaUtilMSDRadix16Sort.h"
#define Data_Digit(num, disp, mask) (((num) >> (disp)) & (mask))
#define Data_Digit_16(num, disp) Data_Digit(num, disp, 0xF)
namespace ParaUtil
{
namespace Internal
{
static constexpr uint64_t radix_num = 1 << msd_radix_16_bit_num;
static constexpr uint64_t radix_mask = radix_num - 1;
static constexpr uint64_t max_radix = radix_mask;
inline void prefix_scan_16_serial(
size_t keys[],
size_t data_num,
size_t bit_offset,
size_t sum_bin[radix_num])
{
size_t i;
memset(sum_bin, 0, radix_num * sizeof(size_t));
for (i = 0; i < data_num; ++i)
++sum_bin[Data_Digit_16(keys[i], bit_offset)];
for (i = 1; i < (radix_num - 1); ++i)
sum_bin[i] += sum_bin[i - 1];
for (i = radix_num - 1; i != 0; --i)
sum_bin[i] = sum_bin[i - 1];
sum_bin[0] = 0;
};
inline void swap_reorder_16_serial(
size_t keys[],
size_t values[],
size_t data_num,
size_t bit_offset,
size_t sum_bin[radix_num])
{
const size_t end_bin[radix_num] = {
sum_bin[1], sum_bin[2], sum_bin[3], sum_bin[4],
sum_bin[5], sum_bin[6], sum_bin[7], sum_bin[8],
sum_bin[9], sum_bin[10], sum_bin[11], sum_bin[12],
sum_bin[13], sum_bin[14], sum_bin[15], data_num
};
for (uint64_t radix = 0; radix < radix_num; ++radix)
{
size_t& data_pos = sum_bin[radix];
const size_t end_pos = end_bin[radix];
while (data_pos < end_pos)
{
uint64_t tmp_radix = Data_Digit_16(keys[data_pos], bit_offset);
if (tmp_radix != radix) // skip sorted part
{
// fill misplaced item by swap reordering
do
{
size_t& new_data_pos = sum_bin[tmp_radix];
size_t new_radix;
while ((new_radix = Data_Digit_16(keys[new_data_pos], bit_offset)) == tmp_radix)
++new_data_pos;
// swap data
size_t tmp = keys[data_pos];
keys[data_pos] = keys[new_data_pos];
keys[new_data_pos] = tmp;
tmp = values[data_pos];
values[data_pos] = values[new_data_pos];
values[new_data_pos] = tmp;
//
++new_data_pos;
tmp_radix = new_radix;
} while (tmp_radix != radix);
}
++data_pos;
}
}
};
tbb::task* MSDRadixSort16Task::execute()
{
if (!is_continuation)
{
if (data_num < min_data_num_for_msd_radix_sort_16 ||
key_bit_num < (msd_radix_16_bit_num + 1))
{
serial_sort(keys, values, data_num,
key_bit_num, tmp_keys, tmp_values);
return nullptr;
}
key_bit_num -= msd_radix_16_bit_num;
size_t sum_bin[radix_num];
prefix_scan_16_serial(keys, data_num, key_bit_num, sum_bin);
swap_reorder_16_serial(keys, values, data_num, key_bit_num, sum_bin);
is_continuation = true;
recycle_as_continuation();
size_t num = sum_bin[0] > 1 ? 1 : 0;
for (size_t radix = 1; radix < radix_num; ++radix)
if ((sum_bin[radix] - sum_bin[radix - 1]) > 1)
++num;
set_ref_count(num);
tbb::task* child_task1 = nullptr;
if (sum_bin[0] > 1)
child_task1 = new (allocate_child())
MSDRadixSort16Task(keys, values, sum_bin[0],
key_bit_num, tmp_keys, tmp_values);
for (size_t radix = 1; radix < radix_num; ++radix)
if ((num = sum_bin[radix] - sum_bin[radix - 1]) > 1)
{
const size_t offset = sum_bin[radix - 1];
spawn(*new (allocate_child())
MSDRadixSort16Task(
keys + offset,
values + offset,
num, key_bit_num,
tmp_keys + offset,
tmp_values + offset));
}
return child_task1;
}
return nullptr;
}
void msd_radix_sort_16(
size_t keys[],
size_t values[],
size_t data_num,
size_t max_key,
size_t tmp_keys[],
size_t tmp_values[],
int thread_num)
{
if (data_num < 2)
return;
tbb::task_scheduler_init init(thread_num);
size_t key_bit_num = cal_digit_num<4>(max_key);
if (key_bit_num)
{
MSDRadixSort16Task& task = *new(tbb::task::allocate_root())
MSDRadixSort16Task(keys, values, data_num, key_bit_num, tmp_keys, tmp_values);
tbb::task::spawn_root_and_wait(task);
}
}
}
}
| 33.289308
| 104
| 0.501795
|
COFS-UWA
|
cfd0a388d365849c55299571788a64f78b67ee78
| 631
|
cpp
|
C++
|
src/scene/Stage.cpp
|
deianvn/kit2d
|
a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5
|
[
"Apache-2.0"
] | null | null | null |
src/scene/Stage.cpp
|
deianvn/kit2d
|
a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5
|
[
"Apache-2.0"
] | null | null | null |
src/scene/Stage.cpp
|
deianvn/kit2d
|
a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5
|
[
"Apache-2.0"
] | null | null | null |
#include "../../include/kit2d/scene/Stage.hpp"
#include "../../include/kit2d/scene/Scene.hpp"
namespace kit2d {
Stage::Stage(Window& window) : window(window) {
window.onUpdate([this](float deltaTime) {
this->scene->update(deltaTime);
});
window.onRender([this](Renderer& renderer) {
this->scene->render(spriteBatch);
spriteBatch.process(renderer);
});
}
void Stage::setScene(std::shared_ptr<Scene> scene) {
this->scene = scene;
scene->prepare();
}
void Stage::play() {
window.loop();
}
Rect Stage::bounds() {
return Rect { window->x, y, width, height };
}
}
| 20.354839
| 54
| 0.613312
|
deianvn
|
cfd3aedf01baa8d1ae911ed9694eab6fcd72cd46
| 1,492
|
cc
|
C++
|
poj/3/3194.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | 1
|
2015-04-17T09:54:23.000Z
|
2015-04-17T09:54:23.000Z
|
poj/3/3194.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | null | null | null |
poj/3/3194.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
bool equidivision(const vector<vector<int> >& grid)
{
const int N = grid.size();
vector<vector<bool> > visited(N, vector<bool>(N, false));
for (int n = 0; n < N; n++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (grid[i][j] != n || visited[i][j]) {
continue;
}
queue<pair<int,int> > q;
q.push(make_pair(i, j));
visited[i][j] = true;
int c = 0;
while (!q.empty()) {
const pair<int,int> p = q.front(); q.pop();
++c;
for (int d = 0; d < 4; d++) {
static const int di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1};
const int k = p.first + di[d], l = p.second + dj[d];
if (0 <= k && k < N && 0 <= l && l < N && grid[k][l] == n && !visited[k][l]) {
q.push(make_pair(k, l));
visited[k][l] = true;
}
}
}
if (c != N) {
return false;
}
}
}
}
return true;
}
int main()
{
int N;
while (cin >> N && N != 0) {
vector<vector<int> > grid(N, vector<int>(N, N-1));
for (int i = 0; i < N-1; i++) {
for (int j = 0; j < N; j++) {
int x, y;
cin >> x >> y;
--x; --y;
grid[x][y] = i;
}
}
if (equidivision(grid)) {
cout << "good" << endl;
} else {
cout << "wrong" << endl;
}
}
return 0;
}
| 24.064516
| 90
| 0.400134
|
eagletmt
|
cfd67f07a35b31f5fa7582523cad4390e276715f
| 1,015
|
cpp
|
C++
|
src/io/github/technicalnotes/programming/basics/36-threadNlocking.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
src/io/github/technicalnotes/programming/basics/36-threadNlocking.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
src/io/github/technicalnotes/programming/basics/36-threadNlocking.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
#include "bits/stdc++.h"
using namespace std;
char *getTime()
{
chrono::time_point<chrono::system_clock> now = chrono::system_clock::now();
time_t t = chrono::system_clock::to_time_t(now);
return ctime(&t);
}
double accountBalance = 100;
mutex accountLock;
void getMoney(int id, double amount)
{
lock_guard<mutex> lock(accountLock);
this_thread::sleep_for(chrono::seconds(2));
cout << id << " tries to withdraw Rs " << amount << " at " << getTime() << endl;
if ((accountBalance - amount) >= 0)
{
accountBalance -= amount;
cout << "New account balance is Rs " << accountBalance << endl;
}
else
{
cout << "Insufficient funds, current balance is Rs " << accountBalance << endl;
}
}
int main()
{
thread threads[10];
for (int i = 0; i < 10; i++)
{
threads[i] = thread(getMoney, i, 15);
}
for (int i = 0; i < 10; i++)
{
threads[i].join();
}
return 0;
}
| 23.068182
| 88
| 0.553695
|
chiragbhatia94
|
cfd6ec574659e3d92a6abb352f6e84dd8242fc97
| 4,026
|
cpp
|
C++
|
window.cpp
|
mauriliodc/path_aligner
|
fba4a8f95cac54c2bd5ee36626980ca7c4b9efb7
|
[
"MIT"
] | null | null | null |
window.cpp
|
mauriliodc/path_aligner
|
fba4a8f95cac54c2bd5ee36626980ca7c4b9efb7
|
[
"MIT"
] | null | null | null |
window.cpp
|
mauriliodc/path_aligner
|
fba4a8f95cac54c2bd5ee36626980ca7c4b9efb7
|
[
"MIT"
] | null | null | null |
#include "window.h"
Window::Window (QWidget *parent) : QMainWindow (parent),ui (new Ui::Window)
{
ui->setupUi(this);
p=0;
laser=0;
}
Window::~Window(){
delete ui;
}
void Window::on_fixed_frame_clicked()
{
QString odometryFilename = QFileDialog::getOpenFileName(this,tr("Open ODOMETRY log file"),"~",tr("All files (*.*)"));
if(odometryFilename.length()>0){
QStringList l = odometryFilename.split("/");
p = new Path(odometryFilename.toStdString());
p->color.r=1.0f;
this->ui->Scene->_drawables.push_back(p);
}
else{
std::cout <<"[BUTTON 1][ON FILE OPEN] no file selected"<<std::endl;
}
}
void Window::on_target_frame_clicked()
{
QString odometryFilename = QFileDialog::getOpenFileName(this,tr("Open ODOMETRY log file"),"~",tr("All files (*.*)"));
if(odometryFilename.length()>0){
QStringList l = odometryFilename.split("/");
laser = new Path(odometryFilename.toStdString());
laser->color.r=1.0f;
laser->color.g=1.0f;
this->ui->Scene->_drawables.push_back(laser);
}
else{
std::cout <<"[BUTTON 2][ON FILE OPEN] no file selected"<<std::endl;
}
}
void Window::on_t_x_valueChanged(double arg1)
{
if(laser==0)return;
laser->transform.translation().x()=(float)arg1;
this->ui->Scene->updateGL();
}
void Window::on_t_y_valueChanged(double arg1)
{
if(laser==0)return;
laser->transform.translation().y()=(float)arg1;
this->ui->Scene->updateGL();
}
void Window::on_t_z_valueChanged(double arg1)
{
if(laser==0)return;
laser->transform.translation().z()=(float)arg1;
this->ui->Scene->updateGL();
}
void Window::on_r_x_valueChanged(double arg1)
{
if(laser==0)return;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(arg1, Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(this->ui->r_y->value(), Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(this->ui->r_z->value(), Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
void Window::on_r_y_valueChanged(double arg1)
{
if(laser==0)return;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(this->ui->r_x->value(), Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(arg1, Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(this->ui->r_z->value(), Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
void Window::on_r_z_valueChanged(double arg1)
{
if(laser==0)return;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(this->ui->r_x->value(), Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(this->ui->r_y->value(), Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(arg1, Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
void Window::on_print_clicked()
{
std::cout<<"Translation:"<<std::endl;
std::cout<< laser->transform.translation().transpose()<<std::endl<< std::endl;
std::cout<<"Rotation quaternion:"<<std::endl;
std::cout<< Eigen::Quaternionf(laser->transform.linear()).x()<< " "
<<Eigen::Quaternionf(laser->transform.linear()).y()<< " "
<<Eigen::Quaternionf(laser->transform.linear()).z()<< " "
<<Eigen::Quaternionf(laser->transform.linear()).w()<< std::endl<< std::endl;
Eigen::Vector3f ea = laser->transform.linear().matrix().eulerAngles(0, 1, 2);
std::cout<<"RPY:"<<std::endl;
std::cout<<ea.transpose()<<std::endl<< std::endl;
}
void Window::on_reset_button_clicked()
{
if(laser==0)return;
laser->transform.translation().x()=0.0f;
laser->transform.translation().y()=0.0f;
laser->transform.translation().z()=0.0f;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(0.0f, Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(0.0f, Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(0.0f, Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
| 30.969231
| 121
| 0.616244
|
mauriliodc
|
cfd7726a7169408dc4d932fb2ff1afdf7efd955f
| 917
|
cpp
|
C++
|
dp/multi_zero_one_pack.cpp
|
FrancsXiang/DataStructure-Algorithms
|
f8f9e6d7be94057b955330cb7058235caef5cfed
|
[
"MIT"
] | 1
|
2020-04-14T05:44:50.000Z
|
2020-04-14T05:44:50.000Z
|
dp/multi_zero_one_pack.cpp
|
FrancsXiang/DataStructure-Algorithms
|
f8f9e6d7be94057b955330cb7058235caef5cfed
|
[
"MIT"
] | null | null | null |
dp/multi_zero_one_pack.cpp
|
FrancsXiang/DataStructure-Algorithms
|
f8f9e6d7be94057b955330cb7058235caef5cfed
|
[
"MIT"
] | 2
|
2020-09-02T08:56:31.000Z
|
2021-06-22T11:20:58.000Z
|
#include <iostream>
#include <algorithm>
#define MAXN 101
#define MAXV 1001
using namespace std;
// if you want the full pack,initialize res[0] = 0,res[1:] = -inf
// or you want the maximum value, initialize res[:] = 0;
//you could also use cost-effective sort to solve
void orgin() {
int vol[MAXN];
int val[MAXN];
int res[MAXN][MAXV];
int v, n;
cin >> v >> n;
for (int i = 1; i <= n; i++) cin >> vol[i] >> val[i];
for (int i = 0; i <= v; i++) res[0][i] = 0;
for (int i = 1; i <= n; i++) {
for (int j = vol[i]; j <= v; j++) {
res[i][j] = max(res[i - 1][j], res[i][j - vol[i]] + val[i]);
}
}
}
void space_opt() {
int vol[MAXN];
int val[MAXN];
int res[MAXV];
int v, n;
for (int i = 1; i <= n; i++) cin >> vol[i] >> val[i];
for (int i = 0; i <= v; i++) res[i] = 0;
for (int i = 1; i <= n; i++) {
for (int j = vol[i]; j <= v; j++) {
res[j] = max(res[j], res[j - vol[i]] + val[i]);
}
}
}
| 24.131579
| 65
| 0.514722
|
FrancsXiang
|
cfdaca73ae234be2ccb6cf70c985a27b77a94a2f
| 12,440
|
cpp
|
C++
|
src/gui/qgsmessagebar.cpp
|
dyna-mis/Hilabeling
|
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
|
[
"MIT"
] | null | null | null |
src/gui/qgsmessagebar.cpp
|
dyna-mis/Hilabeling
|
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
|
[
"MIT"
] | null | null | null |
src/gui/qgsmessagebar.cpp
|
dyna-mis/Hilabeling
|
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
|
[
"MIT"
] | 1
|
2021-12-25T08:40:30.000Z
|
2021-12-25T08:40:30.000Z
|
/***************************************************************************
qgsmessagebar.cpp - description
-------------------
begin : June 2012
copyright : (C) 2012 by Giuseppe Sucameli
email : sucameli at faunalia dot it
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsmessagebar.h"
#include "qgsmessagebaritem.h"
#include "qgsapplication.h"
#include "qgsmessagelog.h"
#include "qgsmessageviewer.h"
#include <QWidget>
#include <QPalette>
#include <QStackedWidget>
#include <QProgressBar>
#include <QToolButton>
#include <QTimer>
#include <QGridLayout>
#include <QMenu>
#include <QMouseEvent>
#include <QLabel>
QgsMessageBar::QgsMessageBar( QWidget *parent )
: QFrame( parent )
{
QPalette pal = palette();
pal.setBrush( backgroundRole(), pal.window() );
setPalette( pal );
setAutoFillBackground( true );
setFrameShape( QFrame::StyledPanel );
setFrameShadow( QFrame::Plain );
mLayout = new QGridLayout( this );
const int xMargin = std::max( 9.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.45 );
const int yMargin = std::max( 1.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.05 );
mLayout->setContentsMargins( xMargin, yMargin, xMargin, yMargin );
setLayout( mLayout );
mCountProgress = new QProgressBar( this );
mCountStyleSheet = QString( "QProgressBar { border: 1px solid rgba(0, 0, 0, 75%);"
" border-radius: 2px; background: rgba(0, 0, 0, 0);"
" image: url(:/images/themes/default/%1) }"
"QProgressBar::chunk { background-color: rgba(0, 0, 0, 30%); width: 5px; }" );
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.svg" ) ) );
mCountProgress->setObjectName( QStringLiteral( "mCountdown" ) );
const int barWidth = std::max( 25.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 1.25 );
const int barHeight = std::max( 14.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.7 );
mCountProgress->setFixedSize( barWidth, barHeight );
mCountProgress->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
mCountProgress->setTextVisible( false );
mCountProgress->setRange( 0, 5 );
mCountProgress->setHidden( true );
mLayout->addWidget( mCountProgress, 0, 0, 1, 1 );
mItemCount = new QLabel( this );
mItemCount->setObjectName( QStringLiteral( "mItemCount" ) );
mItemCount->setToolTip( tr( "Remaining messages" ) );
mItemCount->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred );
mLayout->addWidget( mItemCount, 0, 2, 1, 1 );
mCloseMenu = new QMenu( this );
mCloseMenu->setObjectName( QStringLiteral( "mCloseMenu" ) );
mActionCloseAll = new QAction( tr( "Close All" ), this );
mCloseMenu->addAction( mActionCloseAll );
connect( mActionCloseAll, &QAction::triggered, this, &QgsMessageBar::clearWidgets );
mCloseBtn = new QToolButton( this );
mCloseMenu->setObjectName( QStringLiteral( "mCloseMenu" ) );
mCloseBtn->setToolTip( tr( "Close" ) );
mCloseBtn->setMinimumWidth( 40 );
mCloseBtn->setStyleSheet(
"QToolButton { border:none; background-color: rgba(0, 0, 0, 0); }"
"QToolButton::menu-button { border:none; background-color: rgba(0, 0, 0, 0); }" );
mCloseBtn->setCursor( Qt::PointingHandCursor );
mCloseBtn->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconClose.svg" ) ) );
const int iconSize = std::max( 18.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.9 );
mCloseBtn->setIconSize( QSize( iconSize, iconSize ) );
mCloseBtn->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum );
mCloseBtn->setMenu( mCloseMenu );
mCloseBtn->setPopupMode( QToolButton::MenuButtonPopup );
connect( mCloseBtn, &QAbstractButton::clicked, this, static_cast < bool ( QgsMessageBar::* )() > ( &QgsMessageBar::popWidget ) );
mLayout->addWidget( mCloseBtn, 0, 3, 1, 1 );
mCountdownTimer = new QTimer( this );
mCountdownTimer->setInterval( 1000 );
connect( mCountdownTimer, &QTimer::timeout, this, &QgsMessageBar::updateCountdown );
connect( this, &QgsMessageBar::widgetAdded, this, &QgsMessageBar::updateItemCount );
connect( this, &QgsMessageBar::widgetRemoved, this, &QgsMessageBar::updateItemCount );
// start hidden
setVisible( false );
}
void QgsMessageBar::mousePressEvent( QMouseEvent *e )
{
if ( mCountProgress == childAt( e->pos() ) && e->button() == Qt::LeftButton )
{
if ( mCountdownTimer->isActive() )
{
mCountdownTimer->stop();
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerContinue.svg" ) ) );
}
else
{
mCountdownTimer->start();
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.svg" ) ) );
}
}
}
void QgsMessageBar::popItem( QgsMessageBarItem *item )
{
Q_ASSERT( item );
if ( item != mCurrentItem && !mItems.contains( item ) )
return;
if ( item == mCurrentItem )
{
mLayout->removeWidget( mCurrentItem );
mCurrentItem->hide();
disconnect( mCurrentItem, &QgsMessageBarItem::styleChanged, this, &QWidget::setStyleSheet );
mCurrentItem->deleteLater();
mCurrentItem = nullptr;
if ( !mItems.isEmpty() )
{
showItem( mItems.at( 0 ) );
}
else
{
hide();
}
}
else
{
mItems.removeOne( item );
}
emit widgetRemoved( item );
}
bool QgsMessageBar::popWidget( QgsMessageBarItem *item )
{
if ( !item || !mCurrentItem )
return false;
if ( item == mCurrentItem )
{
popItem( mCurrentItem );
return true;
}
for ( QgsMessageBarItem *existingItem : qgis::as_const( mItems ) )
{
if ( existingItem == item )
{
mItems.removeOne( existingItem );
existingItem->deleteLater();
return true;
}
}
return false;
}
bool QgsMessageBar::popWidget()
{
if ( !mCurrentItem )
return false;
resetCountdown();
QgsMessageBarItem *item = mCurrentItem;
popItem( item );
return true;
}
bool QgsMessageBar::clearWidgets()
{
if ( !mCurrentItem && mItems.empty() )
return true;
while ( !mItems.isEmpty() )
{
popWidget();
}
popWidget();
return !mCurrentItem && mItems.empty();
}
void QgsMessageBar::pushSuccess( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Success );
}
void QgsMessageBar::pushInfo( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Info );
}
void QgsMessageBar::pushWarning( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Warning );
}
void QgsMessageBar::pushCritical( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Critical );
}
void QgsMessageBar::showItem( QgsMessageBarItem *item )
{
Q_ASSERT( item );
if ( mCurrentItem )
disconnect( mCurrentItem, &QgsMessageBarItem::styleChanged, this, &QWidget::setStyleSheet );
if ( item == mCurrentItem )
return;
if ( mItems.contains( item ) )
mItems.removeOne( item );
if ( mCurrentItem )
{
mItems.prepend( mCurrentItem );
mLayout->removeWidget( mCurrentItem );
mCurrentItem->hide();
}
mCurrentItem = item;
mLayout->addWidget( item, 0, 1, 1, 1 );
mCurrentItem->show();
if ( item->duration() > 0 )
{
mCountProgress->setRange( 0, item->duration() );
mCountProgress->setValue( item->duration() );
mCountProgress->setVisible( true );
mCountdownTimer->start();
}
connect( mCurrentItem, &QgsMessageBarItem::styleChanged, this, &QWidget::setStyleSheet );
setStyleSheet( item->getStyleSheet() );
show();
emit widgetAdded( item );
}
void QgsMessageBar::pushItem( QgsMessageBarItem *item )
{
resetCountdown();
item->mMessageBar = this;
// avoid duplicated widget
popWidget( item );
showItem( item );
// Log all messages that are sent to the message bar into the message log so the
// user can get them back easier.
QString formattedTitle = QStringLiteral( "%1 : %2" ).arg( item->title(), item->text() );
QgsMessageLog::logMessage( formattedTitle, tr( "Messages" ), item->level() );
}
QgsMessageBarItem *QgsMessageBar::pushWidget( QWidget *widget, Qgis::MessageLevel level, int duration )
{
QgsMessageBarItem *item = nullptr;
item = dynamic_cast<QgsMessageBarItem *>( widget );
if ( item )
{
item->setLevel( level )->setDuration( duration );
}
else
{
item = new QgsMessageBarItem( widget, level, duration );
}
pushItem( item );
return item;
}
void QgsMessageBar::pushMessage( const QString &title, const QString &text, Qgis::MessageLevel level, int duration )
{
// keep the number of items in the message bar to a maximum of 20, avoids flooding (and freezing) of the main window
if ( mItems.count() > 20 )
mItems.removeFirst();
// block duplicate items, avoids flooding (and freezing) of the main window
for ( auto it = mItems.constBegin(); it != mItems.constEnd(); ++it )
{
if ( level == ( *it )->level() && title == ( *it )->title() && text == ( *it )->text() )
return;
}
QgsMessageBarItem *item = new QgsMessageBarItem( title, text, level, duration );
pushItem( item );
}
void QgsMessageBar::pushMessage( const QString &title, const QString &text, const QString &showMore, Qgis::MessageLevel level, int duration )
{
QgsMessageViewer *mv = new QgsMessageViewer();
mv->setWindowTitle( title );
mv->setMessageAsPlainText( text + "\n\n" + showMore );
QToolButton *showMoreButton = new QToolButton();
QAction *act = new QAction( showMoreButton );
act->setText( tr( "Show more" ) );
showMoreButton->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) );
showMoreButton->setCursor( Qt::PointingHandCursor );
showMoreButton->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred );
showMoreButton->addAction( act );
showMoreButton->setDefaultAction( act );
connect( showMoreButton, &QToolButton::triggered, mv, &QDialog::exec );
connect( showMoreButton, &QToolButton::triggered, showMoreButton, &QObject::deleteLater );
QgsMessageBarItem *item = new QgsMessageBarItem(
title,
text,
showMoreButton,
level,
duration );
pushItem( item );
}
QgsMessageBarItem *QgsMessageBar::createMessage( const QString &text, QWidget *parent )
{
QgsMessageBarItem *item = new QgsMessageBarItem( text, Qgis::Info, 0, parent );
return item;
}
QgsMessageBarItem *QgsMessageBar::createMessage( const QString &title, const QString &text, QWidget *parent )
{
return new QgsMessageBarItem( title, text, Qgis::Info, 0, parent );
}
QgsMessageBarItem *QgsMessageBar::createMessage( QWidget *widget, QWidget *parent )
{
return new QgsMessageBarItem( widget, Qgis::Info, 0, parent );
}
void QgsMessageBar::updateCountdown()
{
if ( !mCountdownTimer->isActive() )
{
resetCountdown();
return;
}
if ( mCountProgress->value() < 2 )
{
popWidget();
}
else
{
mCountProgress->setValue( mCountProgress->value() - 1 );
}
}
void QgsMessageBar::resetCountdown()
{
if ( mCountdownTimer->isActive() )
mCountdownTimer->stop();
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.svg" ) ) );
mCountProgress->setVisible( false );
}
void QgsMessageBar::updateItemCount()
{
mItemCount->setText( !mItems.isEmpty() ? tr( "%n more", "unread messages", mItems.count() ) : QString() );
// do not show the down arrow for opening menu with "close all" if there is just one message
mCloseBtn->setMenu( !mItems.isEmpty() ? mCloseMenu : nullptr );
mCloseBtn->setPopupMode( !mItems.isEmpty() ? QToolButton::MenuButtonPopup : QToolButton::DelayedPopup );
}
| 31.573604
| 141
| 0.650482
|
dyna-mis
|
cfdd07948334c7fc84c2caf3fa62b4a2bfad4efa
| 1,252
|
cpp
|
C++
|
test/src/Version.test.cpp
|
AMS21/CppBase
|
a6ec5542682bcebf5958d54557af1e03752a132f
|
[
"CC0-1.0"
] | null | null | null |
test/src/Version.test.cpp
|
AMS21/CppBase
|
a6ec5542682bcebf5958d54557af1e03752a132f
|
[
"CC0-1.0"
] | 1
|
2020-05-12T19:48:20.000Z
|
2020-05-12T19:48:20.000Z
|
test/src/Version.test.cpp
|
AMS21/CppBase
|
a6ec5542682bcebf5958d54557af1e03752a132f
|
[
"CC0-1.0"
] | null | null | null |
#include <doctest.h>
#include <cpp/Version.hpp>
TEST_CASE("Version.Attribute")
{
#if __has_cpp_attribute(carries_dependencies)
#endif
#if __has_cpp_attribute(deprecated)
#endif
#if __has_cpp_attribute(fallthrough)
#endif
#if __has_cpp_attribute(likely)
#endif
#if __has_cpp_attribute(unlikely)
#endif
#if __has_cpp_attribute(maybe_unused)
#endif
#if __has_cpp_attribute(no_unique_address)
#endif
#if __has_cpp_attribute(nodiscard)
#endif
#if __has_cpp_attribute(noreturn)
#endif
}
TEST_CASE("Version.CoreLanguage")
{
int cpp_aggregate_bases = __cpp_aggregate_bases;
int cpp_aggregate_nsdmi = __cpp_aggregate_nsdmi;
int cpp_aggregate_paren_init = __cpp_aggregate_paren_init;
int cpp_alias_templates = __cpp_alias_templates;
int cpp_aligned_new = __cpp_aligned_new;
int cpp_attributes = __cpp_attributes;
int cpp_binary_literals = __cpp_binary_literals;
int cpp_capture_star_this = __cpp_capture_star_this;
int cpp_char8_t = __cpp_char8_t;
int cpp_concepts = __cpp_concepts;
int cpp_conditional_explicit = __cpp_conditional_explicit;
int cpp_consteval = __cpp_consteval;
int cpp_constexpr = __cpp_constexpr;
}
| 29.116279
| 62
| 0.746006
|
AMS21
|
cfdf565d5dd6e610dedcd293ffce8989883de855
| 1,302
|
cpp
|
C++
|
HackerRank/Mathematics/Fundamentals/Handshake/Solution.cpp
|
nik3212/hackerrank-challenges
|
676cf748a437117016607ae17c15211269bf2f92
|
[
"MIT"
] | 1
|
2018-11-14T14:14:20.000Z
|
2018-11-14T14:14:20.000Z
|
HackerRank/Mathematics/Fundamentals/Handshake/Solution.cpp
|
nik3212/challenges
|
b127bc66ffa27bfdef87ac402dc080f933dad893
|
[
"MIT"
] | null | null | null |
HackerRank/Mathematics/Fundamentals/Handshake/Solution.cpp
|
nik3212/challenges
|
b127bc66ffa27bfdef87ac402dc080f933dad893
|
[
"MIT"
] | null | null | null |
/*
At the annual meeting of Board of Directors of Acme Inc, every one starts shaking hands with everyone else in the room. Given the fact that any two persons shake hand exactly once, Can you tell the total count of handshakes?
Input Format
The first line contains the number of test cases T, T lines follow.
Each line then contains an integer N, the total number of Board of Directors of Acme.
Output Format
Print the number of handshakes for each test-case in a new line.
Constraints
1 <= T <= 1000
0 < N < 10^6
Sample Input
2
1
2
Sample Output
0
1
Explanation
Case 1 : The lonely board member shakes no hands, hence 0.
Case 2 : There are 2 board members, 1 handshake takes place.
*/
#include <bits/stdc++.h>
using namespace std;
/*
* Complete the handshake function below.
*/
int handshake(int n) {
if (n == 0 || n == 1) {
return 0;
}
return n * (n - 1) / 2;
}
int main() {
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int result = handshake(n);
fout << result << "\n";
}
fout.close();
return 0;
}
| 18.083333
| 224
| 0.634409
|
nik3212
|
cfe36472f7d92eb5ec50760171e5141b925409af
| 4,454
|
cpp
|
C++
|
graveyard/src/transport/axis2/ssl/AxisSSLChannelException.cpp
|
vlsinitsyn/axis1
|
65a622201e526dedf7c3aeadce7cac5bd79895bf
|
[
"Apache-2.0"
] | 1
|
2021-11-10T19:36:30.000Z
|
2021-11-10T19:36:30.000Z
|
graveyard/src/transport/axis2/ssl/AxisSSLChannelException.cpp
|
vlsinitsyn/axis1
|
65a622201e526dedf7c3aeadce7cac5bd79895bf
|
[
"Apache-2.0"
] | null | null | null |
graveyard/src/transport/axis2/ssl/AxisSSLChannelException.cpp
|
vlsinitsyn/axis1
|
65a622201e526dedf7c3aeadce7cac5bd79895bf
|
[
"Apache-2.0"
] | 2
|
2021-11-02T13:09:57.000Z
|
2021-11-10T19:36:22.000Z
|
/* -*- C++ -*- */
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @author Damitha Kumarage (damitha@hsenid.lk, damitha@opensource.lk)
*
*/
#include "AxisSSLChannelException.hpp"
/**
* Default when no parameter passed. When thrown with no parameter
* more general SERVER_TRANSPORT_EXCEPTION is assumed.
*/
AxisSSLChannelException::AxisSSLChannelException()
{
processException(SERVER_TRANSPORT_EXCEPTION);
}
AxisSSLChannelException::AxisSSLChannelException (const int iExceptionCode)
{
m_iExceptionCode = iExceptionCode;
processException (iExceptionCode);
}
AxisSSLChannelException::AxisSSLChannelException(const int iExceptionCode, char* pcMessage)
{
m_iExceptionCode = iExceptionCode;
processException(iExceptionCode, pcMessage);
}
AxisSSLChannelException::AxisSSLChannelException (const exception* e)
{
processException (e);
}
AxisSSLChannelException::AxisSSLChannelException (const exception* e, const int iExceptionCode)
{
processException (e, iExceptionCode);
}
AxisSSLChannelException::~AxisSSLChannelException() throw ()
{
}
void AxisSSLChannelException::processException (const exception* e, const int iExceptionCode)
{
m_sMessage = getMessage (iExceptionCode) + ":" + getMessage(e);
}
void AxisSSLChannelException::processException (const exception* e, char* pcMessage)
{
m_sMessage += "AxisSSLChannelException:" + string(pcMessage) + ":" + getMessage (e);
}
void AxisSSLChannelException::processException (const exception* e)
{
m_sMessage += "AxisSSLChannelException:" + getMessage (e);
}
void AxisSSLChannelException::processException(const int iExceptionCode)
{
m_sMessage = getMessage (iExceptionCode);
}
void AxisSSLChannelException::processException(const int iExceptionCode, char* pcMessage)
{
AxisString sMessage = pcMessage;
m_sMessage = getMessage(iExceptionCode) + " " + sMessage;
}
const string AxisSSLChannelException::getMessage (const exception* objException)
{
static string objExDetail = objException->what();
return objExDetail;
}
const string AxisSSLChannelException::getMessage (const int iExceptionCode)
{
switch(iExceptionCode)
{
case CLIENT_SSLCHANNEL_RECEPTION_EXCEPTION:
m_sMessage = "AxisSSLChannelException:Problem occured when" \
" receiving the stream";
break;
case CLIENT_SSLCHANNEL_SENDING_EXCEPTION:
m_sMessage = "AxisSSLChannelException:Problem occured when sending" \
" the stream";
break;
case CLIENT_SSLCHANNEL_CHANNEL_INIT_ERROR:
m_sMessage = "AxisSSLChannelException:Cannot initialize a " \
"channel to the remote end";
break;
case CLIENT_SSLCHANNEL_SOCKET_CREATE_ERROR:
m_sMessage = "AxisSSLChannelException:Sockets error Couldn't" \
" create socket";
break;
case CLIENT_SSLCHANNEL_SOCKET_CONNECT_ERROR:
m_sMessage = "AxisSSLChannelException:Cannot open a channel to the" \
" remote end, shutting down the channel";
break;
case CLIENT_SSLCHANNEL_INVALID_SOCKET_ERROR:
m_sMessage = "AxisSSLChannelException:Socket used to write is invalid";
break;
case CLIENT_SSLCHANNEL_CONTEXT_CREATE_ERROR:
m_sMessage = "AxisSSLChannelException:Could not create SSL context";
break;
case CLIENT_SSLCHANNEL_ERROR:
m_sMessage = "AxisSSLChannelException:OpenSSL Error code is:";
break;
default:
m_sMessage = "AxisSSLChannelException:Unknown SSL Channel Exception";
}
return m_sMessage;
}
const char* AxisSSLChannelException::what() throw ()
{
return m_sMessage.c_str ();
}
const int AxisSSLChannelException::getExceptionCode()
{
return m_iExceptionCode;
}
| 31.146853
| 95
| 0.710373
|
vlsinitsyn
|
cfe61a58a6e7ef9adddfaffe4f3aa0846db4eb44
| 4,744
|
cpp
|
C++
|
src/progress_bar.cpp
|
sweetkristas/anura
|
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
|
[
"CC0-1.0"
] | null | null | null |
src/progress_bar.cpp
|
sweetkristas/anura
|
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
|
[
"CC0-1.0"
] | null | null | null |
src/progress_bar.cpp
|
sweetkristas/anura
|
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
|
[
"CC0-1.0"
] | null | null | null |
/*
Copyright (C) 2003-2013 by David White <davewx7@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include "graphics.hpp"
#include "progress_bar.hpp"
#include "raster.hpp"
namespace gui {
progress_bar::progress_bar(int progress, int minv, int maxv, const std::string& gui_set)
: progress_(progress), min_(minv), max_(maxv), completion_called_(false),
upscale_(false), color_(128,128,128,255), hpad_(10), vpad_(10)
{
if(gui_set.empty() == false) {
frame_image_set_ = framed_gui_element::get(gui_set);
}
}
progress_bar::progress_bar(const variant& v, game_logic::formula_callable* e)
: widget(v,e), completion_called_(false),
progress_(v["progress"].as_int(0)),
min_(v["min"].as_int(0)), max_(v["max"].as_int(100)),
hpad_(10), vpad_(10)
{
if(v.has_key("on_completion")) {
ASSERT_LOG(get_environment() != 0, "You must specify a callable environment");
completion_handler_ = get_environment()->create_formula(v["on_completion"]);
oncompletion_ = boost::bind(&progress_bar::complete, this);
}
std::string frame_set = v["frame_set"].as_string_default("");
if(frame_set != "none" && frame_set.empty() == false) {
frame_image_set_ = framed_gui_element::get(frame_set);
}
upscale_ = v["resolution"].as_string_default("normal") == "normal" ? false : true;
if(v.has_key("color")) {
color_ = graphics::color(v["color"]);
} else if(v.has_key("colour")) {
color_ = graphics::color(v["colour"]);
} else {
color_ = graphics::color("grey");
}
if(v.has_key("padding")) {
ASSERT_LOG(v["padding"].num_elements() == 2, "Padding field must be two element, found " << v["padding"].num_elements())
hpad_ = v["padding"][0].as_int();
vpad_ = v["padding"][1].as_int();
}
}
void progress_bar::complete()
{
if(get_environment()) {
variant value = completion_handler_->execute(*get_environment());
get_environment()->execute_command(value);
} else {
std::cerr << "progress_bar::complete() called without environment!" << std::endl;
}
}
void progress_bar::set_progress(int value)
{
progress_ = std::min(max_, value);
progress_ = std::max(min_, progress_);
if(progress_ >= max_ && completion_called_ == false) {
completion_called_ = true;
if(oncompletion_) {
oncompletion_();
}
}
}
void progress_bar::update_progress(int delta)
{
progress_ = std::min(max_, progress_ + delta);
progress_ = std::max(min_, progress_);
if(progress_ >= max_ && completion_called_ == false) {
completion_called_ = true;
if(oncompletion_) {
oncompletion_();
}
}
}
void progress_bar::set_completion_handler(boost::function<void ()> oncompletion)
{
oncompletion_ = oncompletion;
}
void progress_bar::reset()
{
progress_ = min_;
completion_called_ = false;
}
variant progress_bar::get_value(const std::string& key) const
{
if(key == "progress") {
return variant(progress_);
} else if(key == "min") {
return variant(min_);
} else if(key == "max") {
return variant(max_);
}
return variant();
}
void progress_bar::set_value(const std::string& key, const variant& value)
{
if(key == "progress") {
set_progress(value.as_int());
} else if(key == "min") {
min_ = value.as_int();
} else if(key == "max") {
max_ = value.as_int();
if(progress_ < max_) {
completion_called_ = false;
} else if(completion_called_ == false) {
progress_ = max_;
completion_called_ = true;
if(oncompletion_) {
oncompletion_();
}
}
} else if(key == "resolution") {
upscale_ = value.as_string_default("normal") == "normal" ? false : true;
} else if(key == "color" || key == "colour") {
color_ = graphics::color(value);
} else if(key == "padding") {
ASSERT_LOG(value.num_elements() == 2, "Padding field must be two element, found " << value.num_elements())
hpad_ = value[0].as_int();
vpad_ = value[1].as_int();
}
widget::set_value(key, value);
}
void progress_bar::handle_draw() const
{
if(frame_image_set_) {
frame_image_set_->blit(x(),y(),width(),height(), upscale_);
}
const int w = int((width()-hpad_*2) * float(progress_-min_)/float(max_-min_));
graphics::draw_rect(rect(x()+hpad_,y()+vpad_,w,height()-vpad_*2), color_);
}
}
| 29.283951
| 122
| 0.684233
|
sweetkristas
|
cfe8e78c2ad096dcfd8c34d5cbddaf14f96b6892
| 674
|
cpp
|
C++
|
Cpp_Projects/tryandcatch.cpp
|
EderLukas/Portfolio
|
1c9adef3435129d26d3c6275a79ed363bf062e8f
|
[
"MIT"
] | null | null | null |
Cpp_Projects/tryandcatch.cpp
|
EderLukas/Portfolio
|
1c9adef3435129d26d3c6275a79ed363bf062e8f
|
[
"MIT"
] | null | null | null |
Cpp_Projects/tryandcatch.cpp
|
EderLukas/Portfolio
|
1c9adef3435129d26d3c6275a79ed363bf062e8f
|
[
"MIT"
] | null | null | null |
/*
* source code: tryandcatch.cpp
* author: Lukas Eder
* date: 01.01.2018
*
* Descr.:
* Uebung zu try and catch Fehlerbehandlung inkl. inteligentem Array
*/
#include <iostream>
#include <array>
using namespace std;
int main() {
//Variablen
array<double, 3> preise;
preise.at(0) = 1.45;
preise.at(1) = 3.55;
preise.at(2) = 5.25;
for (unsigned int i = 0; i < preise.size(); i++) {
try {
cout << "Preise pos 1 mit []: " << preise[1] << endl;
cout << "Preise pos 5 mit at()" << preise.at(5) << endl;
cout << "Ende des Try-Blocks" << endl;
}
catch(exception &e){
cout << "Fehler: " << e.what() << endl;
}
}
}
| 21.741935
| 69
| 0.55638
|
EderLukas
|
cfeb15a71d3d8c8a5b4ee0d3a96fd66458c16cc0
| 1,209
|
hpp
|
C++
|
include/ISubThread.hpp
|
lordio/insanity
|
7dfbf398fe08968f40a32280bf2b16cca2b476a1
|
[
"MIT"
] | 1
|
2015-02-05T10:41:14.000Z
|
2015-02-05T10:41:14.000Z
|
include/ISubThread.hpp
|
lordio/insanity
|
7dfbf398fe08968f40a32280bf2b16cca2b476a1
|
[
"MIT"
] | 1
|
2015-02-04T20:47:52.000Z
|
2015-02-05T07:43:05.000Z
|
include/ISubThread.hpp
|
lordio/insanity
|
7dfbf398fe08968f40a32280bf2b16cca2b476a1
|
[
"MIT"
] | null | null | null |
#ifndef INSANITY_INTERFACE_SUB_THREAD
#define INSANITY_INTERFACE_SUB_THREAD
#include "Constants.hpp"
#include "IThread.hpp"
namespace Insanity
{
//"Sub," in opposition to the "main" thread, represented by IApplication.
class INSANITY_API ISubThread : public virtual IThread
{
public:
//=================================================
//Create a new subthread.
//Not intended for use outside the library.
//Inherit from Default::Thread instead.
//=================================================
static ISubThread * Create(ISubThread * ext, bool start = true);
//=================================================
//Start a thread that is not currently running,
// whether it hasn't started yet,
// or has already returned.
//Immediately returns if called relative to current thread.
//=================================================
virtual void Start() = 0;
//=================================================
//The main body of a thread's operations.
// An implementation will call this through the function
// passed to the platform-specific thread creation API.
//=================================================
virtual void Main() = 0;
};
}
#endif
| 31.815789
| 74
| 0.539289
|
lordio
|
cff5243f89c24da48b4e1a8e5bee40914b35363e
| 16,909
|
cpp
|
C++
|
src/TextureLoaderFrontend/load_dds.cpp
|
WubiCookie/VkRenderer
|
87cc5d858591fc976c197ab2834e1ac9a418becd
|
[
"MIT"
] | 2
|
2020-05-31T19:54:19.000Z
|
2021-09-14T12:00:12.000Z
|
src/TextureLoaderFrontend/load_dds.cpp
|
WubiCookie/VkRenderer
|
87cc5d858591fc976c197ab2834e1ac9a418becd
|
[
"MIT"
] | null | null | null |
src/TextureLoaderFrontend/load_dds.cpp
|
WubiCookie/VkRenderer
|
87cc5d858591fc976c197ab2834e1ac9a418becd
|
[
"MIT"
] | null | null | null |
#include "load_dds.hpp"
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
//#define MEAN_AND_LEAN
//#define NO_MINMAX
//#include <windows.h>
#include <iostream>
/*
Can load easier and more indepth with https://github.com/Hydroque/DDSLoader
Because a lot of crappy, weird DDS file loader files were found online. The
resources are actually VERY VERY limited. Written in C, can very easily port to
C++ through casting mallocs (ensure your imports are correct), goto can be
replaced.
https://www.gamedev.net/forums/topic/637377-loading-dds-textures-in-opengl-black-texture-showing/
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
^ Two examples of terrible code
https://gist.github.com/Hydroque/d1a8a46853dea160dc86aa48618be6f9
^ My first look and clean up 'get it working'
https://ideone.com/WoGThC
^ Improvement details
File Structure:
Section Length
///////////////////
FILECODE 4
HEADER 124
HEADER_DX10* 20
(https://msdn.microsoft.com/en-us/library/bb943983(v=vs.85).aspx) PIXELS
fseek(f, 0, SEEK_END); (ftell(f) - 128) - (fourCC == "DX10" ? 17 or 20 : 0)
* the link tells you that this section isn't written unless its a DX10 file
Supports DXT1, DXT3, DXT5.
The problem with supporting DX10 is you need to know what it is used for and
how opengl would use it. File Byte Order: typedef unsigned int DWORD; // 32bits
little endian type index attribute // description
///////////////////////////////////////////////////////////////////////////////////////////////
DWORD 0 file_code; //. always `DDS `, or 0x20534444
DWORD 4 size; //. size of the header, always 124
(includes PIXELFORMAT) DWORD 8 flags; //. bitflags that
tells you if data is present in the file
// CAPS 0x1
// HEIGHT 0x2
// WIDTH 0x4
// PITCH 0x8
// PIXELFORMAT 0x1000
// MIPMAPCOUNT 0x20000
// LINEARSIZE 0x80000
// DEPTH 0x800000
DWORD 12 height; //. height of the base image (biggest
mipmap) DWORD 16 width; //. width of the base image
(biggest mipmap) DWORD 20 pitchOrLinearSize; //. bytes per scan line in
an uncompressed texture, or bytes in the top level texture for a compressed
texture
// D3DX11.lib and other similar
libraries unreliably or inconsistently provide the pitch, convert with
// DX* && BC*: max( 1, ((width+3)/4)
) * block-size
// *8*8_*8*8 && UYVY && YUY2:
((width+1) >> 1) * 4
// (width * bits-per-pixel + 7)/8
(divide by 8 for byte alignment, whatever that means) DWORD 24 depth;
//. Depth of a volume texture (in pixels), garbage if no volume data DWORD 28
mipMapCount; //. number of mipmaps, garbage if no pixel data DWORD 32
reserved1[11]; //. unused DWORD 76 Size; //. size of
the following 32 bytes (PIXELFORMAT) DWORD 80 Flags; //.
bitflags that tells you if data is present in the file for following 28 bytes
// ALPHAPIXELS 0x1
// ALPHA 0x2
// FOURCC 0x4
// RGB 0x40
// YUV 0x200
// LUMINANCE 0x20000
DWORD 84 FourCC; //. File format: DXT1, DXT2, DXT3, DXT4,
DXT5, DX10. DWORD 88 RGBBitCount; //. Bits per pixel DWORD 92
RBitMask; //. Bit mask for R channel DWORD 96 GBitMask; //.
Bit mask for G channel DWORD 100 BBitMask; //. Bit mask for B
channel DWORD 104 ABitMask; //. Bit mask for A channel DWORD
108 caps; //. 0x1000 for a texture w/o mipmaps
// 0x401008 for a texture w/ mipmaps
// 0x1008 for a cube map
DWORD 112 caps2; //. bitflags that tells you if data is
present in the file
// CUBEMAP 0x200 Required
for a cube map.
// CUBEMAP_POSITIVEX 0x400 Required
when these surfaces are stored in a cube map.
// CUBEMAP_NEGATIVEX 0x800 ^
// CUBEMAP_POSITIVEY 0x1000 ^
// CUBEMAP_NEGATIVEY 0x2000 ^
// CUBEMAP_POSITIVEZ 0x4000 ^
// CUBEMAP_NEGATIVEZ 0x8000 ^
// VOLUME 0x200000
Required for a volume texture. DWORD 114 caps3; //. unused
DWORD 116 caps4; //. unused
DWORD 120 reserved2; //. unused
*/
struct PixelFormatHeader
{
enum class FlagBits : uint32_t
{
AlphaPixels = 0x1,
Alpha = 0x2,
FourCC = 0x4,
Rgb = 0x40,
Yuv = 0x200,
Luminance = 0x20000,
};
uint32_t dwSize;
FlagBits dwFlags;
char dwFourCC[4];
uint32_t dwRGBBitCount;
uint32_t dwRBitMask;
uint32_t dwGBitMask;
uint32_t dwBBitMask;
uint32_t dwABitMask;
};
struct Header
{
enum class FlagBits : uint32_t
{
Caps = 0x1,
Height = 0x2,
Width = 0x4,
Pitch = 0x8,
PixelFormat = 0x1000,
MipmapCount = 0x20000,
LinearSize = 0x80000,
Depth = 0x800000,
Texture = Caps | Height | Width | PixelFormat,
Mipmap = MipmapCount,
Volume = Depth,
};
enum class Caps_bits : uint32_t
{
Complex = 0x8,
Mipmap = 0x400000,
Texture = 0x1000,
};
enum class Caps2_bits : uint32_t
{
Cubemap = 0x200,
CubemapPositiveX = 0x400,
CubemapNegativeX = 0x800,
CubemapPositiveY = 0x1000,
CubemapNegativeY = 0x2000,
CubemapPositiveZ = 0x4000,
CubemapNegativeZ = 0x8000,
Volume = 0x200000,
CubemapAllFaces = CubemapPositiveX | CubemapNegativeX |
CubemapPositiveY | CubemapNegativeY |
CubemapPositiveZ | CubemapNegativeZ,
};
char fourCC[4];
FlagBits dwSize;
uint32_t dwFlags;
uint32_t dwHeight;
uint32_t dwWidth;
uint32_t dwPitchOrLinearSize;
uint32_t dwDepth;
uint32_t dwMipMapCount;
uint32_t dwReserved1[11];
PixelFormatHeader ddspf;
Caps_bits dwCaps;
Caps2_bits dwCaps2;
uint32_t dwCaps3;
uint32_t dwCaps4;
uint32_t dwReserved2;
};
enum class Format : uint32_t
{
UNKNOWN,
R32G32B32A32_TYPELESS,
R32G32B32A32_FLOAT,
R32G32B32A32_UINT,
R32G32B32A32_SINT,
R32G32B32_TYPELESS,
R32G32B32_FLOAT,
R32G32B32_UINT,
R32G32B32_SINT,
R16G16B16A16_TYPELESS,
R16G16B16A16_FLOAT,
R16G16B16A16_UNORM,
R16G16B16A16_UINT,
R16G16B16A16_SNORM,
R16G16B16A16_SINT,
R32G32_TYPELESS,
R32G32_FLOAT,
R32G32_UINT,
R32G32_SINT,
R32G8X24_TYPELESS,
D32_FLOAT_S8X24_UINT,
R32_FLOAT_X8X24_TYPELESS,
X32_TYPELESS_G8X24_UINT,
R10G10B10A2_TYPELESS,
R10G10B10A2_UNORM,
R10G10B10A2_UINT,
R11G11B10_FLOAT,
R8G8B8A8_TYPELESS,
R8G8B8A8_UNORM,
R8G8B8A8_UNORM_SRGB,
R8G8B8A8_UINT,
R8G8B8A8_SNORM,
R8G8B8A8_SINT,
R16G16_TYPELESS,
R16G16_FLOAT,
R16G16_UNORM,
R16G16_UINT,
R16G16_SNORM,
R16G16_SINT,
R32_TYPELESS,
D32_FLOAT,
R32_FLOAT,
R32_UINT,
R32_SINT,
R24G8_TYPELESS,
D24_UNORM_S8_UINT,
R24_UNORM_X8_TYPELESS,
X24_TYPELESS_G8_UINT,
R8G8_TYPELESS,
R8G8_UNORM,
R8G8_UINT,
R8G8_SNORM,
R8G8_SINT,
R16_TYPELESS,
R16_FLOAT,
D16_UNORM,
R16_UNORM,
R16_UINT,
R16_SNORM,
R16_SINT,
R8_TYPELESS,
R8_UNORM,
R8_UINT,
R8_SNORM,
R8_SINT,
A8_UNORM,
R1_UNORM,
R9G9B9E5_SHAREDEXP,
R8G8_B8G8_UNORM,
G8R8_G8B8_UNORM,
BC1_TYPELESS,
BC1_UNORM,
BC1_UNORM_SRGB,
BC2_TYPELESS,
BC2_UNORM,
BC2_UNORM_SRGB,
BC3_TYPELESS,
BC3_UNORM,
BC3_UNORM_SRGB,
BC4_TYPELESS,
BC4_UNORM,
BC4_SNORM,
BC5_TYPELESS,
BC5_UNORM,
BC5_SNORM,
B5G6R5_UNORM,
B5G5R5A1_UNORM,
B8G8R8A8_UNORM,
B8G8R8X8_UNORM,
R10G10B10_XR_BIAS_A2_UNORM,
B8G8R8A8_TYPELESS,
B8G8R8A8_UNORM_SRGB,
B8G8R8X8_TYPELESS,
B8G8R8X8_UNORM_SRGB,
BC6H_TYPELESS,
BC6H_UF16,
BC6H_SF16,
BC7_TYPELESS,
BC7_UNORM,
BC7_UNORM_SRGB,
AYUV,
Y410,
Y416,
NV12,
P010,
P016,
_420_OPAQUE,
YUY2,
Y210,
Y216,
NV11,
AI44,
IA44,
P8,
A8P8,
B4G4R4A4_UNORM,
P208,
V208,
V408,
SAMPLER_FEEDBACK_MIN_MIP_OPAQUE,
SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE,
FORCE_UINT
};
enum class ResourceDim : uint32_t
{
UNKNOWN,
BUFFER,
TEXTURE1D,
TEXTURE2D,
TEXTURE3D
};
enum class MiscFlags2 : uint32_t
{
ALPHA_MODE_UNKNOWN = 0x0,
ALPHA_MODE_STRAIGHT = 0x1,
ALPHA_MODE_PREMULTIPLIED = 0x2,
ALPHA_MODE_OPAQUE = 0x3,
ALPHA_MODE_CUSTOM = 0x4,
};
struct Header_DXT10
{
Format dxgiFormat;
ResourceDim resourceDimension;
uint32_t miscFlag;
uint32_t arraySize;
MiscFlags2 miscFlags2;
};
static_assert(sizeof(Header) == 128);
cdm::Texture2D texture_loadDDS(const char* path, cdm::TextureFactory& factory,
cdm::CommandBufferPool& pool,
VkImageLayout outputLayout)
{
// lay out variables to be used
Header header;
memset(&header, 0xcccc, sizeof(header));
Header_DXT10 header10;
memset(&header10, 0xcccc, sizeof(header10));
uint32_t width;
uint32_t height;
uint32_t mipmapCount;
uint32_t blockSize;
VkFormat format;
uint32_t w;
uint32_t h;
std::vector<std::byte> buffer;
// GLuint tid = 0;
cdm::Texture2D texture;
// open the DDS file for binary reading and get file size
FILE* f;
if ((f = fopen(path, "rb")) == 0)
return texture;
fseek(f, 0, SEEK_END);
long file_size = ftell(f);
fseek(f, 0, SEEK_SET);
// allocate new unsigned char space with 4 (file code) + 124 (header size)
// bytes read in 128 bytes from the file
fread(&header, 1, sizeof(header), f);
// compare the `DDS ` signature
if (memcmp(&header, "DDS ", 4) != 0)
goto exit;
//*
// extract height, width, and amount of mipmaps - yes it is stored height
// then width
height = header.dwHeight;
width = header.dwWidth;
mipmapCount = header.dwMipMapCount;
factory.setWidth(width);
factory.setHeight(height);
// factory.setMipLevels(mipmapCount);
factory.setMipLevels(1);
size_t bufferSize = file_size - 128;
// figure out what format to use for what fourCC file type it is
// block size is about physical chunk storage of compressed data in file
// (important)
if (char(header.ddspf.dwFourCC[0]) == 'D')
{
switch (char(header.ddspf.dwFourCC[3]))
{
case '1': // DXT1
format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
blockSize = 8;
break;
case '3': // DXT3
format = VK_FORMAT_BC3_UNORM_BLOCK;
blockSize = 16;
break;
case '5': // DXT5
format = VK_FORMAT_BC5_UNORM_BLOCK;
blockSize = 16;
break;
case '0': // DX10
// unsupported, else will error
// as it adds sizeof(struct DDS_HEADER_DXT10) between pixels
// so, buffer = malloc((file_size - 128) - sizeof(struct
// DDS_HEADER_DXT10));
fread(&header10, 1, sizeof(header10), f);
if (header10.dxgiFormat == Format::R32G32B32A32_FLOAT)
{
format = VK_FORMAT_R32G32B32A32_SFLOAT;
blockSize = 16;
}
else if (header10.dxgiFormat == Format::R32G32_FLOAT)
{
format = VK_FORMAT_R32G32_SFLOAT;
blockSize = 8;
}
bufferSize -= sizeof(Header_DXT10);
break;
default: goto exit;
}
}
else // BC4U/BC4S/ATI2/BC55/R8G8_B8G8/G8R8_G8B8/UYVY-packed/YUY2-packed
// unsupported
goto exit;
factory.setFormat(format);
// allocate new unsigned char space with file_size - (file_code +
// header_size) magnitude read rest of file
buffer.resize(bufferSize);
// buffer = (unsigned char*)malloc(file_size - 128);
// if(buffer == 0)
// goto exit;
fread(buffer.data(), 1, file_size, f);
// prepare new incomplete texture
// glGenTextures(1, &tid);
// if(tid == 0)
// goto exit;
// texture = factory.createTexture2D();
// bind the texture
// make it complete by specifying all needed parameters and ensuring all
// mipmaps are filled
// glBindTexture(GL_TEXTURE_2D, tid);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipMapCount-1); //
// opengl likes array length of mipmaps glTexParameteri(GL_TEXTURE_2D,
// GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,
// GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // don't forget to
// enable mipmaping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
// GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
// GL_REPEAT);
// prepare some variables
unsigned int offset = 0;
unsigned int size = 0;
w = width;
h = height;
// loop through sending block at a time with the magic formula
// upload to opengl properly, note the offset transverses the pointer
// assumes each mipmap is 1/2 the size of the previous mipmap
// std::cout << path << " has " << mipmapCount << " mipLevels" <<
// std::endl;
std::cout << path << std::endl;
VkBufferImageCopy region{};
// region.imageExtent.width = width;
// region.imageExtent.height = height;
region.imageExtent.depth = 1;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
// region.imageSubresource.mipLevel = 0;
/*
for (unsigned int i = 0; i < mipmapCount; i++)
{
if (w == 0 || h == 0)
{ // discard any odd mipmaps 0x1 0x2 resolutions
std::cout << "odd mipmap " << i << "/" << mipmapCount << " (" << w
<< ";" << h << ")" << std::endl;
// mipmapCount--;
// continue;
}
size = ((w + 3) / 4) * ((h + 3) / 4) * blockSize;
//VkBufferImageCopy region{};
region.imageExtent.width = w;
region.imageExtent.height = h;
//region.imageExtent.depth = 1;
//region.bufferRowLength = 0;
//region.bufferImageHeight = 0;
//region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
//region.imageSubresource.baseArrayLayer = 0;
//region.imageSubresource.layerCount = 1;
region.imageSubresource.mipLevel = i;
//if (i == mipmapCount - 2)
{
std::cout << "loading level " << i << "/" << mipmapCount << " ("
<< w << ";" << h << ")" << std::endl;
factory.setWidth(w);
factory.setHeight(h);
texture = factory.createTexture2D();
region.imageSubresource.mipLevel = 0;
texture.uploadData(buffer.data() + offset, size, region,
VK_IMAGE_LAYOUT_UNDEFINED, outputLayout, pool);
if (texture == nullptr)
{
std::cout << "what" << std::endl;
}
break;
}
// glCompressedTexImage2D(GL_TEXTURE_2D, i, format, w, h, 0, size,
// buffer + offset);
offset += size;
w /= 2;
h /= 2;
}
//*/
if (texture.image() == nullptr)
{
region.imageExtent.width = width;
region.imageExtent.height = height;
region.imageSubresource.mipLevel = 0;
std::cout << "loading level " << 0 << "/" << mipmapCount << " ("
<< width << ";" << height << ")" << std::endl;
//size = ((width + 3) / 4) * ((width + 3) / 4) * blockSize;
size = width * width * blockSize;
std::cout << "blockSize " << blockSize << std::endl;
std::cout << "size " << ((width + 3) / 4) << " * " << ((width + 3) / 4)
<< " * " << blockSize << std::endl;
factory.setWidth(width);
factory.setHeight(height);
texture = factory.createTexture2D();
texture.uploadData(buffer.data(), size, region,
VK_IMAGE_LAYOUT_UNDEFINED, outputLayout, pool);
}
// discard any odd mipmaps, ensure a complete texture
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipMapCount-1);
// unbind
// glBindTexture(GL_TEXTURE_2D, 0);
//*/
// easy macro to get out quick and uniform (minus like 15 lines of bulk)
exit:
// free(buffer);
// free(header);
fclose(f);
// return tid;
return texture;
}
| 29.305026
| 98
| 0.603288
|
WubiCookie
|
cfff7dbf1afee58f5dd3a04d6f58c871730fa696
| 712
|
cpp
|
C++
|
cpp/stl/05_insert.cpp
|
Trickness/pl_learning
|
53c10490aed1ba4a02b14aae4890321ad099cc60
|
[
"Unlicense"
] | null | null | null |
cpp/stl/05_insert.cpp
|
Trickness/pl_learning
|
53c10490aed1ba4a02b14aae4890321ad099cc60
|
[
"Unlicense"
] | null | null | null |
cpp/stl/05_insert.cpp
|
Trickness/pl_learning
|
53c10490aed1ba4a02b14aae4890321ad099cc60
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <iterator>
using namespace std;
int iArray[5] = {1,2,3,4,5};
void Display(list<int> &a , const char* s){
cout << s << endl;
copy(a.begin(),a.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
int main(){
list<int> iList;
// Copy iArray backwards into iList
copy(iArray,iArray + 5, back_inserter(iList));
Display(iList,"Before find and copy");
// Locate value 3 in iList
auto p = find(iList.begin(),iList.end(),3);
// Copy first two iArray values to iList ahead of p
copy(iArray, iArray + 2, inserter(iList,p));
Display(iList,"After find and copy");
return 0;
}
| 22.25
| 62
| 0.629213
|
Trickness
|
3202fd54536a01efd617e80e180b3288cabceecd
| 2,511
|
cc
|
C++
|
src/developer/debug/zxdb/symbols/identifier_unittest.cc
|
yanyushr/fuchsia
|
98e70672a81a206d235503e398f37b7b65581f79
|
[
"BSD-3-Clause"
] | 1
|
2019-10-09T10:50:57.000Z
|
2019-10-09T10:50:57.000Z
|
src/developer/debug/zxdb/symbols/identifier_unittest.cc
|
bootingman/fuchsia2
|
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
|
[
"BSD-3-Clause"
] | null | null | null |
src/developer/debug/zxdb/symbols/identifier_unittest.cc
|
bootingman/fuchsia2
|
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/debug/zxdb/symbols/identifier.h"
#include "gtest/gtest.h"
#include "src/developer/debug/zxdb/common/err.h"
namespace zxdb {
TEST(Identifier, GetName) {
// Empty.
Identifier unqualified;
EXPECT_EQ("", unqualified.GetFullName());
// Single name with no "::" at the beginning.
unqualified.AppendComponent("First");
EXPECT_EQ("First", unqualified.GetFullName());
std::vector<std::string> expected_index = {"First"};
// Single name with a "::" at the beginning.
Identifier qualified(Identifier::kGlobal, "First");
EXPECT_EQ("::First", qualified.GetFullName());
// Append some template stuff.
qualified.AppendComponent("Second", {"int", "Foo"});
EXPECT_EQ("::First::Second<int, Foo>", qualified.GetFullName());
expected_index.push_back("Second<int, Foo>");
}
TEST(Identifier, GetScope) {
std::string name1("Name1");
std::string name2("Name2");
std::string name3("Name3");
// "" -> "".
Identifier empty;
EXPECT_EQ("", empty.GetScope().GetDebugName());
// "::" -> "::".
Identifier scope_only(Identifier::kGlobal);
EXPECT_EQ("::", scope_only.GetScope().GetDebugName());
// "Name1" -> "".
Identifier name_only(Identifier::kRelative, Identifier::Component(name1));
EXPECT_EQ("", name_only.GetScope().GetDebugName());
// ::Name1" -> "::".
Identifier scoped_name(Identifier::kGlobal, Identifier::Component(name1));
EXPECT_EQ("::", scoped_name.GetScope().GetDebugName());
// "Name1::Name2" -> "Name1".
Identifier two_names(Identifier::kRelative, Identifier::Component(name1));
two_names.AppendComponent(Identifier::Component(name2));
EXPECT_EQ("\"Name1\"", two_names.GetScope().GetDebugName());
// "::Name1::Name2" -> "::Name1".
Identifier two_scoped_names(Identifier::kGlobal,
Identifier::Component(name1));
two_scoped_names.AppendComponent(Identifier::Component(name2));
EXPECT_EQ("::\"Name1\"", two_scoped_names.GetScope().GetDebugName());
// "Name1::Name2::Name3" -> "Name1::Name2".
Identifier three_scoped_names(Identifier::kRelative,
Identifier::Component(name1));
three_scoped_names.AppendComponent(name2);
three_scoped_names.AppendComponent(name3);
EXPECT_EQ("\"Name1\"; ::\"Name2\"",
three_scoped_names.GetScope().GetDebugName());
}
} // namespace zxdb
| 33.932432
| 76
| 0.680207
|
yanyushr
|
3205b13f2b67c5c04db23a69f1ebf07a9e31ed5d
| 3,456
|
cpp
|
C++
|
1082_b.cpp
|
onexmaster/cp
|
b78b0f1e586d6977d86c97b32f48fed33f1469af
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
1082_b.cpp
|
onexmaster/cp
|
b78b0f1e586d6977d86c97b32f48fed33f1469af
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
1082_b.cpp
|
onexmaster/cp
|
b78b0f1e586d6977d86c97b32f48fed33f1469af
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int t;
cin>>t;
string s;
cin>>s;
vector<int>v(t,0);
if(s[0]=='G')
v[0]=1;
else
v[0]=0;
for(int i=1;i<t;i++)
{
if(s[i]=='G' && s[i-1]=='G')
v[i]=v[i-1]+1;
if(s[i]=='G' && s[i-1]=='S')
v[i]=1;
}
for(int i=t-2;i>=0;i--)
{
if(v[i]!=0)
v[i]=max(v[i+1],v[i]);
}
int mx=*max_element(v.begin(),v.end());
//if can swap is >=2 then i can swap the current s with any of the g
vector<int>prefix(t,0),suffix(t,0);
if(s[0]=='G')
prefix[0]=1;
for(int i=1;i<t;i++)
{
if(s[i]=='G')
prefix[i]=prefix[i-1]+1;
else
prefix[i]=prefix[i-1];
}
if(s[t-1]=='G')
suffix[t-1]=1;
for(int i=t-2;i>=0;i--)
{
if(s[i]=='G')
suffix[i]=suffix[i+1]+1;
else
suffix[i]=suffix[i+1];
}
//print
// for(int i=0;i<t;i++)
// cout<<v[i]<<" ";
// cout<<endl;
// for(int i=0;i<t;i++)
// cout<<prefix[i]<<" ";
// cout<<endl;
// for(int i=0;i<t;i++)
// cout<<suffix[i]<<" ";
// cout<<endl;
//print over
for(int i=1;i<t-1;i++)
{
if(v[i]==0 && v[i-1]!=0 && v[i+1]!=0)
{
//check if we have an extra g to swap beyond the 2 consective seq
bool ok=false;
int look_back=i-v[i-1]-1;
int look_front=i+v[i+1]+1;
//cout<<i<<" "<<look_back<<" "<<look_front<<endl;
if(look_back>=0 && prefix[look_back]>0)
ok=true;
if(look_front<t && suffix[look_front]>0)
ok=true;
if(ok)
mx=max(mx,v[i-1]+v[i+1]+1);
else
mx=max(mx,v[i-1]+v[i+1]);
}
//case 1 GSSGGGG
//if here i replce the first S i get the size of 2 if I replace the second S i get 4
else if(v[i]==0 && v[i-1]!=0)
{
//we are extending the last segment
int look_front=i;
int look_back=i-v[i-1]-1;
bool ok=false;
if(suffix[look_front]>0)
ok=true;
if(look_back>=0 && prefix[look_back]>0)
ok=true;
if(ok)
mx=max(mx,v[i-1]+1);
}
else if(v[i]==0 && v[i+1]!=0)
{
bool ok=false;
int look_front=i+v[i+1]+1;
int look_back=i;
if(prefix[look_back]>0)
ok=true;
if(look_front<t && suffix[look_front]>0)
ok=true;
if(ok)
mx=max(mx,v[i+1]+1);
}
}
cout<<mx<<endl;
return 0;
}
| 23.510204
| 106
| 0.530093
|
onexmaster
|
3208de8949a1662d0acd4a62337215eb51f7ad50
| 1,728
|
hpp
|
C++
|
modules/core/feature/include/opengv2/feature/FeatureBase.hpp
|
MobilePerceptionLab/EventCameraCalibration
|
debd774ac989674b500caf27641b7ad4e94681e9
|
[
"Apache-2.0"
] | 22
|
2021-08-06T03:21:03.000Z
|
2022-02-25T03:40:54.000Z
|
modules/core/feature/include/opengv2/feature/FeatureBase.hpp
|
MobilePerceptionLab/MultiCamCalib
|
2f0e94228c2c4aea7f20c26e3e8daa6321ce8022
|
[
"Apache-2.0"
] | 1
|
2022-02-25T02:55:13.000Z
|
2022-02-25T15:18:45.000Z
|
modules/core/feature/include/opengv2/feature/FeatureBase.hpp
|
MobilePerceptionLab/MultiCamCalib
|
2f0e94228c2c4aea7f20c26e3e8daa6321ce8022
|
[
"Apache-2.0"
] | 7
|
2021-08-11T12:29:35.000Z
|
2022-02-25T03:41:01.000Z
|
//
// Created by huangkun on 2019/12/30.
//
#ifndef OPENGV2_FEATUREBASE_HPP
#define OPENGV2_FEATUREBASE_HPP
#include <memory>
#include <Eigen/Eigen>
#include <opengv2/landmark/LandmarkBase.hpp>
namespace opengv2 {
class FeatureBase { // TODO: inherit ObservationBase
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef std::shared_ptr<FeatureBase> Ptr;
explicit FeatureBase(const Eigen::Ref<const Eigen::VectorXd> &loc) :
locBackup(loc), landmark_(LandmarkBase::Ptr()), loc_(loc), bearingVector_(Eigen::VectorXd()) {}
virtual ~FeatureBase() = default;
inline LandmarkBase::Ptr landmark() const noexcept {
return landmark_.lock();
}
/**
* @note Warning: Not thread safe.
*/
inline void setLandmark(const LandmarkBase::Ptr &lm) noexcept {
landmark_ = lm;
}
inline const Eigen::VectorXd &location() const noexcept {
return loc_;
}
/**
* @note Warning: Not thread safe.
*/
virtual inline void setLocation(const Eigen::Ref<const Eigen::VectorXd> &loc) noexcept {
loc_ = loc;
}
inline const Eigen::VectorXd &bearingVector() noexcept {
return bearingVector_;
}
/**
* @note Warning: Not thread safe.
*/
inline void setBearingVector(const Eigen::Ref<const Eigen::VectorXd> &bv) {
bearingVector_ = bv;
}
Eigen::VectorXd locBackup; // backup
protected:
std::weak_ptr<LandmarkBase> landmark_;
Eigen::VectorXd loc_;
Eigen::VectorXd bearingVector_;
};
}
#endif //OPENGV2_FEATUREBASE_HPP
| 25.043478
| 111
| 0.600116
|
MobilePerceptionLab
|
320ad7582601aa0c407b9fc613bf6d96159f5191
| 518
|
hpp
|
C++
|
src/wrapper.hpp
|
Dreae/SourceLua
|
5737eaf3d77bbd715b258df78ab101265890662c
|
[
"Apache-2.0"
] | null | null | null |
src/wrapper.hpp
|
Dreae/SourceLua
|
5737eaf3d77bbd715b258df78ab101265890662c
|
[
"Apache-2.0"
] | null | null | null |
src/wrapper.hpp
|
Dreae/SourceLua
|
5737eaf3d77bbd715b258df78ab101265890662c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef _INCLUDE_WRAPPER
#define _INCLUDE_WRAPPER
#include <ISmmPlugin.h>
#include "iplayerinfo.h"
#if SOURCE_ENGINE <= SE_DARKMESSIAH
/**
* Wrap the CCommand class so our code looks the same on all engines.
*/
class CCommand
{
public:
const char *ArgS()
{
return g_Engine->Cmd_Args();
}
int ArgC()
{
return g_Engine->Cmd_Argc();
}
const char *Arg(int index)
{
return g_Engine->Cmd_Argv(index);
}
};
#define CVAR_INTERFACE_VERSION VENGINE_CVAR_INTERFACE_VERSION
#endif
#endif // _INCLUDE_WRAPPER
| 15.69697
| 69
| 0.727799
|
Dreae
|
320aee2d2c17261395b2ff39b854baa01a6971bb
| 8,311
|
cc
|
C++
|
pigasus/software/tools/snort2lua/output_states/out_csv.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
pigasus/software/tools/snort2lua/output_states/out_csv.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
pigasus/software/tools/snort2lua/output_states/out_csv.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
//--------------------------------------------------------------------------
// Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// out_csv.cc author Josh Rosenbaum <jrosenba@cisco.com>
#include <sstream>
#include <vector>
#include "conversion_state.h"
#include "helpers/converter.h"
#include "helpers/s2l_util.h"
namespace output
{
namespace
{
class AlertCsv : public ConversionState
{
public:
AlertCsv(Converter& c) : ConversionState(c) { }
bool convert(std::istringstream& data_stream) override;
};
} // namespace
bool AlertCsv::convert(std::istringstream& data_stream)
{
std::string keyword;
std::string val;
bool retval = true;
int limit;
char c = '\0';
table_api.open_top_level_table("alert_csv");
if (!(data_stream >> keyword))
return true;
table_api.add_deleted_comment("<filename> can no longer be specific");
if (!(data_stream >> keyword))
return retval;
table_api.add_diff_option_comment("csv", "fields");
// parsing the format list.
std::istringstream format(keyword);
while (std::getline(format, val, ','))
{
bool tmpval = true;
if (val == "default")
table_api.add_deleted_comment("default");
else if (val == "timestamp")
tmpval = table_api.add_list("fields", "timestamp");
else if (val == "msg")
tmpval = table_api.add_list("fields", "msg");
else if (val == "proto")
tmpval = table_api.add_list("fields", "proto");
else if (val == "ttl")
tmpval = table_api.add_list("fields", "ttl");
else if (val == "tos")
tmpval = table_api.add_list("fields", "tos");
else if (val == "trheader")
tmpval = table_api.add_deleted_comment("trheader");
else if (val == "dst")
{
table_api.add_diff_option_comment("dst", "dst_addr");
tmpval = table_api.add_list("fields", "dst_addr");
}
else if (val == "src")
{
table_api.add_diff_option_comment("src", "src_addr");
tmpval = table_api.add_list("fields", "src_addr");
}
else if (val == "sig_generator")
{
table_api.add_diff_option_comment("sig_generator", "gid");
tmpval = table_api.add_list("fields", "gid");
}
else if (val == "sig_id")
{
table_api.add_diff_option_comment("sig_id", "sid");
tmpval = table_api.add_list("fields", "sid");
}
else if (val == "sig_rev")
{
table_api.add_diff_option_comment("sig_rev", "rev");
tmpval = table_api.add_list("fields", "rev");
}
else if (val == "srcport")
{
table_api.add_diff_option_comment("srcport", "src_port");
tmpval = table_api.add_list("fields", "src_port");
}
else if (val == "dstport")
{
table_api.add_diff_option_comment("dstport", "dst_port");
tmpval = table_api.add_list("fields", "dst_port");
}
else if (val == "ethsrc")
{
table_api.add_diff_option_comment("ethsrc", "eth_src");
tmpval = table_api.add_list("fields", "eth_src");
}
else if (val == "ethdst")
{
table_api.add_diff_option_comment("ethdst", "eth_dst");
tmpval = table_api.add_list("fields", "eth_dst");
}
else if (val == "ethlen")
{
table_api.add_diff_option_comment("ethlen", "eth_len");
tmpval = table_api.add_list("fields", "eth_len");
}
else if (val == "ethtype")
{
table_api.add_diff_option_comment("ethtype", "eth_type");
tmpval = table_api.add_list("fields", "eth_type");
}
else if (val == "tcpflags")
{
table_api.add_diff_option_comment("tcpflags", "tcp_flags");
tmpval = table_api.add_list("fields", "tcp_flags");
}
else if (val == "tcpseq")
{
table_api.add_diff_option_comment("tcpseq", "tcp_seq");
tmpval = table_api.add_list("fields", "tcp_seq");
}
else if (val == "tcpack")
{
table_api.add_diff_option_comment("tcpack", "tcp_ack");
tmpval = table_api.add_list("fields", "tcp_ack");
}
else if (val == "tcplen")
{
table_api.add_diff_option_comment("tcplen", "tcp_len");
tmpval = table_api.add_list("fields", "tcp_len");
}
else if (val == "tcpwindow")
{
table_api.add_diff_option_comment("tcpwindow", "tcp_win");
tmpval = table_api.add_list("fields", "tcp_win");
}
else if (val == "dgmlen")
{
table_api.add_diff_option_comment("dgmlen", "pkt_len");
tmpval = table_api.add_list("fields", "pkt_len");
}
else if (val == "id")
{
table_api.add_diff_option_comment("id", "ip_id");
tmpval = table_api.add_list("fields", "ip_id");
}
else if (val == "iplen")
{
table_api.add_diff_option_comment("iplen", "ip_len");
tmpval = table_api.add_list("fields", "ip_len");
}
else if (val == "icmptype")
{
table_api.add_diff_option_comment("icmptype", "icmp_type");
tmpval = table_api.add_list("fields", "icmp_type");
}
else if (val == "icmpcode")
{
table_api.add_diff_option_comment("icmpcode", "icmp_code");
tmpval = table_api.add_list("fields", "icmp_code");
}
else if (val == "icmpid")
{
table_api.add_diff_option_comment("icmpid", "icmp_id");
tmpval = table_api.add_list("fields", "icmp_id");
}
else if (val == "icmpseq")
{
table_api.add_diff_option_comment("icmpseq", "icmp_seq");
tmpval = table_api.add_list("fields", "icmp_seq");
}
else if (val == "udplength")
{
table_api.add_diff_option_comment("udplength", "udp_len");
tmpval = table_api.add_list("fields", "udp_len");
}
else
{
tmpval = false;
}
if (!tmpval)
{
data_api.failed_conversion(data_stream, val);
retval = false;
}
}
if (!(data_stream >> limit))
return retval;
if (data_stream >> c)
{
if (limit <= 0)
limit = 0;
else if (c == 'K' || c == 'k')
limit = (limit + 1023) / 1024;
else if (c == 'G' || c == 'g')
limit *= 1024;
}
else
limit = (limit + 1024*1024 - 1) / (1024*1024);
retval = table_api.add_option("limit", limit) && retval;
retval = table_api.add_comment("limit now in MB, converted") && retval;
retval = table_api.add_deleted_comment("units") && retval;
return retval;
}
/**************************
******* A P I ***********
**************************/
static ConversionState* ctor(Converter& c)
{
c.get_table_api().open_top_level_table("alert_csv"); // in case there are no arguments
c.get_table_api().close_table();
return new AlertCsv(c);
}
static const ConvertMap alert_csv_api =
{
"alert_csv",
ctor,
};
const ConvertMap* alert_csv_map = &alert_csv_api;
} // namespace output
| 32.088803
| 90
| 0.553844
|
zhipengzhaocmu
|
320ba053f76ac48a47fd3cf23ed89c7d478b06f7
| 3,891
|
cpp
|
C++
|
src/SplitFit.cpp
|
IWantedToBeATranslator/2D-Strip-Packing
|
4ee9a220f2e9debf775b020d961f0ba547f32636
|
[
"MIT"
] | 1
|
2017-12-12T19:23:44.000Z
|
2017-12-12T19:23:44.000Z
|
src/SplitFit.cpp
|
IWantedToBeATranslator/2D-Strip-Packing
|
4ee9a220f2e9debf775b020d961f0ba547f32636
|
[
"MIT"
] | 1
|
2016-04-20T18:47:05.000Z
|
2016-05-04T08:05:45.000Z
|
src/SplitFit.cpp
|
IWantedToBeATranslator/2D-Strip-Packing
|
4ee9a220f2e9debf775b020d961f0ba547f32636
|
[
"MIT"
] | 1
|
2019-07-14T15:39:27.000Z
|
2019-07-14T15:39:27.000Z
|
#include "SplitFit.h"
SplitFit::SplitFit()
{
int levelH[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int levels = 1;
int levelW[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int levelHmin = 0;
int levelRH[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int levelsR = 1;
int levelRW[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
spColorRectSprite bloxBuffer;
spColorRectSprite *WideBlox = new spColorRectSprite[eCount];
spColorRectSprite *ThinBlox = new spColorRectSprite[eCount];
sortNonDecr(_bloxArray, bloxHeights, bloxWidths);
int CountRest = 0;
int Count12 = 0;
FOR(i, 0, eCount)
{
if (_bloxArray[i]->getWidth() > clipWidth / 2)
{
WideBlox[Count12] = _bloxArray[i];
Count12++;
}
else
{
ThinBlox[CountRest] = _bloxArray[i];
CountRest++;
}
}
FOR(i, 0, Count12)
FOR(j, 0, Count12 - 1)
if (WideBlox[j]->getWidth() < WideBlox[j + 1]->getWidth())
{
bloxBuffer = WideBlox[j];
WideBlox[j] = WideBlox[j + 1];
WideBlox[j + 1] = bloxBuffer;
}
FOR(i, 0, Count12)
{
WideBlox[i]->addTween(Actor::TweenPosition(0, levelHmin), 500);
levelHmin += WideBlox[i]->getHeight();
}
int regionRW = 0;
int regionRH = 0;
int regionRX = 0;
int regionRY = 0;
int levelRHmin = 0;
FOR(i, 0, Count12)
{
if (WideBlox[i]->getWidth() < 2 * clipWidth / 3)
{
regionRX = WideBlox[i]->getWidth();
regionRY = regionRH;
regionRW = clipWidth - regionRX;
regionRH = levelHmin - regionRH;
break;
}
regionRH += WideBlox[i]->getHeight();
}
int Rcheck = 0;
int Restcheck = 0;
int checker = 0;
int RorO = 0;
FOR(i, 0, CountRest)
{
if ((ThinBlox[i]->getHeight() <= regionRH) && (ThinBlox[i]->getWidth() <= regionRW))
RorO = 1;
else
RorO = 0;
if (RorO)
{
if (Rcheck)
{
checker = 0;
FOR(k, 0, levelsR)
{
if (regionRW - levelRW[k] >= ThinBlox[i]->getWidth() && !checker)
{
ThinBlox[i]->addTween(Actor::TweenPosition(regionRX + levelRW[k], regionRY + levelRH[k]), 500);
levelRW[k] += ThinBlox[i]->getWidth();
checker = 1;
}
}
if (!checker)
{
if (ThinBlox[i]->getHeight() <= regionRH - levelRHmin)
{
levelsR++;
levelRHmin += ThinBlox[i]->getHeight();
levelRH[levelsR] = levelRHmin;
ThinBlox[i]->addTween(Actor::TweenPosition(regionRX + levelRW[levelsR - 1], regionRY + levelRH[levelsR - 1]), 500);
levelRW[levelsR - 1] += ThinBlox[i]->getWidth();
}
else
RorO = 0;
}
}
else
{
Rcheck = 1;
ThinBlox[i]->addTween(Actor::TweenPosition(regionRX, regionRY), 500);
levelRH[1] = ThinBlox[i]->getHeight();
levelRW[0] = ThinBlox[i]->getWidth();
levelRHmin = levelRH[1];
checker = 0;
}
}
if (!RorO)
{
if (Restcheck)
{
checker = 0;
FOR(k, 0, levels)
{
if (clipWidth - levelW[k] >= ThinBlox[i]->getWidth() && !checker)
{
ThinBlox[i]->addTween(Actor::TweenPosition(levelW[k], levelH[k]), 500);
levelW[k] += ThinBlox[i]->getWidth();
checker = 1;
}
}
if (!checker)
{
levels++;
levelHmin += ThinBlox[i]->getHeight();
levelH[levels] = levelHmin;
ThinBlox[i]->addTween(Actor::TweenPosition(levelW[levels - 1], levelH[levels - 1]), 500);
levelW[levels - 1] += ThinBlox[i]->getWidth();
}
}
else
{
Restcheck = 1;
ThinBlox[i]->addTween(Actor::TweenPosition(0, levelHmin), 500);
levelH[0] = levelHmin;
levelH[1] = levelHmin + ThinBlox[i]->getHeight();
levelW[0] = ThinBlox[i]->getWidth();
levelHmin = levelH[1];
checker = 0;
}
}
}
algosHeights = levelHmin;
updateState;
}
| 24.018519
| 122
| 0.555641
|
IWantedToBeATranslator
|
320bf69707aaae190ebccb03cd7d07ac9c80ace7
| 677
|
cpp
|
C++
|
codes_of_questions/1007_DNA_sorting.cpp
|
Zaryob/algorithmsolutions
|
3f3270aed8274b5a7102afe5f21aa8da0245625e
|
[
"MIT"
] | 5
|
2021-03-27T21:26:07.000Z
|
2021-12-23T22:15:37.000Z
|
codes_of_questions/1007_DNA_sorting.cpp
|
Zaryob/algorithmsolutions
|
3f3270aed8274b5a7102afe5f21aa8da0245625e
|
[
"MIT"
] | null | null | null |
codes_of_questions/1007_DNA_sorting.cpp
|
Zaryob/algorithmsolutions
|
3f3270aed8274b5a7102afe5f21aa8da0245625e
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct dna
{
int pos;
int key;
string str;
};
bool cmp(const dna &a, const dna &b)
{
if (a.key != b.key)
{
return a.key < b.key;
}
else
{
return a.pos < b.pos;
}
}
int main()
{
int n, m, count;
dna inv[110];
string str;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> str;
count = 0;
for (int j = 0; j < n - 1; j++)
{
for (int k = j + 1; k < n; k++)
{
if (str[j] > str[k]) count++;
}
}
inv[i].key = count;
inv[i].pos = i;
inv[i].str = str;
}
sort(inv, inv + m, cmp);
for (int i = 0; i < m; i++)
{
cout << inv[i].str << endl;
}
return 0;
}
| 11.877193
| 36
| 0.478582
|
Zaryob
|
320cf2711bacf04a487260e91cd6e5effe949e09
| 2,792
|
cpp
|
C++
|
source/resource/font.cpp
|
synaodev/LeviathanRacket
|
c70dfddf0097c7f4e902ec5de46a6eabed5a4691
|
[
"MIT"
] | 5
|
2020-03-25T14:46:23.000Z
|
2022-02-23T01:46:26.000Z
|
source/resource/font.cpp
|
synaodev/LeviathanRacket
|
c70dfddf0097c7f4e902ec5de46a6eabed5a4691
|
[
"MIT"
] | 1
|
2022-01-14T00:01:48.000Z
|
2022-01-14T00:01:48.000Z
|
source/resource/font.cpp
|
synaodev/LeviathanRacket
|
c70dfddf0097c7f4e902ec5de46a6eabed5a4691
|
[
"MIT"
] | 2
|
2020-03-25T14:46:24.000Z
|
2020-08-21T04:33:23.000Z
|
#include "./font.hpp"
#include "./vfs.hpp"
#include "../utility/logger.hpp"
#include "../video/texture.hpp"
#include <fstream>
#include <glm/gtc/constants.hpp>
#include <nlohmann/json.hpp>
const font_glyph_t font_t::kNullGlyph {};
void font_t::load(const std::string& directory, const std::string& name) {
auto make_table = [](const std::string& value) {
switch (std::stoi(value)) {
case 1: return 2;
case 2: return 1;
case 4: return 0;
case 8: return 3;
default: return 0;
}
};
if (!glyphs.empty()) {
synao_log("Warning! Tried to overwrite font!\n");
return;
}
const std::string full_path = directory + name;
std::ifstream ifs { full_path, std::ios::binary };
if (ifs.is_open()) {
nlohmann::json file = nlohmann::json::parse(ifs);
auto block = file["font"];
dimensions.x = std::stof(block["common"]["-base"].get<std::string>());
dimensions.y = std::stof(block["common"]["-lineHeight"].get<std::string>());
atlas = vfs_t::atlas(block["pages"]["page"]["-file"].get<std::string>());
for (auto ot : block["chars"]["char"]) {
char32_t id = std::stoi(ot["-id"].get<std::string>());
const font_glyph_t glyph {
std::stof(ot["-x"].get<std::string>()),
std::stof(ot["-y"].get<std::string>()),
std::stof(ot["-width"].get<std::string>()),
std::stof(ot["-height"].get<std::string>()),
std::stof(ot["-xoffset"].get<std::string>()),
std::stof(ot["-yoffset"].get<std::string>()),
std::stof(ot["-xadvance"].get<std::string>()),
std::invoke(make_table, ot["-chnl"].get<std::string>())
};
glyphs[id] = glyph;
}
if (block.find("kernings") != block.end()) {
for (auto ot : block["kernings"]["kerning"]) {
char32_t first = std::stoi(ot["-first"].get<std::string>());
char32_t second = std::stoi(ot["-second"].get<std::string>());
auto key = std::pair{first, second};
kernings[key] = std::stof(ot["-amount"].get<std::string>());
}
}
} else {
synao_log("Failed to load font from {}!\n", full_path);
}
}
const font_glyph_t& font_t::glyph(char32_t code_point) const {
auto it = glyphs.find(code_point);
if (it == glyphs.end()) {
return kNullGlyph;
}
return it->second;
}
real_t font_t::kerning(char32_t first, char32_t second) const {
if (first == U'\0' or second == U'\0') {
return 0.0f;
}
auto it = kernings.find(std::pair{first, second});
if (it == kernings.end()) {
return 0.0f;
}
return it->second;
}
const atlas_t* font_t::get_atlas() const {
return atlas;
}
sint_t font_t::get_atlas_name() const {
if (atlas) {
return atlas->get_name();
}
return 0;
}
glm::vec2 font_t::get_inverse_dimensions() const {
if (atlas) {
return atlas->get_inverse_dimensions();
}
return glm::one<glm::vec2>();
}
glm::vec2 font_t::get_dimensions() const {
return dimensions;
}
| 25.851852
| 78
| 0.625358
|
synaodev
|
320e6f684dea75528b653b8b6172938f63e9d919
| 436
|
cpp
|
C++
|
src/Red/Data/JSON/Number.cpp
|
OutOfTheVoid/ProjectRed
|
801327283f5a302be130c90d593b39957c84cce5
|
[
"MIT"
] | 1
|
2020-06-14T06:14:50.000Z
|
2020-06-14T06:14:50.000Z
|
src/Red/Data/JSON/Number.cpp
|
OutOfTheVoid/ProjectRed
|
801327283f5a302be130c90d593b39957c84cce5
|
[
"MIT"
] | null | null | null |
src/Red/Data/JSON/Number.cpp
|
OutOfTheVoid/ProjectRed
|
801327283f5a302be130c90d593b39957c84cce5
|
[
"MIT"
] | null | null | null |
#include <Red/Data/JSON/Number.h>
Red::Data::JSON::Number :: Number ( double Value ):
RefCounted ( 0 ),
Value ( Value )
{
}
Red::Data::JSON::Number :: ~Number ()
{
}
Red::Data::JSON::IType :: DataType Red::Data::JSON::Number :: GetType () const
{
return kDataType_Number;
}
double Red::Data::JSON::Number :: Get ()
{
return Value;
}
void Red::Data::JSON::Number :: Set ( double Value )
{
this -> Value = Value;
}
| 13.212121
| 78
| 0.605505
|
OutOfTheVoid
|
32112ab813d3aa682de5b9cba42ab4654fb1fb80
| 10,516
|
cpp
|
C++
|
work_addons/ofxXTween/src/ofxXTweener.cpp
|
jjongun/ofxAddons
|
44958f20e5dfcd71cfa5c5596aa0c480893894b8
|
[
"MIT"
] | null | null | null |
work_addons/ofxXTween/src/ofxXTweener.cpp
|
jjongun/ofxAddons
|
44958f20e5dfcd71cfa5c5596aa0c480893894b8
|
[
"MIT"
] | null | null | null |
work_addons/ofxXTween/src/ofxXTweener.cpp
|
jjongun/ofxAddons
|
44958f20e5dfcd71cfa5c5596aa0c480893894b8
|
[
"MIT"
] | null | null | null |
#include "ofxXTweener.h"
#pragma region Easing functions
/***** LINEAR ****/
float Linear::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Linear::easeIn(float t, float b, float c, float d) {
return c*t / d + b;
}
float Linear::easeOut(float t, float b, float c, float d) {
return c*t / d + b;
}
float Linear::easeInOut(float t, float b, float c, float d) {
return c*t / d + b;
}
/***** SINE ****/
float Sine::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Sine::easeIn(float t, float b, float c, float d) {
return -c * cos(t / d * float(PI / 2)) + c + b;
}
float Sine::easeOut(float t, float b, float c, float d) {
return c * sin(t / d * float(PI / 2)) + b;
}
float Sine::easeInOut(float t, float b, float c, float d) {
return -c / 2 * float(cos(PI*t / d) - 1) + b;
}
/**** Quint ****/
float Quint::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Quint::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t*t*t*t + b;
}
float Quint::easeOut(float t, float b, float c, float d) {
return c*((t = t / d - 1)*t*t*t*t + 1) + b;
}
float Quint::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return c / 2 * t*t*t*t*t + b;
return c / 2 * ((t -= 2)*t*t*t*t + 2) + b;
}
/**** Quart ****/
float Quart::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Quart::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t*t*t + b;
}
float Quart::easeOut(float t, float b, float c, float d) {
return -c * ((t = t / d - 1)*t*t*t - 1) + b;
}
float Quart::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return c / 2 * t*t*t*t + b;
return -c / 2 * ((t -= 2)*t*t*t - 2) + b;
}
/**** Quad ****/
float Quad::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Quad::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t + b;
}
float Quad::easeOut(float t, float b, float c, float d) {
return -c *(t /= d)*(t - 2) + b;
}
float Quad::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return ((c / 2)*(t*t)) + b;
return -c / 2 * (((t - 2)*(--t)) - 1) + b;
/*
originally return -c/2 * (((t-2)*(--t)) - 1) + b;
I've had to swap (--t)*(t-2) due to diffence in behaviour in
pre-increment operators between java and c++, after hours
of joy
*/
}
/**** Expo ****/
float Expo::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Expo::easeIn(float t, float b, float c, float d) {
return float((t == 0) ? b : c * pow(2, 10 * (t / d - 1)) + b);
}
float Expo::easeOut(float t, float b, float c, float d) {
return float((t == d) ? b + c : c * (-pow(2, -10 * t / d) + 1) + b);
}
float Expo::easeInOut(float t, float b, float c, float d) {
if (t == 0) return b;
if (t == d) return b + c;
if ((t /= d / 2) < 1) return float(c / 2 * pow(2, 10 * (t - 1)) + b);
return float(c / 2 * (-pow(2, -10 * --t) + 2) + b);
}
/**** Elastic ****/
float Elastic::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Elastic::easeIn(float t, float b, float c, float d) {
if (t == 0) return b; if ((t /= d) == 1) return b + c;
float p = d*.3f;
float a = c;
float s = p / 4;
float postFix = float(a*pow(2, 10 * (t -= 1))); // this is a fix, again, with post-increment operators
return float(-(postFix * sin((t*d - s)*(2 * PI) / p)) + b);
}
float Elastic::easeOut(float t, float b, float c, float d) {
if (t == 0) return b; if ((t /= d) == 1) return b + c;
float p = d*.3f;
float a = c;
float s = p / 4;
return float(a*pow(2, -10 * t) * sin((t*d - s)*(2 * PI) / p) + c + b);
}
float Elastic::easeInOut(float t, float b, float c, float d) {
if (t == 0) return b; if ((t /= d / 2) == 2) return b + c;
float p = d*(.3f*1.5f);
float a = c;
float s = p / 4;
if (t < 1) {
float postFix = float(a*pow(2, 10 * (t -= 1))); // postIncrement is evil
return float(-.5f*(postFix* sin((t*d - s)*(2 * PI) / p)) + b);
}
float postFix = float(a*pow(2, -10 * (t -= 1))); // postIncrement is evil
return postFix * float(sin((t*d - s)*(2 * PI) / p)*.5f + c + b);
}
/**** Cubic ****/
float Cubic::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Cubic::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t*t + b;
}
float Cubic::easeOut(float t, float b, float c, float d) {
return c*((t = t / d - 1)*t*t + 1) + b;
}
float Cubic::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return c / 2 * t*t*t + b;
return c / 2 * ((t -= 2)*t*t + 2) + b;
}
/*** Circ ***/
float Circ::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Circ::easeIn(float t, float b, float c, float d) {
return -c * (sqrt(1 - (t /= d)*t) - 1) + b;
}
float Circ::easeOut(float t, float b, float c, float d) {
return c * sqrt(1 - (t = t / d - 1)*t) + b;
}
float Circ::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return -c / 2 * (sqrt(1 - t*t) - 1) + b;
return c / 2 * (sqrt(1 - t*(t -= 2)) + 1) + b;
}
/**** Bounce ****/
float Bounce::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Bounce::easeIn(float t, float b, float c, float d) {
return c - easeOut(d - t, 0, c, d) + b;
}
float Bounce::easeOut(float t, float b, float c, float d) {
if ((t /= d) < (1 / 2.75f)) {
return c*(7.5625f*t*t) + b;
}
else if (t < (2 / 2.75f)) {
float postFix = t -= (1.5f / 2.75f);
return c*(7.5625f*(postFix)*t + .75f) + b;
}
else if (t < (2.5 / 2.75)) {
float postFix = t -= (2.25f / 2.75f);
return c*(7.5625f*(postFix)*t + .9375f) + b;
}
else {
float postFix = t -= (2.625f / 2.75f);
return c*(7.5625f*(postFix)*t + .984375f) + b;
}
}
float Bounce::easeInOut(float t, float b, float c, float d) {
if (t < d / 2) return easeIn(t * 2, 0, c, d) * .5f + b;
else return easeOut(t * 2 - d, 0, c, d) * .5f + c*.5f + b;
}
/**** Back *****/
float Back::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Back::easeIn(float t, float b, float c, float d) {
float s = 1.70158f;
float postFix = t /= d;
return c*(postFix)*t*((s + 1)*t - s) + b;
}
float Back::easeOut(float t, float b, float c, float d) {
float s = 1.70158f;
return c*((t = t / d - 1)*t*((s + 1)*t + s) + 1) + b;
}
float Back::easeInOut(float t, float b, float c, float d) {
float s = 1.70158f;
if ((t /= d / 2) < 1) return c / 2 * (t*t*(((s *= (1.525f)) + 1)*t - s)) + b;
float postFix = t -= 2;
return c / 2 * ((postFix)*t*(((s *= (1.525f)) + 1)*t + s) + 2) + b;
}
#pragma endregion
//implementation Tweener Class*********************************************************
#pragma region ofxXTween
float ofxXTweener::runEquation(int transition, int equation, float t, float b, float c, float d) {
float result = 0;
if (equation == EASE_IN) {
result = funcs[transition]->easeIn(t, b, c, d);
}
else if (equation == EASE_OUT) {
result = funcs[transition]->easeOut(t, b, c, d);
}
else if (equation == EASE_IN_OUT) {
result = funcs[transition]->easeInOut(t, b, c, d);
}
else if (equation == EASE_NONE)
{
result = funcs[transition]->easeNone(t, b, c, d);
}
return result;
}
void ofxXTweener::callTween(long duration, float start , float end, int draw_priority, Transition transition, Equation ease , TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
updateTween = update;
completeTween = complete;
this->duration = duration;
this->start_value = start;
this->end_value = end;
this->draw_priority = draw_priority;
this->transition = transition;
this->ease = ease;
zerofloat = 0.0f;
updateTween(0.0f);
StartTimer(draw_priority);
}
void ofxXTweener::Run(long duration, float start, float end, int draw_priority, Transition transition, Equation ease, TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, start, end, draw_priority, transition, ease, update,
[complete , tween]() {
complete();
delete tween;
});
}
void ofxXTweener::Run(long duration, float start, float end, int draw_priority, Transition transition, Equation ease, TWEEN_CALLBACK update)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, start, end, draw_priority, transition, ease, update ,
[tween]() {
delete tween;
});
}
void ofxXTweener::Run(long duration, float start, float end, Transition transition, Equation ease, TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, start, end, ofEventOrder::OF_EVENT_ORDER_APP, transition, ease, update,
[complete , tween]() {
complete();
delete tween;
});
}
void ofxXTweener::RunZeroToOne(long duration, Transition transition, Equation ease, TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, 0, 1, ofEventOrder::OF_EVENT_ORDER_APP , transition, ease, update,
[complete, tween]() {
complete();
delete tween;
});
}
void ofxXTweener::RunZeroToOne(long duration, Transition transition, Equation ease, TWEEN_CALLBACK update)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, 0, 1, ofEventOrder::OF_EVENT_ORDER_APP, transition, ease, update,
[tween]() {
delete tween;
});
}
void ofxXTweener::StartTimer(int draw_priority)
{
start_time = ofGetElapsedTimef();
ofAddListener(ofEvents().draw, this, &ofxXTweener::timeElapsed , draw_priority);
}
void ofxXTweener::StopTimer(int draw_priority)
{
ofRemoveListener(ofEvents().draw, this, &ofxXTweener::timeElapsed , draw_priority);
}
void ofxXTweener::timeElapsed(ofEventArgs &e)
{
float elapsed = ofGetElapsedTimef() - start_time;
if (elapsed < 0.0001f)
elapsed = 0;
//float res = runEquation(CUBIC, EASE_OUT, elapsed, 0, 1, duration);
float res = runEquation(transition, ease, elapsed, 0, 1, duration);
res = ofMap(res, 0, 1, start_value, end_value);
updateTween(res);
if (elapsed > duration)
{
StopTimer(this->draw_priority);
completeTween();
}
}
ofxXTweener::ofxXTweener()
{
zerofloat = 0.0f;
this->funcs[LINEAR] = &nfLinear;
this->funcs[SINE] = &nfSine;
this->funcs[QUINT] = &nfQuint;
this->funcs[QUART] = &nfQuart;
this->funcs[QUAD] = &nfQuad;
this->funcs[EXPO] = &nfExpo;
this->funcs[ELASTIC] = &nfElastic;
this->funcs[CUBIC] = &nfCubic;
this->funcs[CIRC] = &nfCirc;
this->funcs[BOUNCE] = &nfBounce;
this->funcs[BACK] = &nfBack;
lastTime = 0;
}
ofxXTweener::~ofxXTweener()
{
}
#pragma endregion
| 27.103093
| 176
| 0.603461
|
jjongun
|
32121d63e621256eef322efc6b1f72fcfcc9a340
| 761
|
hpp
|
C++
|
src/protocols/wl/data_device.hpp
|
Link1J/Awning
|
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
|
[
"MIT"
] | null | null | null |
src/protocols/wl/data_device.hpp
|
Link1J/Awning
|
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
|
[
"MIT"
] | null | null | null |
src/protocols/wl/data_device.hpp
|
Link1J/Awning
|
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <wayland-server.h>
#include <unordered_map>
#include <vector>
#include <string>
namespace Awning::Protocols::WL::Data_Device
{
extern const struct wl_data_device_interface interface;
namespace Interface
{
void Start_Drag(struct wl_client* client, struct wl_resource* resource, struct wl_resource* source, struct wl_resource* origin, struct wl_resource* icon, uint32_t serial);
void Set_Selection(struct wl_client* client, struct wl_resource* resource, struct wl_resource* source, uint32_t serial);
void Release(struct wl_client* client, struct wl_resource* resource);
}
wl_resource* Create(struct wl_client* wl_client, uint32_t version, uint32_t id, struct wl_resource* seat);
void Destroy(struct wl_resource* resource);
}
| 34.590909
| 173
| 0.792378
|
Link1J
|
321459382e58a205aac83dd508d19189b1440df1
| 7,119
|
cpp
|
C++
|
Engine/Dependences/Framework/Depends/LuaBridge/Tests/Source/NamespaceTests.cpp
|
GlebShikovec/SREngine
|
bb806c3e4da06ef6fddee5b46ed5d2fca231be43
|
[
"MIT"
] | 7
|
2020-10-16T11:34:27.000Z
|
2022-03-12T17:53:15.000Z
|
Engine/Dependences/Framework/Depends/LuaBridge/Tests/Source/NamespaceTests.cpp
|
Kiper220/SREngine
|
f1fa36b5ded1f489a9fdb59d8d4b40eb294ba9ec
|
[
"MIT"
] | 1
|
2022-03-07T14:42:22.000Z
|
2022-03-07T14:42:22.000Z
|
Engine/Dependences/Framework/Depends/LuaBridge/Tests/Source/NamespaceTests.cpp
|
GlebShikovec/SREngine
|
bb806c3e4da06ef6fddee5b46ed5d2fca231be43
|
[
"MIT"
] | 6
|
2021-05-06T15:09:52.000Z
|
2022-03-12T17:57:14.000Z
|
// https://github.com/vinniefalco/LuaBridge
//
// Copyright 2019, Dmitry Tarakanov
// SPDX-License-Identifier: MIT
#include "TestBase.h"
struct NamespaceTests : TestBase
{
template <class T>
T variable (const std::string& name)
{
runLua ("result = " + name);
return result <T> ();
}
};
TEST_F (NamespaceTests, Variables)
{
int int_ = -10;
auto any = luabridge::newTable (L);
any ["a"] = 1;
ASSERT_THROW (
luabridge::getGlobalNamespace (L).addProperty ("int", &int_),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &int_)
.addProperty ("any", &any)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any"));
runLua ("ns.int = -20");
ASSERT_EQ (-20, int_);
runLua ("ns.any = {b = 2}");
ASSERT_TRUE (any.isTable ());
ASSERT_TRUE (any ["b"].isNumber ());
ASSERT_EQ (2, any ["b"].cast <int> ());
}
TEST_F (NamespaceTests, ReadOnlyVariables)
{
int int_ = -10;
auto any = luabridge::newTable (L);
any ["a"] = 1;
ASSERT_THROW (
luabridge::getGlobalNamespace (L).addProperty ("int", &int_),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &int_, false)
.addProperty ("any", &any, false)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any"));
ASSERT_THROW (runLua ("ns.int = -20"), std::runtime_error);
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_THROW (runLua ("ns.any = {b = 2}"), std::runtime_error);
ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any"));
}
namespace {
template <class T>
struct Property
{
static T value;
};
template <class T>
T Property <T>::value;
template <class T>
void setProperty (const T& value)
{
Property <T>::value = value;
}
template <class T>
const T& getProperty ()
{
return Property <T>::value;
}
} // namespace
TEST_F (NamespaceTests, Properties)
{
setProperty <int> (-10);
ASSERT_THROW (
luabridge::getGlobalNamespace (L)
.addProperty ("int", &getProperty <int>, &setProperty <int>),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &getProperty <int>, &setProperty <int>)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
runLua ("ns.int = -20");
ASSERT_EQ (-20, getProperty <int> ());
}
TEST_F (NamespaceTests, ReadOnlyProperties)
{
setProperty <int> (-10);
ASSERT_THROW (
luabridge::getGlobalNamespace (L)
.addProperty ("int", &getProperty <int>),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &getProperty <int>)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_THROW (
runLua ("ns.int = -20"),
std::runtime_error);
ASSERT_EQ (-10, getProperty <int> ());
}
namespace {
template <class T>
struct Storage
{
static T value;
};
template <class T>
T Storage <T>::value;
template <class T>
int getDataC (lua_State* L)
{
luabridge::Stack <T>::push (L, Storage <T>::value);
return 1;
}
template <class T>
int setDataC (lua_State* L)
{
Storage <T>::value = luabridge::Stack <T>::get (L, -1);
return 0;
}
} // namespace
TEST_F (NamespaceTests, Properties_ProxyCFunctions)
{
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("value", &getDataC <int>, &setDataC <int>)
.endNamespace ();
Storage <int>::value = 1;
runLua ("ns.value = 2");
ASSERT_EQ (2, Storage <int>::value);
Storage <int>::value = 3;
runLua ("result = ns.value");
ASSERT_TRUE (result ().isNumber ());
ASSERT_EQ (3, result ().cast <int> ());
}
TEST_F (NamespaceTests, Properties_ProxyCFunctions_ReadOnly)
{
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("value", &getDataC <int>)
.endNamespace ();
Storage <int>::value = 1;
ASSERT_THROW (runLua ("ns.value = 2"), std::exception);
ASSERT_EQ (1, Storage <int>::value);
Storage <int>::value = 3;
runLua ("result = ns.value");
ASSERT_TRUE (result ().isNumber ());
ASSERT_EQ (3, result ().cast <int> ());
}
namespace {
struct Class {};
}
TEST_F (NamespaceTests, LuaStackIntegrity)
{
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
{
auto ns2 = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.beginNamespace ("ns2");
ASSERT_EQ (4, lua_gettop (L)); // Stack: ..., global namespace table (gns), namespace table (ns), ns2
ns2.endNamespace (); // Stack: ...
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
{
auto globalNs = luabridge::getGlobalNamespace (L);
ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns
{
auto ns = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace");
// both globalNs an ns are active
ASSERT_EQ (4, lua_gettop (L)); // Stack: ..., gns, gns, ns
}
ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns
{
auto ns = globalNs
.beginNamespace ("namespace");
// globalNs became inactive
ASSERT_EQ (3, lua_gettop (L)); // Stack: ..., gns, ns
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
ASSERT_THROW (globalNs.beginNamespace ("namespace"), std::exception);
ASSERT_THROW (globalNs.beginClass <Class> ("Class"), std::exception);
}
{
auto globalNs = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.endNamespace ();
// globalNs is active
ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns
}
ASSERT_EQ (1, lua_gettop (L)); // StacK: ...
{
auto cls = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.beginClass <Class> ("Class");
ASSERT_EQ (6, lua_gettop (L)); // Stack: ..., gns, ns, const table, class table, static table
{
auto ns = cls.endClass ();
ASSERT_EQ (3, lua_gettop (L)); // Stack: ..., gns, ns
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
}
ASSERT_EQ (1, lua_gettop (L)); // StacK: ...
// Test class continuation
{
auto cls = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.beginClass <Class> ("Class");
ASSERT_EQ (6, lua_gettop (L)); // Stack: ..., gns, ns, const table, class table, static table
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
}
#ifdef _M_IX86 // Windows 32bit only
namespace {
int __stdcall StdCall (int i)
{
return i + 10;
}
} // namespace
TEST_F (NamespaceTests, StdCallFunctions)
{
luabridge::getGlobalNamespace (L)
.addFunction ("StdCall", &StdCall);
runLua ("result = StdCall (2)");
ASSERT_TRUE (result ().isNumber ());
ASSERT_EQ (12, result <int> ());
}
#endif // _M_IX86
| 22.817308
| 105
| 0.617643
|
GlebShikovec
|
3216a0912083e09e1e4d9a060d8eb8d6739fa22f
| 5,810
|
cc
|
C++
|
cartographer/mapping_2d/scan_matching/ceres_scan_matcher.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | 2
|
2020-02-25T05:52:57.000Z
|
2021-03-18T08:28:38.000Z
|
cartographer/mapping_2d/scan_matching/ceres_scan_matcher.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | null | null | null |
cartographer/mapping_2d/scan_matching/ceres_scan_matcher.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2016 The Cartographer 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 "../mapping_2d/scan_matching/ceres_scan_matcher.h"
#include <utility>
#include <vector>
#include "eigen3/Eigen/Core"
#include "../common/ceres_solver_options.h"
#include "../common/lua_parameter_dictionary.h"
#include "../kalman_filter/pose_tracker.h"
#include "../mapping_2d/probability_grid.h"
#include "../mapping_2d/scan_matching/occupied_space_cost_functor.h"
#include "../mapping_2d/scan_matching/rotation_delta_cost_functor.h"
#include "../mapping_2d/scan_matching/translation_delta_cost_functor.h"
#include "../transform/transform.h"
#include "ceres/ceres.h"
#include "glog/logging.h"
/*
* 用优化的方式进行scan-match。也就是说这里是用梯度下降的方式来进行scan-match
* 因此这里的作用实际上和gmapping的hill-climb方法是差不多的。
* 这种局部优化的方法很容易陷入到局部极小值当中。因此这个方法能正常工作的前提是初始值离全局最优值比较近。
* 因此这个方法一般是用作其他方法的优化。
* 比如在cartographer中 在调用这个方法之前,首先会用CSM方法来进行搜索出来一个初值,然后再用这个优化的方法来进行优化
*/
namespace cartographer {
namespace mapping_2d {
namespace scan_matching {
proto::CeresScanMatcherOptions CreateCeresScanMatcherOptions(
common::LuaParameterDictionary* const parameter_dictionary) {
proto::CeresScanMatcherOptions options;
options.set_occupied_space_cost_functor_weight(
parameter_dictionary->GetDouble("occupied_space_cost_functor_weight"));
options.set_previous_pose_translation_delta_cost_functor_weight(
parameter_dictionary->GetDouble(
"previous_pose_translation_delta_cost_functor_weight"));
options.set_initial_pose_estimate_rotation_delta_cost_functor_weight(
parameter_dictionary->GetDouble(
"initial_pose_estimate_rotation_delta_cost_functor_weight"));
options.set_covariance_scale(
parameter_dictionary->GetDouble("covariance_scale"));
*options.mutable_ceres_solver_options() =
common::CreateCeresSolverOptionsProto(
parameter_dictionary->GetDictionary("ceres_solver_options").get());
return options;
}
CeresScanMatcher::CeresScanMatcher(
const proto::CeresScanMatcherOptions& options)
: options_(options),
ceres_solver_options_(
common::CreateCeresSolverOptions(options.ceres_solver_options())) {
ceres_solver_options_.linear_solver_type = ceres::DENSE_QR;
}
CeresScanMatcher::~CeresScanMatcher() {}
void CeresScanMatcher::Match(const transform::Rigid2d& previous_pose,
const transform::Rigid2d& initial_pose_estimate,
const sensor::PointCloud2D& point_cloud,
const ProbabilityGrid& probability_grid,
transform::Rigid2d* const pose_estimate,
kalman_filter::Pose2DCovariance* const covariance,
ceres::Solver::Summary* const summary) const
{
double ceres_pose_estimate[3] = {initial_pose_estimate.translation().x(),
initial_pose_estimate.translation().y(),
initial_pose_estimate.rotation().angle()};
ceres::Problem problem;
CHECK_GT(options_.occupied_space_cost_functor_weight(), 0.);
//构造残差--栅格
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<OccupiedSpaceCostFunctor, ceres::DYNAMIC,
3>(
new OccupiedSpaceCostFunctor(
options_.occupied_space_cost_functor_weight() /
std::sqrt(static_cast<double>(point_cloud.size())),
point_cloud, probability_grid),
point_cloud.size()),
nullptr, ceres_pose_estimate);
CHECK_GT(options_.previous_pose_translation_delta_cost_functor_weight(), 0.);
//构造残差--平移
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<TranslationDeltaCostFunctor, 2, 3>(
new TranslationDeltaCostFunctor(
options_.previous_pose_translation_delta_cost_functor_weight(),
previous_pose)),
nullptr, ceres_pose_estimate);
CHECK_GT(options_.initial_pose_estimate_rotation_delta_cost_functor_weight(),
0.);
//构造残差--旋转
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<RotationDeltaCostFunctor, 1,
3>(new RotationDeltaCostFunctor(
options_.initial_pose_estimate_rotation_delta_cost_functor_weight(),
ceres_pose_estimate[2])),
nullptr, ceres_pose_estimate);
//求解器
ceres::Solve(ceres_solver_options_, &problem, summary);
//优化完毕之后得到的最优位姿
*pose_estimate = transform::Rigid2d(
{ceres_pose_estimate[0], ceres_pose_estimate[1]}, ceres_pose_estimate[2]);
//计算位姿的方差
ceres::Covariance::Options options;
ceres::Covariance covariance_computer(options);
std::vector<std::pair<const double*, const double*>> covariance_blocks;
covariance_blocks.emplace_back(ceres_pose_estimate, ceres_pose_estimate);
CHECK(covariance_computer.Compute(covariance_blocks, &problem));
double ceres_covariance[3 * 3];
covariance_computer.GetCovarianceBlock(ceres_pose_estimate,
ceres_pose_estimate, ceres_covariance);
*covariance = Eigen::Map<kalman_filter::Pose2DCovariance>(ceres_covariance);
*covariance *= options_.covariance_scale();
}
} // namespace scan_matching
} // namespace mapping_2d
} // namespace cartographer
| 40.068966
| 80
| 0.724269
|
linghusmile
|
3217a82afab606ad838675c40d023585b0b4a668
| 10,699
|
hpp
|
C++
|
cpp/src/test/test_position_manipulation.hpp
|
arthur-bit-monnot/fire-rs-saop
|
321e16fceebf44e8e97b482c24f37fbf6dd7d162
|
[
"BSD-2-Clause"
] | 13
|
2018-11-19T15:51:23.000Z
|
2022-01-16T11:24:21.000Z
|
cpp/src/test/test_position_manipulation.hpp
|
fire-rs-laas/fire-rs-saop
|
321e16fceebf44e8e97b482c24f37fbf6dd7d162
|
[
"BSD-2-Clause"
] | 14
|
2017-10-12T16:19:19.000Z
|
2018-03-12T12:07:56.000Z
|
cpp/src/test/test_position_manipulation.hpp
|
fire-rs-laas/fire-rs-saop
|
321e16fceebf44e8e97b482c24f37fbf6dd7d162
|
[
"BSD-2-Clause"
] | 4
|
2018-03-12T12:28:55.000Z
|
2021-07-07T18:32:17.000Z
|
/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#include <iostream>
#include "../ext/dubins.h"
#include "../core/trajectory.hpp"
#include "../core/raster.hpp"
#include "../core/uav.hpp"
#include "../vns/vns_interface.hpp"
#include "../vns/factory.hpp"
#include "../vns/neighborhoods/dubins_optimization.hpp"
#include "../core/fire_data.hpp"
#include <boost/test/included/unit_test.hpp>
namespace SAOP {
namespace Test {
using namespace boost::unit_test;
UAV uav("test", 10., 32. * M_PI / 180, 0.1);
void test_single_point_to_observe() {
// all points ignited at time 0, except ont at time 100
DRaster ignitions(100, 100, 0, 0, 25);
ignitions.set(10, 10, 100);
DRaster elevation(100, 100, 0, 0, 25);
auto fd = make_shared<FireData>(ignitions, elevation);
// only interested in the point ignited at time 100
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 100)};
Plan p(confs, fd, TimeWindow{90, 110});
auto vns = SAOP::build_default();
auto res = vns->search(p, 0, 1);
// BOOST_CHECK(res.final());
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe() {
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = SAOP::build_default();
auto res = vns->search(std::move(p), 0, 1);
// BOOST_CHECK(Plan(res.final()));
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe_with_start_end_positions() {
Waypoint3d start(5, 5, 0, 0);
Waypoint3d end(11, 11, 0, 0);
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(
uav,
start,
end,
10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = SAOP::build_default();
auto res = vns->search(std::move(p), 0, 1);
// BOOST_CHECK(Plan(res.final()));
const auto& traj = res.final().trajectories()[0];
//ASSERT(traj[0] == start);
//ASSERT(traj[traj.size()-1] == end);
BOOST_CHECK(traj.insertion_range_start() == 1);
BOOST_CHECK(traj.insertion_range_end() == traj.size() - 2);
cout << "SUCCESS" << endl;
}
void test_segment_rotation() {
for (size_t i = 0; i < 100; i++) {
Waypoint wp(drand(-100000, 10000), drand(-100000, 100000), drand(-10 * M_PI, 10 * M_PI));
Segment seg(wp, drand(0, 1000));
Segment seg_rotated = uav.rotate_on_visibility_center(seg, drand(-10 * M_PI, 10 * M_PI));
Segment seg_back = uav.rotate_on_visibility_center(seg_rotated, wp.dir);
BOOST_CHECK(seg == seg_back);
}
}
void test_projection_on_firefront() {
// uniform propagation along the y axis
{
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, y);
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 50.5);
BOOST_CHECK(res && res->y == 50);
auto res_back = fd.project_on_fire_front(Cell{79, 1}, 50.5);
BOOST_CHECK(res_back && res_back->y == 50);
}
// uniform propagation along the x axis
{
DRaster ignitions(10, 10, 0, 0, 1);
for (size_t x = 0; x < 10; x++) {
for (size_t y = 0; y < 10; y++) {
ignitions.set(x, y, x);
}
}
DRaster elevation(10, 10, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 5.5);
BOOST_CHECK(res && res->x == 5);
auto res_back = fd.project_on_fire_front(Cell{7, 1}, 5.5);
BOOST_CHECK(res_back && res_back->x == 5);
}
// circular propagation center on (50,50)
{
auto dist = [](size_t x, size_t y) {
return sqrt(pow((double) x - 50., 2.) + pow((double) y - 50., 2.));
};
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, dist(x, y));
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
for (size_t i = 0; i < 100; i++) {
const size_t x = rand(0, 100);
const size_t y = rand(0, 100);
auto res = fd.project_on_fire_front(Cell{x, y}, 25);
BOOST_CHECK(res && abs(dist(res->x, res->y) - 25) < 1.5);
}
}
}
void test_trajectory_as_waypoints() {
Trajectory traj((TrajectoryConfig(uav)));
traj.sampled(2);
}
void test_trajectory_slice() {
TimeWindow tw1 = TimeWindow(10, 300);
TrajectoryConfig config1 = TrajectoryConfig(uav, tw1.start, tw1.end);
Trajectory traj = Trajectory(config1);
traj.append_segment(Segment3d(Waypoint3d(0, 0, 0, 0)));
traj.append_segment(Segment3d(Waypoint3d(100, 100, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(300, 200, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(500, 500, 0, 0)));
Trajectory sliced1 = traj.slice(TimeWindow(tw1.start + 1, tw1.end - 1));
Trajectory sliced2 = traj.slice(TimeWindow(tw1.start + 1, 85));
BOOST_CHECK(sliced1.size() == traj.size() - 1);
BOOST_CHECK(sliced2.size() == traj.size() - 2);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced1.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced2.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(3), sliced1.start_time(2), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(2), sliced2.start_time(1), 0.1);
}
void test_time_window_order() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
BOOST_CHECK(tw1.start == s);
BOOST_CHECK(tw1.end == e);
BOOST_CHECK(tw1.start == tw2.start);
BOOST_CHECK(tw1.end == tw1.end);
}
void test_time_window() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
TimeWindow tw3 = TimeWindow(s - 1, e);
TimeWindow tw4 = TimeWindow(s, e + 1);
BOOST_CHECK(tw1 == tw2);
BOOST_CHECK(tw1 != tw3);
BOOST_CHECK(tw3.contains(tw1));
BOOST_CHECK(tw3.contains(tw1.center()));
BOOST_CHECK(tw3.intersects(tw4));
BOOST_CHECK(tw3.union_with(tw1) == tw3);
BOOST_CHECK(tw4.intersection_with(tw3) == tw1);
auto empty_intersect = TimeWindow(s - 1, s).intersection_with(TimeWindow(e, e + 1));
BOOST_CHECK(empty_intersect.is_empty());
}
test_suite* position_manipulation_test_suite() {
test_suite* ts2 = BOOST_TEST_SUITE("position_manipulation_tests");
srand(time(0));
ts2->add(BOOST_TEST_CASE(&test_trajectory_slice));
ts2->add(BOOST_TEST_CASE(&test_time_window_order));
ts2->add(BOOST_TEST_CASE(&test_time_window));
ts2->add(BOOST_TEST_CASE(&test_trajectory_as_waypoints));
ts2->add(BOOST_TEST_CASE(&test_segment_rotation));
ts2->add(BOOST_TEST_CASE(&test_single_point_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe_with_start_end_positions));
ts2->add(BOOST_TEST_CASE(&test_projection_on_firefront));
return ts2;
}
}
}
| 38.210714
| 105
| 0.549397
|
arthur-bit-monnot
|
32198d49dc2fa06def4ac0e909270088f01cb6bf
| 26,482
|
cpp
|
C++
|
himan-plugins/source/geotiff.cpp
|
fmidev/himan
|
481e0cf9a3d15c900e07d08cf7e22de1c50a6823
|
[
"MIT"
] | 18
|
2017-04-20T18:51:41.000Z
|
2022-03-23T21:12:49.000Z
|
himan-plugins/source/geotiff.cpp
|
fmidev/himan
|
481e0cf9a3d15c900e07d08cf7e22de1c50a6823
|
[
"MIT"
] | 5
|
2018-07-05T02:15:56.000Z
|
2021-06-01T09:36:51.000Z
|
himan-plugins/source/geotiff.cpp
|
fmidev/himan
|
481e0cf9a3d15c900e07d08cf7e22de1c50a6823
|
[
"MIT"
] | 2
|
2020-02-18T06:32:53.000Z
|
2021-03-29T15:17:09.000Z
|
#include "geotiff.h"
#include "cpl_conv.h" // for CPLMalloc()
#include "file_accessor.h"
#include "gdal_frmts.h"
#include "grid.h"
#include "lambert_conformal_grid.h"
#include "lambert_equal_area_grid.h"
#include "latitude_longitude_grid.h"
#include "logger.h"
#include "plugin_factory.h"
#include "producer.h"
#include "reduced_gaussian_grid.h"
#include "s3.h"
#include "stereographic_grid.h"
#include "timer.h"
#include "transverse_mercator_grid.h"
#include "util.h"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <ogr_spatialref.h>
#include <thread>
#include "plugin_factory.h"
#include "radon.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include "gdal_priv.h"
#pragma GCC diagnostic pop
using namespace himan;
using namespace himan::plugin;
struct GDALDatasetCloser
{
void operator()(GDALDataset* ds) const
{
GDALClose(ds);
}
};
typedef std::unique_ptr<GDALDataset, GDALDatasetCloser> GDALDatasetPtr;
void CheckGDALError(OGRErr errarg, const char* file, const int line);
#define GDAL_CHECK(errarg) CheckGDALError(errarg, __FILE__, __LINE__)
inline void CheckGDALError(OGRErr errarg, const char* file, const int line)
{
if (errarg != OGRERR_NONE)
{
std::cerr << "Error at " << file << "(" << line << "): " << CPLGetLastErrorMsg() << std::endl;
himan::Abort();
}
}
template <typename T>
GDALDataType TypeToGDALType();
template <>
GDALDataType TypeToGDALType<unsigned char>()
{
return GDT_Byte;
}
template <>
GDALDataType TypeToGDALType<short>()
{
return GDT_Int16;
}
template <>
GDALDataType TypeToGDALType<float>()
{
return GDT_Float32;
}
template <>
GDALDataType TypeToGDALType<double>()
{
return GDT_Float64;
}
template <typename T>
T ConvertTo(const std::string& str)
{
std::istringstream ss(str);
T num;
ss >> num;
return num;
}
static std::once_flag oflag;
void CreateDirectory(const std::string& filename)
{
namespace fs = boost::filesystem;
fs::path pathname(filename);
if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
{
fs::create_directories(pathname.parent_path());
}
}
geotiff::geotiff()
{
call_once(oflag, [&]() {
GDALRegister_GTiff();
GDALRegister_COG();
// Check environment for AWS variables
// GDAL requires Himan uses
// * AWS_S3_ENDPOINT S3_HOSTNAME
// * AWS_ACCESS_KEY_ID S3_ACCESS_KEY_ID
// * AWS_SECRET_ACCESS_KEY S3_SECRET_ACCESS_KEY
// * AWS_SESSION_TOKEN S3_SESSION_TOKEN
//
// if latter is found, copy it to former
const std::vector<std::pair<std::string, std::string>> keys{{"S3_HOSTNAME", "AWS_S3_ENDPOINT"},
{"S3_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID"},
{"S3_SECRET_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY"},
{"S3_SESSION_TOKEN", "AWS_SESSION_TOKEN"}};
for (const auto& key : keys)
{
try
{
const std::string val = util::GetEnv(key.first);
setenv(key.second.c_str(), val.c_str(), 0);
}
catch (...)
{
}
}
});
itsLogger = logger("geotiff");
}
std::pair<HPWriteStatus, file_information> geotiff::ToFile(info<double>& anInfo)
{
return ToFile<double>(anInfo);
}
void WriteAreaAndGrid(GDALDataset& ds, const himan::regular_grid& g, const producer& prod, const configuration& conf)
{
const point fp = g.Projected(g.TopLeft());
double adfGeoTransform[6] = {fp.X(), g.Di(), 0, fp.Y(), 0, -1 * g.Dj()};
GDAL_CHECK(ds.SetGeoTransform(adfGeoTransform));
OGRSpatialReference sp;
GDAL_CHECK(sp.importFromProj4(g.Proj4String().c_str()));
// If earth shape is WGS84, set datum also to WGS84, since AFAIK
// no other datum uses it as ellipsoid.
if (g.EarthShape().Name() == "WGS84")
{
sp.SetWellKnownGeogCS("WGS84");
}
const std::string geom = conf.TargetGeomName().empty() ? prod.Name() : conf.TargetGeomName();
GDAL_CHECK(sp.SetProjCS(geom.c_str()));
GDAL_CHECK(ds.SetSpatialRef(&sp));
}
template <typename T>
void WriteData(GDALDataset& ds, const info<T>& anInfo, int bandNo)
{
const int ni = static_cast<int>(anInfo.Data().SizeX());
const int nj = static_cast<int>(anInfo.Data().SizeY());
const GDALDataType dtype = TypeToGDALType<T>();
GDALRasterBand* poBand = ds.GetRasterBand(bandNo);
if (bandNo == 1)
{
// Only for first band, because otherwise:
// band 2: Setting nodata to nan on band 2, but band 1 has nodata at nan. The TIFFTAG_GDAL_NODATA only support
// one value per dataset. This value of nan will be used for all bands on re-opening
GDAL_CHECK(poBand->SetNoDataValue(anInfo.Data().MissingValue()));
}
matrix<T> values = anInfo.Data();
if (dynamic_cast<regular_grid*>(anInfo.Grid().get())->ScanningMode() != kTopLeft)
{
util::Flip<T>(values);
}
if (poBand->RasterIO(GF_Write, 0, 0, ni, nj, values.ValuesAsPOD(), ni, nj, dtype, 0, 0) != OGRERR_NONE)
{
logger logr("geotiff");
logr.Error("File write failed");
himan::Abort();
}
}
void WriteBandMetadata(GDALRasterBand* b, const forecast_type& ftype, const forecast_time& ftime, const level& lvl,
const param& par)
{
GDAL_CHECK(b->SetMetadataItem("forecast_type", static_cast<std::string>(ftype).c_str(), nullptr));
GDAL_CHECK(
b->SetMetadataItem("origin_time", ftime.OriginDateTime().String("%Y-%m-%dT%H:%M:%S+00:00").c_str(), nullptr));
GDAL_CHECK(
b->SetMetadataItem("valid_time", ftime.ValidDateTime().String("%Y-%m-%dT%H:%M:%S+00:00").c_str(), nullptr));
GDAL_CHECK(b->SetMetadataItem("step", ftime.Step().String("%02h:%02M:%02S").c_str(), nullptr));
GDAL_CHECK(b->SetMetadataItem("level", static_cast<std::string>(lvl).c_str(), nullptr));
GDAL_CHECK(b->SetMetadataItem("param_name", par.Name().c_str(), nullptr));
if (par.Aggregation().Type() != kUnknownAggregationType)
{
GDAL_CHECK(b->SetMetadataItem("aggregation", static_cast<std::string>(par.Aggregation()).c_str(), nullptr));
}
if (par.ProcessingType().Type() != kUnknownProcessingType)
{
GDAL_CHECK(
b->SetMetadataItem("processing_type", static_cast<std::string>(par.ProcessingType()).c_str(), nullptr));
}
}
template <typename T>
std::pair<HPWriteStatus, file_information> geotiff::ToFile(info<T>& anInfo)
{
if (anInfo.Grid()->Class() == kIrregularGrid && anInfo.Grid()->Type() != kReducedGaussian)
{
itsLogger.Error(fmt::format("Unable to write irregular grid of type {} to geotiff",
HPGridTypeToString.at(anInfo.Grid()->Type())));
throw kInvalidWriteOptions;
}
if (itsWriteOptions.configuration->WriteStorageType() == kS3ObjectStorageSystem ||
itsWriteOptions.configuration->WriteMode() != kSingleGridToAFile)
{
return std::make_pair(HPWriteStatus::kPending, file_information());
}
GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
file_information finfo;
finfo.file_location = util::MakeFileName(anInfo, *itsWriteOptions.configuration);
finfo.file_type = kGeoTIFF;
finfo.storage_type = itsWriteOptions.configuration->WriteStorageType();
// We use Create() method as there is nothing to copy from
// (CreateCopy() being the alternative)
const regular_grid* g = dynamic_cast<regular_grid*>(anInfo.Grid().get());
// Enable compression
char** opts = NULL;
opts = CSLSetNameValue(opts, "COMPRESS", "DEFLATE");
const GDALDataType dtype = TypeToGDALType<T>();
CreateDirectory(finfo.file_location);
auto ds = GDALDatasetPtr(driver->Create(finfo.file_location.c_str(), static_cast<int>(anInfo.Data().SizeX()),
static_cast<int>(anInfo.Data().SizeY()), 1, dtype, opts));
WriteAreaAndGrid(*ds, *g, anInfo.Producer(), *itsWriteOptions.configuration);
GDAL_CHECK(ds->SetMetadataItem("producer_id", fmt::format("{}", anInfo.Producer().Id()).c_str(), nullptr));
WriteBandMetadata(ds->GetRasterBand(1), anInfo.ForecastType(), anInfo.Time(), anInfo.Level(), anInfo.Param());
WriteData(*ds, anInfo, 1);
itsLogger.Info(fmt::format("Wrote file '{}'", finfo.file_location));
return std::make_pair(HPWriteStatus::kFinished, finfo);
}
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<double>(info<double>&);
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<float>(info<float>&);
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<short>(info<short>&);
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<unsigned char>(info<unsigned char>&);
template <typename T>
std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile(const std::vector<info<T>>& infos)
{
// No "pending" checking here
GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
std::map<std::string, std::vector<size_t>> list;
for (size_t i = 0; i < infos.size(); i++)
{
const auto& info = infos[i];
const std::string fname = util::MakeFileName<T>(info, *itsWriteOptions.configuration);
auto& elem = list[fname];
elem.push_back(i);
}
std::vector<std::pair<HPWriteStatus, file_information>> ret(infos.size());
// If writing to s3, first write all data to a memory location
// where it can be picked up. Use gdal's /vsimem feature for this.
const std::string vrt =
(itsWriteOptions.configuration->WriteStorageType() == kS3ObjectStorageSystem) ? "/vsimem/" : "";
for (const auto& m : list)
{
const auto& first = infos[m.second[0]];
file_information finfo;
finfo.file_location = m.first;
finfo.file_type = kGeoTIFF;
finfo.storage_type = itsWriteOptions.configuration->WriteStorageType();
const regular_grid* g = dynamic_cast<regular_grid*>(first.Grid().get());
// Enable compression
char** opts = NULL;
opts = CSLSetNameValue(opts, "COMPRESS", "DEFLATE");
const GDALDataType dtype = TypeToGDALType<T>();
if (itsWriteOptions.configuration->WriteStorageType() != kS3ObjectStorageSystem)
{
CreateDirectory(finfo.file_location);
}
auto ds = GDALDatasetPtr(driver->Create(
fmt::format("{}{}", vrt, finfo.file_location).c_str(), static_cast<int>(first.Data().SizeX()),
static_cast<int>(first.Data().SizeY()), static_cast<int>(m.second.size()), dtype, opts));
if (!ds)
{
himan::Abort();
}
GDAL_CHECK(ds->SetMetadataItem("producer_id", fmt::format("{}", first.Producer().Id()).c_str(), nullptr));
WriteAreaAndGrid(*ds, *g, first.Producer(), *itsWriteOptions.configuration);
int j = 1;
for (const size_t i : m.second)
{
WriteBandMetadata(ds->GetRasterBand(j), infos[i].ForecastType(), infos[i].Time(), infos[i].Level(),
infos[i].Param());
WriteData(*ds, infos[i], j);
finfo.message_no = j++;
ret[i] = std::make_pair(HPWriteStatus::kFinished, finfo);
}
if (itsWriteOptions.configuration->WriteStorageType() == kS3ObjectStorageSystem)
{
ds->FlushCache();
// Earlier data was written to memory, now get a pointer to that memory block
// and pass it to himan::s3
VSILFILE* inmem = VSIFOpenL(fmt::format("{}/{}", vrt, finfo.file_location).c_str(), "rb");
himan::buffer buff;
// Get file size
VSIFSeekL(inmem, 0, SEEK_END);
buff.length = VSIFTellL(inmem);
VSIFSeekL(inmem, 0, SEEK_SET);
itsLogger.Trace(fmt::format("In-mem file size is {} bytes", buff.length));
buff.data = static_cast<unsigned char*>(malloc(buff.length));
// Read contents
VSIFReadL(buff.data, buff.length, 1, inmem);
s3::WriteObject(finfo.file_location, buff);
itsLogger.Info(fmt::format("Wrote file 's3://{}'", finfo.file_location));
}
else
{
itsLogger.Info(fmt::format("Wrote file '{}'", finfo.file_location));
}
}
return ret;
}
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<double>(
const std::vector<info<double>>&);
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<float>(
const std::vector<info<float>>&);
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<short>(
const std::vector<info<short>>&);
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<unsigned char>(
const std::vector<info<unsigned char>>&);
std::unique_ptr<grid> ReadAreaAndGrid(GDALDataset* ds)
{
logger log("geotiff");
const int ni = ds->GetRasterXSize(), nj = ds->GetRasterYSize();
double adfGeoTransform[6];
if (ds->GetGeoTransform(adfGeoTransform) != CE_None)
{
log.Error("File does not contain geo transformation coefficients");
throw kFileMetaDataNotFound;
}
const double di = adfGeoTransform[1];
const double dj = fabs(adfGeoTransform[5]);
const point fp(adfGeoTransform[0], adfGeoTransform[3]);
const HPScanningMode sm = (adfGeoTransform[5] < 0) ? kTopLeft : kBottomLeft;
ASSERT(di > 0);
std::string proj = ds->GetProjectionRef();
if (proj.empty())
{
log.Fatal("File does not contain spatial metadata");
throw kFileMetaDataNotFound;
}
OGRSpatialReference spRef(proj.c_str());
const char* projptr = spRef.GetAttrValue("PROJECTION");
if (projptr != nullptr)
{
const std::string projection = spRef.GetAttrValue("PROJECTION");
if (projection == SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA)
{
return std::unique_ptr<lambert_equal_area_grid>(new lambert_equal_area_grid(
sm, fp, ni, nj, di, dj, std::unique_ptr<OGRSpatialReference>(spRef.Clone()), true));
}
else if (projection == SRS_PT_TRANSVERSE_MERCATOR)
{
return std::unique_ptr<transverse_mercator_grid>(new transverse_mercator_grid(
sm, fp, ni, nj, di, dj, std::unique_ptr<OGRSpatialReference>(spRef.Clone()), true));
}
else if (projection == SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP || projection == SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP)
{
return std::unique_ptr<lambert_conformal_grid>(new lambert_conformal_grid(
sm, fp, ni, nj, di, dj, std::unique_ptr<OGRSpatialReference>(spRef.Clone()), true));
}
log.Error(fmt::format("Unsupported projection: {}", projection));
}
else if (spRef.IsGeographic())
{
// No projection -- latlon with some datum
// spRef.GetAttrValue("DATUM|SPHEROID|AUTHORITY")
OGRErr erra = 0, errb = 0;
const double A = spRef.GetSemiMajor(&erra);
const double B = spRef.GetSemiMinor(&errb);
earth_shape<double> es;
if (erra != OGRERR_NONE || errb != OGRERR_NONE)
{
log.Error("Unable to extract datum information from file");
}
else
{
es = earth_shape<double>(A, B);
}
return std::unique_ptr<latitude_longitude_grid>(new latitude_longitude_grid(sm, fp, ni, nj, di, dj, es));
}
throw kFileMetaDataNotFound;
}
param ReadParam(const std::map<std::string, std::string>& meta, const producer& prod, const param& par)
{
logger logr("geotiff");
std::string param_value;
for (const auto& m : meta)
{
if (m.first == "param_name")
{
param_value = m.second;
break;
}
}
if (param_value.empty())
{
return par;
}
auto r = GET_PLUGIN(radon);
auto parameter = r->RadonDB().GetParameterFromGeoTIFF(prod.Id(), param_value);
if (parameter.empty() || parameter["name"].empty())
{
logr.Trace(
fmt::format("Parameter information matching '{}' not found from table 'param_geotiff'", param_value));
return par;
}
param p(parameter["name"]);
p.Id(std::stoi(parameter["id"]));
p.InterpolationMethod(par.InterpolationMethod());
return p;
}
level ReadLevel(const std::map<std::string, std::string>& meta, const level& lvl)
{
HPLevelType type = HPLevelType::kUnknownLevel;
double value = kHPMissingValue, value2 = kHPMissingValue;
for (const auto& m : meta)
{
if (m.first == "level")
{
const auto tokens = util::Split(m.second, "/");
type = static_cast<HPLevelType>(stoi(tokens[0]));
value = stod(tokens[1]);
if (tokens.size() == 3)
{
value2 = stod(tokens[2]);
}
break;
}
}
if (type != kUnknownLevel)
{
return level(type, value, value2);
}
return lvl;
}
forecast_type ReadForecastType(const std::map<std::string, std::string>& meta, const forecast_type& ftype)
{
HPForecastType type = HPForecastType::kUnknownType;
double value = kHPMissingValue;
for (const auto& m : meta)
{
if (m.first == "forecast_type")
{
const auto tokens = util::Split(m.second, "/");
type = static_cast<HPForecastType>(stoi(tokens[1]));
value = stod(tokens[1]);
break;
}
}
if (type != kUnknownType)
{
return forecast_type(type, value);
}
return ftype;
}
void SQLTimeMaskToCTimeMask(std::string& sqlTimeMask)
{
boost::replace_all(sqlTimeMask, "YYYY", "%Y");
boost::replace_all(sqlTimeMask, "MM", "%m");
boost::replace_all(sqlTimeMask, "DD", "%d");
boost::replace_all(sqlTimeMask, "hh", "%H");
boost::replace_all(sqlTimeMask, "mm", "%M");
}
forecast_time ReadTime(const std::map<std::string, std::string>& meta, const forecast_time& ftime)
{
raw_time origintime = ftime.OriginDateTime();
raw_time validtime = ftime.ValidDateTime();
std::string origintimestr, validtimestr, mask;
for (const auto& m : meta)
{
if (m.first == "analysis_time")
{
origintimestr = m.second;
}
else if (m.first == "valid_time")
{
validtimestr = m.second;
}
else if (m.first == "time_mask")
{
mask = m.second;
}
}
if (mask.find("YYYY") != std::string::npos)
{
SQLTimeMaskToCTimeMask(mask);
}
if (!origintimestr.empty() && !mask.empty())
{
origintime = raw_time(origintimestr, mask);
}
if (!validtimestr.empty() && !mask.empty())
{
validtime = raw_time(validtimestr, mask);
}
return forecast_time(origintime, validtime);
}
std::map<std::string, std::string> ParseMetadata(char** mdata, const producer& prod)
{
std::map<std::string, std::string> ret;
if (mdata == nullptr)
{
return ret;
}
// First check keys with Himan-known 'standard' names
const std::vector<std::string> standardNames{"forecast_type", "level"};
for (const auto& keyName : standardNames)
{
const char* m = CSLFetchNameValue(mdata, keyName.c_str());
if (m != nullptr)
{
ret[keyName] = std::string(m);
}
}
std::string query =
fmt::format("SELECT attribute, key, mask FROM geotiff_metadata WHERE producer_id = {}", prod.Id());
auto r = GET_PLUGIN(radon);
r->RadonDB().Query(query);
logger log("geotiff");
while (true)
{
const auto row = r->RadonDB().FetchRow();
if (row.empty())
{
break;
}
const auto attribute = row[0];
const auto keyName = row[1];
const auto keyMask = row[2];
std::string metadata;
if (keyName.empty() == false)
{
// metadata consists of key=value pairs
const char* m = CSLFetchNameValue(mdata, keyName.c_str());
if (m == nullptr)
{
log.Trace("Did not find expected key '" + keyName + "' from metadata");
continue;
}
metadata = std::string(m);
}
else if (mdata != nullptr)
{
// no defined keys for metadata elements
// in database this means that 'key' column is empty string
metadata = std::string(*mdata);
}
else
{
continue;
}
// Try to extract information from free-form text fields
// attribute: a metadata attribute name that Himan understands, like 'analysis_time'
// keyName: name of the metadata element in geotiff file
// keyMask: optional mask for the value of the key, if only specific value needs
// to be extraced, regular expressions are used
if (keyMask.empty())
{
ret[attribute] = metadata;
}
else
{
const boost::regex re(keyMask);
boost::smatch what;
if (boost::regex_search(metadata, what, re) == false || what.size() == 0)
{
log.Warning(fmt::format("Regex did not match for attribute {}", attribute));
log.Warning(fmt::format("Regex: '{}' Metadata: '{}'", keyMask, metadata));
}
if (what.size() != 2)
{
log.Fatal(fmt::format("Regex matched too many times: {}", what.size() - 1));
himan::Abort();
}
log.Debug(fmt::format("Regex match for {}: {}", attribute, std::string(what[1])));
ret[attribute] = what[1];
}
}
return ret;
}
template <typename T>
void ReadData(GDALRasterBand* poBand, matrix<T>& mat, const std::map<std::string, std::string>& meta)
{
if (meta.find("missing_value") != meta.end())
{
mat.MissingValue(ConvertTo<T>(meta.at("missing_value")));
}
else
{
mat.MissingValue(static_cast<T>(poBand->GetNoDataValue(nullptr)));
}
ASSERT(poBand->GetXSize() == static_cast<int>(mat.SizeX()));
ASSERT(poBand->GetYSize() == static_cast<int>(mat.SizeY()));
int nXSize = poBand->GetXSize();
int nYSize = poBand->GetYSize();
if (poBand->RasterIO(GF_Read, 0, 0, nXSize, nYSize, mat.ValuesAsPOD(), nXSize, nYSize, TypeToGDALType<T>(), 0, 0) !=
CE_None)
{
throw std::runtime_error("Read failed");
}
const T offset = static_cast<T>(poBand->GetOffset(nullptr));
const T scale = static_cast<T>(poBand->GetScale(nullptr));
// Change missingvalue to our own
mat.MissingValue(MissingValue<T>());
// Apply scale and base
if (offset != 0 || scale != 1)
{
auto& data = mat.Values();
for_each(data.begin(), data.end(), [=](T& val) { val = static_cast<T>(val * scale + offset); });
}
}
std::vector<std::shared_ptr<info<double>>> geotiff::FromFile(const file_information& theInputFile,
const search_options& options, bool validate,
bool readData) const
{
return FromFile<double>(theInputFile, options, validate, readData);
}
template <typename T>
std::vector<std::shared_ptr<info<T>>> geotiff::FromFile(const file_information& theInputFile,
const search_options& options, bool validate,
bool readData) const
{
std::vector<std::shared_ptr<himan::info<T>>> infos;
auto ParseFileName = [](const file_information& finfo) {
std::string ret = finfo.file_location;
if (finfo.storage_type == kS3ObjectStorageSystem)
{
const auto pos = ret.find("s3://");
if (pos != std::string::npos)
{
ret = ret.erase(pos, 5);
}
ret = fmt::format("/vsis3_streaming/{}", ret);
}
return ret;
};
auto ds =
GDALDatasetPtr(reinterpret_cast<GDALDataset*>(GDALOpen(ParseFileName(theInputFile).c_str(), GA_ReadOnly)));
if (ds == nullptr)
{
itsLogger.Error("Failed to open dataset from " + theInputFile.file_location);
return infos;
}
auto meta = ParseMetadata(ds->GetMetadata(), options.prod); // Get full dataset metadata
if (meta.size() == 0)
{
itsLogger.Trace(
fmt::format("No elements recognized from global metadata from '{}'", theInputFile.file_location));
}
auto area = ReadAreaAndGrid(ds.get());
if (area == nullptr)
{
return infos;
}
// "first guess" metadata from file metadata
auto par = ReadParam(meta, options.prod, options.param);
auto lvl = ReadLevel(meta, options.level);
auto ftype = ReadForecastType(meta, options.ftype);
auto ftime = ReadTime(meta, options.time);
auto MakeInfoFromGeoTIFFBand = [&](GDALRasterBand* poBand) -> std::shared_ptr<info<T>> {
// Read possible metadata from band
auto bmeta = ParseMetadata(poBand->GetMetadata(), options.prod);
auto bpar = ReadParam(bmeta, options.prod, par);
auto blvl = ReadLevel(bmeta, lvl);
auto bftype = ReadForecastType(bmeta, ftype);
auto bftime = ReadTime(bmeta, ftime);
if (bpar == param() || blvl == level() || bftype == forecast_type() || bftime == forecast_time())
{
itsLogger.Warning("Failed to gather all required metadata");
itsLogger.Warning("Param: " + bpar.Name());
itsLogger.Warning("Level: " + static_cast<std::string>(blvl));
itsLogger.Warning("Time: " + bftime.OriginDateTime().String() + " step: " + bftime.Step().String("%H:%M"));
itsLogger.Warning("Forecast type: " + static_cast<std::string>(bftype));
throw kFileDataNotFound;
}
if (validate && options.time != bftime)
{
itsLogger.Warning("Time does not match: " + options.time.OriginDateTime().String() + " step " +
options.time.Step().String("%02H:%02M:%02S") + " vs " + bftime.OriginDateTime().String() +
" step " + bftime.Step().String("%02H:%02M:%02S"));
}
if (validate && options.level != blvl)
{
itsLogger.Warning("Level does not match");
}
if (validate && options.ftype != bftype)
{
itsLogger.Warning("Forecast type does not match");
}
if (validate && options.param != bpar)
{
itsLogger.Warning("param does not match: " + options.param.Name() + " vs " + bpar.Name());
}
auto anInfo = std::make_shared<info<T>>(bftype, bftime, blvl, bpar);
auto b = std::make_shared<base<T>>();
b->grid = std::shared_ptr<grid>(area->Clone());
anInfo->Create(b, true);
anInfo->Producer(options.prod);
if (readData)
{
ReadData<T>(poBand, anInfo->Data(), meta);
}
return anInfo;
};
if (theInputFile.message_no == boost::none)
{
for (int bandNo = 1; bandNo <= ds->GetRasterCount(); bandNo++)
{
itsLogger.Info("Read from file '" + theInputFile.file_location + "' band# " + std::to_string(bandNo));
GDALRasterBand* poBand = ds->GetRasterBand(bandNo);
try
{
infos.push_back(MakeInfoFromGeoTIFFBand(poBand));
}
catch (const HPExceptionType& e)
{
}
}
}
else
{
itsLogger.Info("Read from file '" + theInputFile.file_location + "' band# " +
std::to_string(theInputFile.message_no.get()));
GDALRasterBand* poBand = ds->GetRasterBand(static_cast<int>(theInputFile.message_no.get()));
try
{
infos.push_back(MakeInfoFromGeoTIFFBand(poBand));
}
catch (...)
{
}
}
return infos;
}
template std::vector<std::shared_ptr<info<double>>> geotiff::FromFile<double>(const file_information&,
const search_options&, bool, bool) const;
template std::vector<std::shared_ptr<info<float>>> geotiff::FromFile<float>(const file_information&,
const search_options&, bool, bool) const;
template std::vector<std::shared_ptr<info<short>>> geotiff::FromFile<short>(const file_information&,
const search_options&, bool, bool) const;
template std::vector<std::shared_ptr<info<unsigned char>>> geotiff::FromFile<unsigned char>(const file_information&,
const search_options&, bool,
bool) const;
| 29.489978
| 120
| 0.663998
|
fmidev
|
321a1cd6e50b7fda1c89b6fe67bea9189add0552
| 24,431
|
cpp
|
C++
|
be/src/olap/base_expansion_handler.cpp
|
DiffBlue-benchmarks/baidu-palo
|
27e021b0a9616a795a650026ed8c59aea7d09841
|
[
"Apache-2.0"
] | 1
|
2021-07-14T07:30:48.000Z
|
2021-07-14T07:30:48.000Z
|
be/src/olap/base_expansion_handler.cpp
|
DiffBlue-benchmarks/baidu-palo
|
27e021b0a9616a795a650026ed8c59aea7d09841
|
[
"Apache-2.0"
] | null | null | null |
be/src/olap/base_expansion_handler.cpp
|
DiffBlue-benchmarks/baidu-palo
|
27e021b0a9616a795a650026ed8c59aea7d09841
|
[
"Apache-2.0"
] | 1
|
2018-06-29T06:40:03.000Z
|
2018-06-29T06:40:03.000Z
|
// Copyright (c) 2017, Baidu.com, 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.
#include "olap/base_expansion_handler.h"
#include <algorithm>
#include <list>
#include <map>
#include <string>
#include <vector>
#include "olap/delete_handler.h"
#include "olap/merger.h"
#include "olap/olap_data.h"
#include "olap/olap_engine.h"
#include "olap/olap_header.h"
#include "olap/olap_index.h"
#include "olap/olap_table.h"
#include "olap/utils.h"
#include "util/palo_metrics.h"
using std::list;
using std::map;
using std::string;
using std::vector;
namespace palo {
OLAPStatus BaseExpansionHandler::init(SmartOLAPTable table, bool is_manual_trigger) {
// 表在首次查询或PUSH等操作时,会被加载到内存
// 如果表没有被加载,表明该表上目前没有任何操作,所以不进行BE操作
if (!table->is_loaded()) {
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
OLAP_LOG_TRACE("init base expansion handler. [table=%s]", table->full_name().c_str());
_table = table;
// 1. 尝试取得base expansion的锁
if (!_try_base_expansion_lock()) {
OLAP_LOG_WARNING("another base expansion is running. [table=%s]",
table->full_name().c_str());
return OLAP_ERR_BE_TRY_BE_LOCK_ERROR;
}
// 2. 检查是否满足base expansion触发策略
OLAP_LOG_TRACE("check whether satisfy base expansion policy.");
bool is_policy_satisfied = false;
vector<Version> candidate_versions;
is_policy_satisfied = _check_whether_satisfy_policy(is_manual_trigger, &candidate_versions);
// 2.1 如果不满足触发策略,则直接释放base expansion锁, 返回错误码
if (!is_policy_satisfied) {
_release_base_expansion_lock();
return OLAP_ERR_BE_NO_SUITABLE_VERSION;
}
// 2.2 如果满足触发策略,触发base expansion
// 不释放base expansion锁, 在run()完成之后再释放
if (!_validate_need_merged_versions(candidate_versions)) {
OLAP_LOG_FATAL("error! invalid need merged versions");
_release_base_expansion_lock();
return OLAP_ERR_BE_INVALID_NEED_MERGED_VERSIONS;
}
_need_merged_versions = candidate_versions;
return OLAP_SUCCESS;
}
OLAPStatus BaseExpansionHandler::run() {
OLAP_LOG_INFO("start base expansion. [table=%s; old_base_version=%d; new_base_version=%d]",
_table->full_name().c_str(),
_old_base_version.second,
_new_base_version.second);
OLAPStatus res = OLAP_SUCCESS;
OlapStopWatch stage_watch;
_table->set_base_expansion_status(BASE_EXPANSION_RUNNING, _new_base_version.second);
// 1. 计算新base的version hash
VersionHash new_base_version_hash;
res = _table->compute_all_versions_hash(_need_merged_versions, &new_base_version_hash);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to calculate new base version hash.[table=%s; new_base_version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return res;
}
OLAP_LOG_TRACE("new_base_version_hash", "%ld", new_base_version_hash);
// 2. 获取生成新base需要的data sources
vector<IData*> base_data_sources;
_table->acquire_data_sources_by_versions(_need_merged_versions, &base_data_sources);
if (base_data_sources.empty()) {
OLAP_LOG_WARNING("fail to acquire need data sources. [table=%s; version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return OLAP_ERR_BE_ACQUIRE_DATA_SOURCES_ERROR;
}
if (PaloMetrics::be_merge_delta_num() != NULL) {
PaloMetrics::be_merge_delta_num()->increment(_need_merged_versions.size());
int64_t merge_size = 0;
for (IData* i_data : base_data_sources) {
merge_size += i_data->olap_index()->data_size();
}
PaloMetrics::be_merge_size()->increment(merge_size);
}
// 保存生成base文件时候计算的selectivities
vector<uint32_t> selectivities;
// 保存生成base文件时候累积的行数
uint64_t row_count = 0;
// 3. 执行base expansion
// 执行过程可能会持续比较长时间
stage_watch.reset();
res = _do_base_expansion(new_base_version_hash,
&base_data_sources,
&selectivities,
&row_count);
// 释放不再使用的IData对象
_table->release_data_sources(&base_data_sources);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to do base version. [table=%s; version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return res;
}
OLAP_LOG_TRACE("elapsed time of doing base version", "%ldus",
stage_watch.get_elapse_time_us());
// 4. 使新生成的base生效,并删除不再需要版本对应的文件
_obtain_header_wrlock();
vector<OLAPIndex*> unused_olap_indices;
// 使得新生成的各个Version生效, 如果失败掉则需要清理掉已经生成的Version文件
res = _update_header(selectivities, row_count, &unused_olap_indices);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to update header. [table=%s; version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return res;
}
_release_header_lock();
_delete_old_files(&unused_olap_indices);
// validate that delete action is right
// if error happened, sleep 1 hour. Report a fatal log every 1 minute
if (_validate_delete_file_action() != OLAP_SUCCESS) {
int sleep_count = 0;
while (true) {
if (sleep_count >= 60) {
break;
}
++sleep_count;
OLAP_LOG_FATAL("base expansion's delete action has error.sleep 1 minute...");
sleep(60);
}
_cleanup();
return OLAP_ERR_BE_ERROR_DELETE_ACTION;
}
_table->set_base_expansion_status(BASE_EXPANSION_WAITING, -1);
_release_base_expansion_lock();
return OLAP_SUCCESS;
}
OLAPStatus BaseExpansionHandler::_exclude_not_expired_delete(
const vector<Version>& need_merged_versions,
vector<Version>* candidate_versions) {
const int64_t delete_delta_expire_time = config::delete_delta_expire_time * 60;
OLAPStatus res = OLAP_SUCCESS;
for (unsigned int index = 0; index < need_merged_versions.size(); ++index) {
Version temp = need_merged_versions[index];
int64_t file_creation_time = 0;
res = _table->version_creation_time(temp, &file_creation_time);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("table doesn't have version. [table=%s; version=%d-%d]",
_table->full_name().c_str(), temp.first, temp.second);
return res;
}
int64_t file_existed_time = time(NULL) - file_creation_time;
// 从小版本号往大版本号查找;找到第1个没有过期的delete版本时,退出
if (_table->is_delete_data_version(temp)
&& file_existed_time < delete_delta_expire_time) {
OLAP_LOG_INFO("delete version is not expired."
"[delete_version=%d; existed_time=%ld; expired_time=%ld]",
temp.first, file_existed_time,
delete_delta_expire_time);
break;
}
candidate_versions->push_back(temp);
}
return OLAP_SUCCESS;
}
static bool version_comparator(const Version& lhs, const Version& rhs) {
return lhs.second < rhs.second;
}
bool BaseExpansionHandler::_check_whether_satisfy_policy(bool is_manual_trigger,
vector<Version>* candidate_versions) {
_obtain_header_rdlock();
int32_t cumulative_layer_point = _table->cumulative_layer_point();
if (cumulative_layer_point == -1) {
OLAP_LOG_FATAL("tablet has an unreasonable cumulative layer point. "
"[tablet='%s' cumulative_layer_point=%d]",
_table->full_name().c_str(), cumulative_layer_point);
_release_header_lock();
return false;
}
// 为了后面计算方便,我们在这里先将cumulative_layer_point减1
--cumulative_layer_point;
vector<Version> path_versions;
if (OLAP_SUCCESS != _table->select_versions_to_span(Version(0, cumulative_layer_point),
&path_versions)) {
OLAP_LOG_WARNING("fail to select shortest version path. [start=%d end=%d]",
0, cumulative_layer_point);
_release_header_lock();
return false;
}
// be_layer_point应该为cumulative_layer_point之前,倒数第2个cumulative文件的end version
int64_t base_creation_time = 0;
size_t base_size = 0;
int32_t be_layer_point = -1;
for (unsigned int index = 0; index < path_versions.size(); ++index) {
Version temp = path_versions[index];
// base文件
if (temp.first == 0) {
_old_base_version = temp;
base_size = _table->get_version_entity_by_version(temp).data_size;
base_creation_time = _table->file_version(index).creation_time();
continue;
}
if (temp.second == cumulative_layer_point) {
be_layer_point = temp.first - 1;
_latest_cumulative = temp;
_new_base_version = Version(0, be_layer_point);
}
}
// 只有1个base文件和1个delta文件
if (be_layer_point == -1) {
OLAP_LOG_TRACE("can't do base expansion: no cumulative files. "
"[table=%s; base_version=0-%d; cumulative_layer_point=%d]",
_table->full_name().c_str(),
_old_base_version.second,
cumulative_layer_point + 1);
_release_header_lock();
return false;
}
// 只有1个cumulative文件
if (be_layer_point == _old_base_version.second) {
OLAP_LOG_TRACE("can't do base expansion: only one cumulative file. "
"[table=%s; base_version=0-%d; cumulative_layer_point=%d]",
_table->full_name().c_str(),
_old_base_version.second,
cumulative_layer_point + 1);
_release_header_lock();
return false;
}
// 使用最短路径算法,选择可合并的cumulative版本
vector<Version> need_merged_versions;
if (OLAP_SUCCESS != _table->select_versions_to_span(_new_base_version,
&need_merged_versions)) {
OLAP_LOG_WARNING("fail to select shortest version path. [start=%d end=%d]",
_new_base_version.first, _new_base_version.second);
_release_header_lock();
return false;
}
std::sort(need_merged_versions.begin(), need_merged_versions.end(), version_comparator);
// 如果是手动执行START_BASE_EXPANSION命令,则不检查base expansion policy,
// 也不考虑删除版本过期问题, 只要有可以合并的cumulative,就执行base expansion
if (is_manual_trigger) {
OLAP_LOG_TRACE("manual triggle base expansion. [table=%s]", _table->full_name().c_str());
*candidate_versions = need_merged_versions;
_release_header_lock();
return true;
}
if (_exclude_not_expired_delete(need_merged_versions, candidate_versions) != OLAP_SUCCESS) {
OLAP_LOG_WARNING("failed to exclude not expired delete version.");
_release_header_lock();
return false;
}
if (candidate_versions->size() != need_merged_versions.size()) {
OLAP_LOG_INFO("reset new base version. "
"[previous_new_base_version=0-%d; new_base_version=0-%d]",
_new_base_version.second, candidate_versions->rbegin()->second);
_new_base_version = Version(0, candidate_versions->rbegin()->second);
}
// 统计可合并cumulative版本文件的总大小
size_t cumulative_total_size = 0;
for (vector<Version>::const_iterator version_iter = candidate_versions->begin();
version_iter != candidate_versions->end(); ++version_iter) {
Version temp = *version_iter;
// 跳过base文件
if (temp.first == 0) {
continue;
}
// cumulative文件
cumulative_total_size += _table->get_version_entity_by_version(temp).data_size;
}
_release_header_lock();
// 检查是否满足base expansion的触发条件
// 满足以下条件时触发base expansion: 触发条件1 || 触发条件2 || 触发条件3
// 触发条件1:cumulative文件个数超过一个阈值
const uint32_t be_policy_cumulative_files_number = config::be_policy_cumulative_files_number;
// candidate_versions中包含base文件,所以这里减1
if (candidate_versions->size() - 1 >= be_policy_cumulative_files_number) {
OLAP_LOG_INFO("satisfy the base expansion policy. [table=%s; "
"cumualtive_files_number=%d; policy_cumulative_files_number=%d]",
_table->full_name().c_str(),
candidate_versions->size() - 1,
be_policy_cumulative_files_number);
return true;
}
// 触发条件2:所有cumulative文件的大小超过base文件大小的某一比例
const double be_policy_cumulative_base_ratio = config::be_policy_cumulative_base_ratio;
double cumulative_base_ratio = static_cast<double>(cumulative_total_size) / base_size;
if (cumulative_base_ratio > be_policy_cumulative_base_ratio) {
OLAP_LOG_INFO("satisfy the base expansion policy. [table=%s; cumualtive_total_size=%d; "
"base_size=%d; cumulative_base_ratio=%f; policy_ratio=%f]",
_table->full_name().c_str(),
cumulative_total_size,
base_size,
cumulative_base_ratio,
be_policy_cumulative_base_ratio);
return true;
}
// 触发条件3:距离上一次进行base expansion已经超过设定的间隔时间
const uint32_t be_policy_be_interval = config::be_policy_be_interval_seconds;
int64_t interval_since_last_be = time(NULL) - base_creation_time;
if (interval_since_last_be > be_policy_be_interval) {
OLAP_LOG_INFO("satisfy the base expansion policy. [table=%s; "
"interval_since_last_be=%ld; policy_interval=%ld]",
_table->full_name().c_str(),
interval_since_last_be, be_policy_be_interval);
return true;
}
OLAP_LOG_TRACE(
"don't satisfy the base expansion policy."
"[cumulative_files_number=%d; cumulative_base_ratio=%f; interval_since_last_be=%ld]",
candidate_versions->size() - 1,
cumulative_base_ratio,
interval_since_last_be);
return false;
}
OLAPStatus BaseExpansionHandler::_do_base_expansion(VersionHash new_base_version_hash,
vector<IData*>* base_data_sources,
vector<uint32_t>* selectivities,
uint64_t* row_count) {
// 1. 生成新base文件对应的olap index
OLAPIndex* new_base = new (std::nothrow) OLAPIndex(_table.get(),
_new_base_version,
new_base_version_hash,
false,
0, 0);
if (new_base == NULL) {
OLAP_LOG_WARNING("fail to new OLAPIndex.");
return OLAP_ERR_MALLOC_ERROR;
}
OLAP_LOG_INFO("start merge new base. [table='%s' version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
// 2. 执行base expansion的merge
// 注意:无论是行列存,还是列存,在执行merge时都使用Merger类,不能使用MassiveMerger。
// 原因:MassiveMerger中的base文件不是通过Reader读取的,所以会导致删除条件失效,
// 无法达到删除数据的目的
// 想法:如果一定要使用MassiveMerger,这里可以提供一种方案
// 1. 在此处加一个检查,检测此次BE是否包含删除条件, 即检查Reader中
// ReaderParams的delete_handler
// 2. 如果包含删除条件,则不使用MassiveMerger,使用Merger
// 3. 如果不包含删除条件,则可以使用MassiveMerger
uint64_t merged_rows = 0;
uint64_t filted_rows = 0;
OLAPStatus res = OLAP_SUCCESS;
if (_table->data_file_type() == OLAP_DATA_FILE
|| _table->data_file_type() == COLUMN_ORIENTED_FILE) {
_table->obtain_header_rdlock();
bool use_simple_merge = true;
if (_table->delete_data_conditions_size() > 0) {
use_simple_merge = false;
}
_table->release_header_lock();
Merger merger(_table, new_base, READER_BASE_EXPANSION);
res = merger.merge(
*base_data_sources, use_simple_merge, &merged_rows, &filted_rows);
if (res == OLAP_SUCCESS) {
*row_count = merger.row_count();
*selectivities = merger.selectivities();
}
} else {
OLAP_LOG_WARNING("unknown data file type. [type=%s]",
DataFileType_Name(_table->data_file_type()).c_str());
res = OLAP_ERR_DATA_FILE_TYPE_ERROR;
}
// 3. 如果merge失败,执行清理工作,返回错误码退出
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to make new base version. [table='%s' version='%d.%d' res=%d]",
_table->full_name().c_str(),
_new_base_version.first,
_new_base_version.second,
res);
new_base->delete_all_files();
SAFE_DELETE(new_base);
return OLAP_ERR_BE_MERGE_ERROR;
}
// 4. 如果merge成功,则将新base文件对应的olap index载入
_new_olap_indices.push_back(new_base);
OLAP_LOG_TRACE("merge new base success, start load index. [table='%s' version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
res = new_base->load();
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to load index. [version='%d-%d' version_hash=%ld table='%s']",
new_base->version().first,
new_base->version().second,
new_base->version_hash(),
_table->full_name().c_str());
return res;
}
// Check row num changes
uint64_t source_rows = 0;
for (IData* i_data : *base_data_sources) {
source_rows += i_data->olap_index()->num_rows();
}
bool row_nums_check = config::row_nums_check;
if (row_nums_check) {
if (source_rows != new_base->num_rows() + merged_rows + filted_rows) {
OLAP_LOG_FATAL("fail to check row num! "
"[source_rows=%lu merged_rows=%lu filted_rows=%lu new_index_rows=%lu]",
source_rows, merged_rows, filted_rows, new_base->num_rows());
return OLAP_ERR_CHECK_LINES_ERROR;
}
} else {
OLAP_LOG_INFO("all row nums. "
"[source_rows=%lu merged_rows=%lu filted_rows=%lu new_index_rows=%lu]",
source_rows, merged_rows, filted_rows, new_base->num_rows());
}
return OLAP_SUCCESS;
}
OLAPStatus BaseExpansionHandler::_update_header(const vector<uint32_t>& selectivities,
uint64_t row_count,
vector<OLAPIndex*>* unused_olap_indices) {
vector<Version> unused_versions;
_get_unused_versions(&unused_versions);
OLAPStatus res = OLAP_SUCCESS;
// 由于在replace_data_sources中可能会发生很小概率的非事务性失败, 因此这里定位FATAL错误
res = _table->replace_data_sources(&unused_versions,
&_new_olap_indices,
unused_olap_indices);
if (res != OLAP_SUCCESS) {
OLAP_LOG_FATAL("fail to replace data sources. "
"[res=%d table=%s; new_base=%d; old_base=%d]",
_table->full_name().c_str(),
_new_base_version.second,
_old_base_version.second);
return res;
}
_table->set_selectivities(selectivities);
OLAP_LOG_INFO("BE remove delete conditions. [removed_version=%d]", _new_base_version.second);
// Base Expansion完成之后,需要删除header中版本号小于等于新base文件版本号的删除条件
DeleteConditionHandler cond_handler;
cond_handler.delete_cond(_table, _new_base_version.second, true);
// 如果保存Header失败, 所有新增的信息会在下次启动时丢失, 属于严重错误
// 暂时没办法做很好的处理,报FATAL
res = _table->save_header();
if (res != OLAP_SUCCESS) {
OLAP_LOG_FATAL("fail to save header. "
"[res=%d table=%s; new_base=%d; old_base=%d]",
_table->full_name().c_str(),
_new_base_version.second,
_old_base_version.second);
return OLAP_ERR_BE_SAVE_HEADER_ERROR;
}
_new_olap_indices.clear();
return OLAP_SUCCESS;
}
void BaseExpansionHandler::_delete_old_files(vector<OLAPIndex*>* unused_indices) {
if (!unused_indices->empty()) {
OLAPUnusedIndex* unused_index = OLAPUnusedIndex::get_instance();
for (vector<OLAPIndex*>::iterator it = unused_indices->begin();
it != unused_indices->end(); ++it) {
unused_index->add_unused_index(*it);
}
}
}
void BaseExpansionHandler::_cleanup() {
// 清理掉已生成的版本文件
for (vector<OLAPIndex*>::iterator it = _new_olap_indices.begin();
it != _new_olap_indices.end(); ++it) {
(*it)->delete_all_files();
SAFE_DELETE(*it);
}
_new_olap_indices.clear();
// 释放打开的锁
_release_header_lock();
_release_base_expansion_lock();
_table->set_base_expansion_status(BASE_EXPANSION_WAITING, -1);
}
bool BaseExpansionHandler::_validate_need_merged_versions(
const vector<Version>& candidate_versions) {
if (candidate_versions.size() <= 1) {
OLAP_LOG_WARNING("unenough versions need to be merged. [size=%lu]",
candidate_versions.size());
return false;
}
// 1. validate versions in candidate_versions are continuous
// Skip the first element
for (unsigned int index = 1; index < candidate_versions.size(); ++index) {
Version previous_version = candidate_versions[index - 1];
Version current_version = candidate_versions[index];
if (current_version.first != previous_version.second + 1) {
OLAP_LOG_WARNING("wrong need merged version. "
"previous_version=%d-%d; current_version=%d-%d",
previous_version.first, previous_version.second,
current_version.first, current_version.second);
return false;
}
}
// 2. validate m_new_base_version is OK
if (_new_base_version.first != 0
|| _new_base_version.first != candidate_versions.begin()->first
|| _new_base_version.second != candidate_versions.rbegin()->second) {
OLAP_LOG_WARNING("new_base_version is wrong. "
"[new_base_version=%d-%d; vector_version=%d-%d]",
_new_base_version.first, _new_base_version.second,
candidate_versions.begin()->first,
candidate_versions.rbegin()->second);
return false;
}
OLAP_LOG_TRACE("valid need merged version");
return true;
}
OLAPStatus BaseExpansionHandler::_validate_delete_file_action() {
// 1. acquire the latest version to make sure all is right after deleting files
_obtain_header_rdlock();
const FileVersionMessage* latest_version = _table->latest_version();
Version test_version = Version(0, latest_version->end_version());
vector<IData*> test_sources;
_table->acquire_data_sources(test_version, &test_sources);
if (test_sources.size() == 0) {
OLAP_LOG_INFO("acquire data sources failed. version=%d-%d",
test_version.first, test_version.second);
_release_header_lock();
return OLAP_ERR_BE_ERROR_DELETE_ACTION;
}
_table->release_data_sources(&test_sources);
OLAP_LOG_TRACE("delete file action is OK");
_release_header_lock();
return OLAP_SUCCESS;
}
} // namespace palo
| 38.595577
| 99
| 0.620237
|
DiffBlue-benchmarks
|
321c3ffcbfc764ede04835b683800520a8bdff0b
| 404
|
cpp
|
C++
|
state_mach.cpp
|
davitkalantaryan/fork-cpp-raft
|
f8d08a645ba541d42c6f2db54137fbfa53b5908d
|
[
"BSD-3-Clause"
] | 20
|
2015-01-19T02:12:50.000Z
|
2020-12-09T17:02:42.000Z
|
state_mach.cpp
|
davitkalantaryan/fork-cpp-raft
|
f8d08a645ba541d42c6f2db54137fbfa53b5908d
|
[
"BSD-3-Clause"
] | 1
|
2015-12-15T11:28:19.000Z
|
2015-12-15T11:28:19.000Z
|
state_mach.cpp
|
davitkalantaryan/fork-cpp-raft
|
f8d08a645ba541d42c6f2db54137fbfa53b5908d
|
[
"BSD-3-Clause"
] | 9
|
2015-08-20T15:35:17.000Z
|
2020-07-17T02:26:35.000Z
|
#include "state_mach.h"
using namespace Raft;
State::State() {
}
State::~State() {
}
bool State::is_follower() {
return d_state == RAFT_STATE_FOLLOWER;
}
bool State::is_leader() {
return d_state == RAFT_STATE_LEADER;
}
bool State::is_candidate() {
return d_state == RAFT_STATE_CANDIDATE;
}
void State::set(RAFT_STATE state) { d_state = state; }
RAFT_STATE State::get() { return d_state; }
| 14.962963
| 54
| 0.693069
|
davitkalantaryan
|
321e52d806270a22769c244eecdbf204b18e506a
| 1,539
|
cpp
|
C++
|
samples/webserver.cpp
|
nodenative/nodenative
|
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
|
[
"MIT"
] | 16
|
2016-03-16T22:16:18.000Z
|
2021-04-05T04:46:38.000Z
|
samples/webserver.cpp
|
nodenative/nodenative
|
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
|
[
"MIT"
] | 11
|
2016-03-16T22:02:26.000Z
|
2021-04-04T02:20:51.000Z
|
samples/webserver.cpp
|
nodenative/nodenative
|
cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3
|
[
"MIT"
] | 5
|
2016-03-22T14:03:34.000Z
|
2021-01-06T18:08:46.000Z
|
#include <iostream>
#include <native/native.hpp>
using namespace native;
using namespace http;
int main() {
std::shared_ptr<Loop> loop = Loop::Create();
std::shared_ptr<Server> server = Server::Create(loop);
server->get("/", [](std::shared_ptr<ServerConnection> connection) -> Future<void> {
// some initial work on the main thread
std::weak_ptr<ServerConnection> connectionWeak = connection;
ServerResponse &res = connection->getResponse();
res.setStatus(200);
res.setHeader("Content-Type", "text/plain");
// wait... I have some async work too. I will update you when I'm done.
return worker([]() {
// Some work on the thread pool to keep the main thread free
std::chrono::milliseconds time(2000);
std::this_thread::sleep_for(time);
})
.then([]() {
// and some work on the main thread to sync data and avoid race condition
std::chrono::milliseconds time(100);
std::this_thread::sleep_for(time);
})
.finally([connectionWeak]() {
// in the end send the response.
connectionWeak.lock()->getResponse().end("C++ FTW\n");
});
});
server->onError([](const Error &err) { std::cout << "error name: " << err.name(); });
if (!server->listen("0.0.0.0", 8080)) {
std::cout << "cannot start server. Check the port 8080 if it is free.\n";
return 1; // Failed to run server.
}
std::cout << "Server running at http://0.0.0.0:8080/" << std::endl;
return run();
}
| 34.2
| 87
| 0.606888
|
nodenative
|
321ea55f66bcb059d8b71afc93e24621cc8442e6
| 5,572
|
cpp
|
C++
|
OpenCup/e.cpp
|
JackBai0914/Competitive-Programming-Codebase
|
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
|
[
"MIT"
] | null | null | null |
OpenCup/e.cpp
|
JackBai0914/Competitive-Programming-Codebase
|
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
|
[
"MIT"
] | null | null | null |
OpenCup/e.cpp
|
JackBai0914/Competitive-Programming-Codebase
|
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
|
[
"MIT"
] | null | null | null |
/*
* * * * * * * * * * * * * * * * * *
*
* @author: Xingjian Bai
* @date: 2020-10-11 10:31:31
* @description:
* /Users/jackbai/Desktop/OI/OpenCup/e.cpp
*
* @notes:
* g++ -fsanitize=address -ftrapv e.cpp
* * * * * * * * * * * * * * * * * */
#include <bits/stdc++.h>
#define F first
#define S second
#define MP make_pair
#define TIME (double)clock()/CLOCKS_PER_SEC
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
const int MOD = 1000000007;
const int INF = 1e9;
const ld eps = 1e-8;
#define FOR(i,a,b) for (int i = (a); i < (b); i ++)
#define F0R(i,a) FOR(i, 0, a)
#define ROF(i, a, b) for (int i = (b) - 1; i >= a; i --)
#define R0F(i, a) ROF(i, 0, a)
#define trav(a, x) for (auto& a: x)
#define debug(x) cerr << "(debug mod) " << #x << " = " << x << endl
const int maxn = 1e6;
int n, m;
ll fans = 0;
vector <int> adj[maxn];
ll dg[maxn], dg2[maxn], sdg[maxn];
int a3[maxn], a3i[maxn];
priority_queue <pii> a3q;
namespace SegTree{
typedef struct node {
int st, ed;
node *l, *r;
ll mx, num_mx, lz;
ll mx2, num_mx2;
node () {}
node (int stt, int edd, node *L, node *R, ll mxx) {
st = stt, ed = edd, l = L, r = R, mx = mxx, num_mx = 1, mx2 = -INF, num_mx2 = 0, lz = 0;
}
} *pnode;
void update (pnode r) {
if (!r || !r->l)
return ;
r->mx = max (r->l->mx, r->r->mx);
r->mx2 = -INF;
if (r->l->mx != r->mx) r->mx2 = max (r->mx2, r->l->mx);
if (r->r->mx != r->mx) r->mx2 = max (r->mx2, r->r->mx);
if (r->l->mx2 != r->mx) r->mx2 = max (r->mx2, r->l->mx2);
if (r->r->mx2 != r->mx) r->mx2 = max (r->mx2, r->r->mx2);
r->num_mx = 0;
r->num_mx2 = 0;
if (r->l->mx == r->mx) r->num_mx += r->l->num_mx;
if (r->r->mx == r->mx) r->num_mx += r->r->num_mx;
if (r->l->mx2 == r->mx) r->num_mx += r->l->num_mx2;
if (r->r->mx2 == r->mx) r->num_mx += r->r->num_mx2;
if (r->l->mx == r->mx2) r->num_mx2 += r->l->num_mx;
if (r->r->mx == r->mx2) r->num_mx2 += r->r->num_mx;
if (r->l->mx2 == r->mx2) r->num_mx2 += r->l->num_mx2;
if (r->r->mx2 == r->mx2) r->num_mx2 += r->r->num_mx2;
}
pnode build (int st, int ed) {
if (st == ed) {
pnode ne = new node (st, ed, 0, 0, sdg[st]);
return ne;
}
int mid = (st + ed) >> 1;
pnode ne = new node (st, ed, build (st, mid), build (mid + 1, ed), 0);
update (ne);
return ne;
}
void down (pnode r) {
if (!r || !r->l)
return ;
if (r->lz) {
r->l->mx += r->lz;
r->r->mx += r->lz;
r->l->mx2 += r->lz;
r->r->mx2 += r->lz;
r->l->lz += r->lz;
r->r->lz += r->lz;
r->lz = 0;
}
}
void modify (pnode r, int st, int ed, ll v) {
if (st <= r->st && r->ed <= ed) {
r->mx += v;
r->mx2 += v;
r->lz += v;
return ;
}
down (r);
if (st <= r->l->ed) modify (r->l, st, ed, v);
if (r->r->st <= ed) modify (r->r, st, ed, v);
update (r);
}
ll count_zero(pnode r, int st, int ed, ll v) {
// cout << r->st << " " << r->ed << " " << st << " " << ed << " " << v << endl;
// cout << "info: " << r->mx << " " << r->num_mx << " " << r->mx2 << " " << r->num_mx2 << endl;
if (st <= r->st && r->ed <= ed) {
if (r->mx == v) return r->num_mx;
if (r->mx2 == v) return r->num_mx2;
return 0;
}
down (r);
ll ans = 0;
if (st <= r->l->ed) ans += count_zero (r->l, st, ed, v);
if (r->r->st <= ed) ans += count_zero (r->r, st, ed, v);
return ans;
}
void order (pnode r) {
// cout << r->st << " " << r->ed << " : " << r->mx << " " << r->mx2 << " " << r->num_mx << " " << r->num_mx2 << endl;
if (r->st == r->ed) {
cout << r->st << " : " << r->mx << endl;
return ;
}
down(r);
order(r->l);
order(r->r);
}
} using namespace SegTree;
pnode root;
void dg_minus(int x, ll dt) {
dg2[x] -= dt;
modify (root, x, n, -dt);
}
ll find_sdg (int st, int ed, ll val) {
return count_zero(root, st, ed, val);
}
int main() {
scanf("%d %d", &n, &m);
F0R(i, m) {
int x, y;
scanf("%d %d", &x, &y);
adj[x].push_back(y);
adj[y].push_back(x);
dg[x] ++, dg[y] ++;
dg2[max(x, y)] ++;
}
FOR(i, 1, n + 1) {
sort(adj[i].begin(), adj[i].end());
if (adj[i].size() >= 3) {
a3[i] = adj[i][2], a3i[i] = 2;
a3q.push(MP(-max(i, a3[i]), i));
}
else {
a3[i] = n + 1, a3i[i] = adj[i].size();
a3q.push(MP(-(n + 1), i));
}
sdg[i] = sdg[i - 1] + dg2[i];
}
FOR(i, 1, n + 1)
sdg[i] -= i;
root = build(1, n);
FOR(i, 1, n + 1) {
order(root);
// cout << "begin" << endl;
//find the largest r such that for all i from l to r, dg[i] <= 2
int bound, bid;
bool cont = true;
do {
pii tp = a3q.top();
bound = -tp.F, bid = tp.S;
if (bound == n + 1) break;
if (bid >= i && bound == max(bid, a3[bid])) break;
a3q.pop();
} while (true);
bound = min (bound, n + 1);
// cout << "bound: " << bound << endl;
//find the number of i from l to bound-1 such that sdg[i]-2*i==-2*l;
ll pans = find_sdg(i, bound - 1, -i);
cout << "find " << -i << " in " << i << " " << bound - 1 << endl;
fans += pans;
cout << "ans " << i << " : " << pans << endl;
//delete i's neithbors' a3
F0R(j, adj[i].size()) {
int to = adj[i][j];
if (to < i)
continue ;
if (a3i[to] == adj[to].size())
continue ;
a3i[to] ++;
if (a3i[to] == adj[to].size()) {
a3[to] = n + 1;
a3q.push(MP(-(n + 1), i));
}
else {
a3[to] = adj[to][a3i[to]];
a3q.push(MP(-max(to, a3[to]), to));
}
}
//delete i's neighbors's dg
F0R(j, adj[i].size()) {
int to = adj[i][j];
if (to > i)
dg_minus(to, 1);
}
}
printf("%lld\n", fans);
// cerr << TIME << endl;
return 0;
}
| 25.559633
| 119
| 0.470747
|
JackBai0914
|
32234a55fff0457a3399490a0db7f51162085257
| 437
|
cc
|
C++
|
platform/client_native_pixmap_factory_qt.cc
|
tworaz/ozone_qt
|
a015069d3d68cfe0826e76977c974baa1f459834
|
[
"MIT"
] | null | null | null |
platform/client_native_pixmap_factory_qt.cc
|
tworaz/ozone_qt
|
a015069d3d68cfe0826e76977c974baa1f459834
|
[
"MIT"
] | null | null | null |
platform/client_native_pixmap_factory_qt.cc
|
tworaz/ozone_qt
|
a015069d3d68cfe0826e76977c974baa1f459834
|
[
"MIT"
] | null | null | null |
// Copyright 2015 Piotr Tworek. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone_qt/platform/client_native_pixmap_factory_qt.h"
#include "ui/ozone/common/stub_client_native_pixmap_factory.h"
namespace ui {
ClientNativePixmapFactory* CreateClientNativePixmapFactoryQt() {
return CreateStubClientNativePixmapFactory();
}
} // namespace ui
| 27.3125
| 73
| 0.796339
|
tworaz
|