hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 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
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9b48d5e4e8a9a8f65d4e01e68adc6cfac40bc6dc | 4,261 | hpp | C++ | mllib/LogisticRegression.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | 1 | 2019-01-23T02:10:10.000Z | 2019-01-23T02:10:10.000Z | mllib/LogisticRegression.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | mllib/LogisticRegression.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | /*
Edit by Christina
*/
#pragma once
#include <limits>
#include "mllib/Utility.hpp"
#include "mllib/Instances.hpp"
#include "lib/aggregator_factory.hpp"
#include "mllib/Classifier.hpp"
namespace husky{
namespace mllib{
/*
MODE
GLOBAL: global training
LOCAL: training using local data
*/
enum class MODE {GLOBAL=0, LOCAL=1};
class LogisticRegression : public Classifier{
private:
matrix_double param_matrix;//parameter matrix
int max_iter; //Maximun iterations|pass through the data, default:5
double eta0; //The initial learning rate. The default value is 1.
double alpha; //Constant that multuplies the regularization term, defualt: 0.0001.
double trival_improve_th; //If weighted squared error improve is less than trival_improve_th, then this improve is trival.
int max_trival_improve_iter; //If there are max_trival_improve_iter sequential iteration with trival_improve, then training will be stopped.
MODE mode; //default: GLOBAL
int class_num; //default: 2
/*
Default settings
maximize conditional log likelihood
gradient descent update rule
L2 penalty (least squares of 'param_vec'), a regularizer
invscaling learning_rate : eta = eta0/pow(t, 0.5) NOTE: learning rate will only be updated when the loss increases, at the same time t will be increased by 1.
*/
/* Variables for extension
std::string loss;//The loss function to be used. Defaults to "squared_loss". Only "Squared loss" is implemented in this stage.
std::string penalty; //The penalty to be used. Defaults to "L2", second norm of 'param_vec', which is a standard regularizer.
std::string learning_rate; //Type of learning rate to be used. Options include (1)'constant': eta = eta0;(2)'invscaling': eta = eta0/pow(t, 0.5);
*/
public:
LogisticRegression(){
//default parameters
max_iter = 5;
eta0 = 1;
alpha = 0.0001;
trival_improve_th = 0.001;
max_trival_improve_iter = 100;
mode = MODE::GLOBAL;
class_num = 2;
}
LogisticRegression(int m_iter, double e0, double al, double trival_im, double max_trival_im, MODE m, int classNum) : max_iter(m_iter), eta0(e0), alpha(al), trival_improve_th(trival_im), max_trival_improve_iter(max_trival_im), mode(m), class_num(classNum){}
/*
train a logistic regression model with even weighted instances.
*/
void fit(const Instances& instances);
/*
train model in global or local mode.
*/
void local_fit(const Instances& instances);
void global_fit(const Instances& instances);
void local_fit(const Instances& instances, std::string instance_weight_name);
void global_fit(const Instances& instances, std::string instance_weight_name);
/*
train a logistic regression model using instance weight, which is specified as a attribute list of original_instances, name of which is 'instance_weight_name'.
*/
void fit(const Instances& instances, std::string instance_weight_name);
AttrList<Instance, Prediction>& predict(const Instances& instances,std::string prediction_name="prediction");
Classifier* clone(int seed=0){
return new LogisticRegression(this->max_iter, this->eta0, this->alpha, this->trival_improve_th, this->max_trival_improve_iter, this->mode, this->class_num);
}
matrix_double get_parameters(){
return param_matrix;
}
};
}
}
| 45.817204 | 273 | 0.574513 | Christina-hshi |
9b494df3b5e60407052fe5b8a93ae58a3c4bab6a | 565 | hpp | C++ | include/MemeCore/TestRequest.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | include/MemeCore/TestRequest.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | include/MemeCore/TestRequest.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | #ifndef _ML_REQUEST_HPP_
#define _ML_REQUEST_HPP_
#include <MemeCore/IRequest.hpp>
namespace ml
{
/* * * * * * * * * * * * * * * * * * * * */
class ML_CORE_API TestRequest
: public IRequest
{
public:
using LogFunc = void(*)(const ml::String &);
public:
TestRequest();
~TestRequest();
public:
void setValue(int32_t value);
void setFunc(LogFunc value);
public:
void process() override;
void finish() override;
private:
int32_t m_value;
LogFunc m_func;
};
/* * * * * * * * * * * * * * * * * * * * */
}
#endif // !_ML_REQUEST_HPP_ | 15.694444 | 46 | 0.59469 | Gurman8r |
9b52892eac05dc229e55bcbb9214c1db73817838 | 9,115 | hpp | C++ | libraries/protocol/include/scorum/protocol/betting/market.hpp | scorum/scorum | 1da00651f2fa14bcf8292da34e1cbee06250ae78 | [
"MIT"
] | 53 | 2017-10-28T22:10:35.000Z | 2022-02-18T02:20:48.000Z | libraries/protocol/include/scorum/protocol/betting/market.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 38 | 2017-11-25T09:06:51.000Z | 2018-10-31T09:17:22.000Z | libraries/protocol/include/scorum/protocol/betting/market.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 27 | 2018-01-08T19:43:35.000Z | 2022-01-14T10:50:42.000Z | #pragma once
#include <fc/static_variant.hpp>
#include <scorum/protocol/betting/wincase.hpp>
#include <scorum/protocol/betting/market_kind.hpp>
#include <scorum/protocol/config.hpp>
#include <boost/range/algorithm/transform.hpp>
namespace scorum {
namespace protocol {
template <market_kind kind, typename tag = void> struct over_under_market
{
int16_t threshold;
template <bool site> using wincase = over_under_wincase<site, kind, tag>;
using over = wincase<true>;
using under = wincase<false>;
static constexpr market_kind kind_v = kind;
bool has_trd_state() const
{
return threshold % SCORUM_BETTING_THRESHOLD_FACTOR == 0;
}
};
template <market_kind kind, typename tag = void> struct score_yes_no_market
{
uint16_t home;
uint16_t away;
template <bool site> using wincase = score_yes_no_wincase<site, kind, tag>;
using yes = wincase<true>;
using no = wincase<false>;
static constexpr market_kind kind_v = kind;
bool has_trd_state() const
{
return false;
}
};
template <market_kind kind, typename tag = void> struct yes_no_market
{
template <bool site> using wincase = yes_no_wincase<site, kind, tag>;
using yes = wincase<true>;
using no = wincase<false>;
static constexpr market_kind kind_v = kind;
bool has_trd_state() const
{
return false;
}
};
struct home_tag;
struct away_tag;
struct draw_tag;
struct both_tag;
using result_home = yes_no_market<market_kind::result, home_tag>;
using result_draw = yes_no_market<market_kind::result, draw_tag>;
using result_away = yes_no_market<market_kind::result, away_tag>;
using round_home = yes_no_market<market_kind::round>;
using handicap = over_under_market<market_kind::handicap>;
using correct_score_home = yes_no_market<market_kind::correct_score, home_tag>;
using correct_score_draw = yes_no_market<market_kind::correct_score, draw_tag>;
using correct_score_away = yes_no_market<market_kind::correct_score, away_tag>;
using correct_score = score_yes_no_market<market_kind::correct_score>;
using goal_home = yes_no_market<market_kind::goal, home_tag>;
using goal_both = yes_no_market<market_kind::goal, both_tag>;
using goal_away = yes_no_market<market_kind::goal, away_tag>;
using total = over_under_market<market_kind::total>;
using total_goals_home = over_under_market<market_kind::total_goals, home_tag>;
using total_goals_away = over_under_market<market_kind::total_goals, away_tag>;
using market_type = fc::static_variant<result_home,
result_draw,
result_away,
round_home,
handicap,
correct_score_home,
correct_score_draw,
correct_score_away,
correct_score,
goal_home,
goal_both,
goal_away,
total,
total_goals_home,
total_goals_away>;
using wincase_type = fc::static_variant<result_home::yes,
result_home::no,
result_draw::yes,
result_draw::no,
result_away::yes,
result_away::no,
round_home::yes,
round_home::no,
handicap::over,
handicap::under,
correct_score_home::yes,
correct_score_home::no,
correct_score_draw::yes,
correct_score_draw::no,
correct_score_away::yes,
correct_score_away::no,
correct_score::yes,
correct_score::no,
goal_home::yes,
goal_home::no,
goal_both::yes,
goal_both::no,
goal_away::yes,
goal_away::no,
total::over,
total::under,
total_goals_home::over,
total_goals_home::under,
total_goals_away::over,
total_goals_away::under>;
std::pair<wincase_type, wincase_type> create_wincases(const market_type& market);
wincase_type create_opposite(const wincase_type& wincase);
market_type create_market(const wincase_type& wincase);
bool has_trd_state(const market_type& market);
bool match_wincases(const wincase_type& lhs, const wincase_type& rhs);
market_kind get_market_kind(const wincase_type& wincase);
template <typename T> std::set<market_kind> get_markets_kind(const T& markets)
{
std::set<market_kind> actual_markets;
boost::transform(markets, std::inserter(actual_markets, actual_markets.begin()), [](const market_type& m) {
return m.visit([&](const auto& market_impl) { return market_impl.kind_v; });
});
return actual_markets;
}
template <typename T> bool is_belong_markets(const wincase_type& wincase, const T& markets)
{
const auto wincase_market = create_market(wincase);
for (const auto& market : markets)
{
if (wincase_market == market)
return true;
}
return false;
}
} // namespace protocol
} // namespace scorum
#include <scorum/protocol/betting/wincase_comparison.hpp>
#include <scorum/protocol/betting/market_comparison.hpp>
namespace fc {
using scorum::protocol::market_type;
using scorum::protocol::wincase_type;
template <> void to_variant(const wincase_type& wincase, fc::variant& variant);
template <> void from_variant(const fc::variant& variant, wincase_type& wincase);
template <> void to_variant(const market_type& market, fc::variant& var);
template <> void from_variant(const fc::variant& var, market_type& market);
}
FC_REFLECT_EMPTY(scorum::protocol::result_home)
FC_REFLECT_EMPTY(scorum::protocol::result_draw)
FC_REFLECT_EMPTY(scorum::protocol::result_away)
FC_REFLECT_EMPTY(scorum::protocol::round_home)
FC_REFLECT(scorum::protocol::handicap, (threshold))
FC_REFLECT_EMPTY(scorum::protocol::correct_score_home)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_away)
FC_REFLECT(scorum::protocol::correct_score, (home)(away))
FC_REFLECT_EMPTY(scorum::protocol::goal_home)
FC_REFLECT_EMPTY(scorum::protocol::goal_both)
FC_REFLECT_EMPTY(scorum::protocol::goal_away)
FC_REFLECT(scorum::protocol::total, (threshold))
FC_REFLECT(scorum::protocol::total_goals_home, (threshold))
FC_REFLECT(scorum::protocol::total_goals_away, (threshold))
FC_REFLECT_EMPTY(scorum::protocol::result_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::result_home::no)
FC_REFLECT_EMPTY(scorum::protocol::result_draw::yes)
FC_REFLECT_EMPTY(scorum::protocol::result_draw::no)
FC_REFLECT_EMPTY(scorum::protocol::result_away::yes)
FC_REFLECT_EMPTY(scorum::protocol::result_away::no)
FC_REFLECT_EMPTY(scorum::protocol::round_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::round_home::no)
FC_REFLECT(scorum::protocol::handicap::over, (threshold))
FC_REFLECT(scorum::protocol::handicap::under, (threshold))
FC_REFLECT_EMPTY(scorum::protocol::correct_score_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_home::no)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::yes)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::no)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_away::yes)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_away::no)
FC_REFLECT(scorum::protocol::correct_score::yes, (home)(away))
FC_REFLECT(scorum::protocol::correct_score::no, (home)(away))
FC_REFLECT_EMPTY(scorum::protocol::goal_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::goal_home::no)
FC_REFLECT_EMPTY(scorum::protocol::goal_both::yes)
FC_REFLECT_EMPTY(scorum::protocol::goal_both::no)
FC_REFLECT_EMPTY(scorum::protocol::goal_away::yes)
FC_REFLECT_EMPTY(scorum::protocol::goal_away::no)
FC_REFLECT(scorum::protocol::total::over, (threshold))
FC_REFLECT(scorum::protocol::total::under, (threshold))
FC_REFLECT(scorum::protocol::total_goals_home::over, (threshold))
FC_REFLECT(scorum::protocol::total_goals_home::under, (threshold))
FC_REFLECT(scorum::protocol::total_goals_away::over, (threshold))
FC_REFLECT(scorum::protocol::total_goals_away::under, (threshold))
| 40.691964 | 111 | 0.635765 | scorum |
9b64fe04440fda5b7bfc633eaf03e32d5e2ea0a8 | 1,259 | cc | C++ | deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc | jeffersQuan/greenworks | ab73a59574e4a15a1e97091334b384f6e84257eb | [
"MIT"
] | null | null | null | deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc | jeffersQuan/greenworks | ab73a59574e4a15a1e97091334b384f6e84257eb | [
"MIT"
] | null | null | null | deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc | jeffersQuan/greenworks | ab73a59574e4a15a1e97091334b384f6e84257eb | [
"MIT"
] | null | null | null | // Copyright (c) 2019, Entropy Game Global Limited.
// All rights reserved.
#include <stdint.h>
#include "rail/sdk/base/rail_array.h"
#include "thirdparty/gtest/gtest.h"
struct Item {
int32_t id;
int32_t value;
};
TEST(RailArray, size) {
rail::RailArray<struct Item> array;
EXPECT_EQ(0U, array.size());
array.resize(100);
EXPECT_EQ(100U, array.size());
array.resize(0);
EXPECT_EQ(0U, array.size());
struct Item item;
item.id = 1;
item.value = 100;
array.push_back(item);
EXPECT_EQ(1U, array.size());
EXPECT_EQ(100, array[0].value);
array[0].value = 101;
EXPECT_EQ(101, array[0].value);
const struct Item& it = array[0];
EXPECT_EQ(101, it.value);
struct Item item2;
item2.id = 2;
item2.value = 200;
array.push_back(item2);
EXPECT_EQ(2U, array.size());
rail::RailArray<char> str("Hello", 5);
EXPECT_EQ(5U, str.size());
}
TEST(RailArray, assign) {
rail::RailArray<struct Item> array;
Item items[5];
items[1].value = 100;
array.assign(items, sizeof(items) / sizeof(Item));
EXPECT_EQ(5U, array.size());
EXPECT_EQ(100, array[1].value);
}
TEST(RailArray, buf) {
rail::RailArray<int64_t> array;
EXPECT_EQ(NULL, array.buf());
}
| 22.890909 | 54 | 0.631454 | jeffersQuan |
9b6caf18dd8e10d0f32bb9507f848b8ed7329c4f | 1,552 | hpp | C++ | code/szen/inc/szen/System/SpriteBatch.hpp | Sonaza/scyori | a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf | [
"BSD-3-Clause"
] | null | null | null | code/szen/inc/szen/System/SpriteBatch.hpp | Sonaza/scyori | a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf | [
"BSD-3-Clause"
] | null | null | null | code/szen/inc/szen/System/SpriteBatch.hpp | Sonaza/scyori | a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf | [
"BSD-3-Clause"
] | null | null | null | #ifndef SZEN_SPRITEBATCH_HPP
#define SZEN_SPRITEBATCH_HPP
#include <SFML/Graphics.hpp>
#include <functional>
#include <map>
#include <vector>
#include <thor/Particles.hpp>
namespace sz
{
class TextureAsset;
class ShaderAsset;
struct BatchData
{
BatchData() : texture(NULL), shader(NULL), particles(NULL) {}
BatchData(size_t layer, const sf::Texture*, const sf::Shader*, sf::BlendMode);
BatchData(size_t layer, thor::ParticleSystem*, const sf::Shader*, sf::BlendMode);
BatchData(size_t layer, sf::Text*, sf::BlendMode);
size_t layer;
sf::VertexArray vertices;
const sf::Texture* texture;
const sf::Shader* shader;
sf::BlendMode blendmode;
thor::ParticleSystem* particles;
sf::Text text;
enum Type
{
Vertices,
Particles,
Text
} type;
};
typedef std::vector<BatchData> BatchDataList;
class SpriteBatch
{
public:
SpriteBatch();
~SpriteBatch();
static void init();
static void clear();
//static void append(const sf::Vertex* quad, sf::Uint32 layer, TextureAsset* texture, ShaderAsset* shader, sf::BlendMode blendmode);
static void append(const sf::Vertex* quad, sf::Uint32 layer, const sf::Texture* texture, ShaderAsset* shader, sf::BlendMode blendmode);
static void append(thor::ParticleSystem* system, sf::Uint32 layer, ShaderAsset* shader, sf::BlendMode blendmode);
static void append(sf::Text* text, sf::Uint32 layer, sf::BlendMode blendmode);
static void draw(sf::RenderTarget&);
private:
static BatchDataList m_batchData;
};
}
#endif // SZEN_SPRITEBATCH_HPP
| 21.555556 | 137 | 0.717784 | Sonaza |
9b724925d691a7781cd8a990a5556961f5e913fb | 37,941 | cpp | C++ | src/Parser.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/Parser.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/Parser.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | #include "Parser.h"
#include "Tokenizer.h"
#include "malloc.h"
#include "config.h"
//#include <stdio.h>
//#include "string.h"
#define REDUCE 0x20000000
#define SHIFT 0x40000000
#define ACCEPT 0x60000000
#define ACTION_MASK 0x60000000
struct Rule {
ScriptTokenType result;
NodeType nodeType;
unsigned char numTerms:4;
unsigned char operatorPos:4;
ScriptTokenType terms[8];
};
const Rule rules[] = {
{PARSER_SCRIPT, NODE_NONE, 2, 1, PARSER_FUNCTION_LIST, TOKEN_END},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 2, 1, PARSER_FUNCTION, PARSER_FUNCTION_LIST},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_FUNCTION},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 2, 1, PARSER_STRUCT, PARSER_FUNCTION_LIST},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_STRUCT},
//{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_RAW_STRUCT},
/*
{PARSER_RAW_STRUCT, NODE_RAW_STRUCT, 6, 1, TOKEN_RAW, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, PARSER_RAW_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT},
{PARSER_RAW_STRUCT_LIST, NODE_RAW_STRUCT_LIST, 3, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_SEMICOLON, PARSER_STRUCT_LIST},
{PARSER_RAW_STRUCT_LIST, NODE_RAW_STRUCT_LIST, 2, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_SEMICOLON},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 2, 0, PARSER_TYPE, TOKEN_IDENTIFIER},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 3, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_COMMA, TOKEN_IDENTIFIER},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 5, 0, PARSER_TYPE, TOKEN_ TOKEN_IDENTIFIER},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 6, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_COMMA, TOKEN_IDENTIFIER},
{PARSER_TYPE, NODE_INT_TYPE, 1, 0, TOKEN_INT_TYPE},
{PARSER_TYPE, NODE_FLOAT_TYPE, 1, 0, TOKEN_FLOAT_TYPE},
{PARSER_TYPE, NODE_DOUBLE_TYPE, 1, 0, TOKEN_DOUBLE_TYPE},
{PARSER_TYPE, NODE_CHAR_TYPE, 1, 0, TOKEN_CHAR_TYPE},
{PARSER_TYPE, NODE_STRING_TYPE, 1, 0, TOKEN_STRING_TYPE},
//*/
{PARSER_STRUCT, NODE_STRUCT, 5, 0, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, PARSER_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT},
{PARSER_STRUCT, NODE_STRUCT, 7, 0, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_EXTENDS, PARSER_IDENTIFIER_LIST, TOKEN_OPEN_CODE, PARSER_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT},
//{PARSER_STRUCT, NODE_STRUCT, 4, 1, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, TOKEN_CLOSE_CODE},
{PARSER_STRUCT_LIST, NODE_STRUCT_LIST, 2, 1, PARSER_STRUCT_ENTRY, PARSER_STRUCT_LIST},
{PARSER_STRUCT_LIST, NODE_STRUCT_LIST, 1, 0, PARSER_STRUCT_ENTRY},
{PARSER_STRUCT_ENTRY, NODE_NONE, 3, 1, TOKEN_VAR, PARSER_STRUCT_VALUES, TOKEN_END_STATEMENT},
{PARSER_STRUCT_ENTRY, NODE_NONE, 1, 0, PARSER_FUNCTION},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 1, 0, TOKEN_IDENTIFIER},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 2, 1, TOKEN_MOD, TOKEN_IDENTIFIER},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 3, 0, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_STRUCT_VALUES},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 4, 1, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_STRUCT_VALUES},
{PARSER_FUNCTION, NODE_IGNORE, 1, 0, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_FUNCTION_ALIAS, 5, 3, TOKEN_ALIAS, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_END_STATEMENT},
//{PARSER_FUNCTION, NODE_DLL32, 4, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
//{PARSER_FUNCTION, NODE_DLL64, 4, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL32, 5, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL64, 5, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL32, 4, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL64, 4, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL_FUNCTION, 6, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL_FUNCTION, 7, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_STRING, PARSER_DLL_ARG_LIST, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL_FUNCTION_SIMPLE, 7, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_STRING, PARSER_DLL_ARG_LIST, TOKEN_END_STATEMENT},
// Hack to allow 0 element list.
{PARSER_DLL_ARG_LIST, NODE_DLL_ARG, 2, 0, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_DLL_ARG_LIST, NODE_NONE, 3, 0, TOKEN_OPEN_PAREN, PARSER_DLL_ARGS, TOKEN_CLOSE_PAREN},
{PARSER_DLL_ARGS, NODE_DLL_ARGS, 1, 0, PARSER_DLL_ARG},
{PARSER_DLL_ARGS, NODE_DLL_ARGS, 3, 0, PARSER_DLL_ARG, TOKEN_COMMA, PARSER_DLL_ARGS},
{PARSER_DLL_ARG, NODE_DLL_ARG, 2, 0, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER},
{PARSER_DLL_ARG, NODE_DLL_ARG, 1, 0, TOKEN_IDENTIFIER},
{PARSER_FUNCTION, NODE_FUNCTION, 6, 0, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_IDENTIFIER_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
{PARSER_FUNCTION, NODE_FUNCTION, 5, 0, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
{PARSER_STRUCT_ENTRY, NODE_FUNCTION, 7, 0, TOKEN_FUNCTION, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_IDENTIFIER_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
{PARSER_STRUCT_ENTRY, NODE_FUNCTION, 6, 0, TOKEN_FUNCTION, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
//{PARSER_SIMPLE_EXPRESSION, NODE_FUNCTION_CALL, 3, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_REF_CALL, 8, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_CALL, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_REF_CALL, 6, 0, TOKEN_CALL, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_FUNCTION_CALL, 2, 0, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_FUNCTION_CALL, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_FUNCTION_CALL, 5, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_MOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_THIS_FUNCTION_CALL, 3, 0, TOKEN_MOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
//{PARSER_FUNCTION_CALL, NODE_FUNCTION_CALL, 4, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_LIST, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_MAKE_COPY, 4, 0, TOKEN_OPEN_PAREN, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_LIST_CREATE, 3, 0, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_EMPTY_LIST, 2, 0, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_LIST_ADD_NULL, 3, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_LIST_ADD, 4, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_APPEND, 5, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_LIST},
//{PARSER_LIST, NODE_LIST_ADD_NULL, 4, TOKEN_LIST, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN},
//{PARSER_LIST, NODE_LIST_CREATE, 4, TOKEN_LIST, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
//{PARSER_LIST, NODE_EMPTY_LIST, 3, TOKEN_LIST, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
// {PARSER_SIMPLE_EXPRESSION, NODE_DICT_TO_LIST, 4, 0, TOKEN_DICT_TO_LIST, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_NONE, 4, 0, TOKEN_OPEN_PAREN, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_LIST_ADD_NULL, 3, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_LIST_ADD, 4, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_APPEND, 5, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
//{PARSER_LIST, NODE_LIST_CREATE, 4, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, TOKEN_CLOSE_PAREN},
//{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 3, PARSER_LIST_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION},
{PARSER_LIST_EXPRESSION, NODE_LIST_ADD, 3, 0, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_LIST_ADD_NULL, 2, 0, PARSER_LIST_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_APPEND, 4, 0, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE_NULL, 1, 0, TOKEN_COMMA},
//{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 2, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 2, 0, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_NONE, 3, 0, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_DICT},
{PARSER_DICT, NODE_NONE, 4, 0, TOKEN_DICT, TOKEN_OPEN_PAREN, PARSER_DICT_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_DICT, NODE_NONE, 3, 0, TOKEN_OPEN_PAREN, PARSER_DICT_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_DICT, NODE_EMPTY_DICT, 3, 0, TOKEN_DICT, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_DICT_EXPRESSION, NODE_APPEND, 3, 0, PARSER_DICT_EXPRESSION, TOKEN_COMMA, PARSER_MINI_DICT_EXPRESSION},
{PARSER_DICT_EXPRESSION, NODE_NONE, 1, 0, PARSER_MINI_DICT_EXPRESSION},
{PARSER_MINI_DICT_EXPRESSION, NODE_DICT_CREATE, 3, 0, PARSER_EXPRESSION, TOKEN_COLON, PARSER_EXPRESSION},
{PARSER_MINI_DICT_EXPRESSION, NODE_MAKE_COPY, 2, 0, TOKEN_APPEND, PARSER_EXPRESSION},
{PARSER_SIMPLE_EXPRESSION, NODE_SIZE, 4, 0, TOKEN_SIZE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 3, 0, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_IDENTIFIER_LIST},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 1, 0, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 4, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_IDENTIFIER_LIST},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 2, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER},
{PARSER_STATEMENT_LIST, NODE_NONE, 1, 0, PARSER_STATEMENT},
{PARSER_STATEMENT_LIST, NODE_STATEMENT_LIST, 2, 0, PARSER_STATEMENT_LIST, PARSER_STATEMENT},
{PARSER_STATEMENT_BLOCK, NODE_NONE, 3, 0, TOKEN_OPEN_CODE, PARSER_STATEMENT_LIST, TOKEN_CLOSE_CODE},
{PARSER_STATEMENT_BLOCK, NODE_EMPTY, 2, 0, TOKEN_OPEN_CODE, TOKEN_CLOSE_CODE},
{PARSER_STATEMENT, NODE_DISCARD_LAST, 2, 0, PARSER_EXPRESSION, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_NONE, 1, 0, PARSER_STATEMENT_BLOCK},
//{PARSER_STATEMENT, NODE_DISCARD_FIRST, 1, PARSER_IF},
//{PARSER_STATEMENT, NODE_DISCARD_FIRST, 1, PARSER_IF_ELSE},
//{PARSER_STATEMENT, NODE_NONE, 1, PARSER_RETURN},
//{PARSER_RETURN, NODE_RETURN, 3, TOKEN_RETURN, PARSER_EXPRESSION, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_RETURN, 3, 0, TOKEN_RETURN, PARSER_EXPRESSION, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_RETURN, 2, 0, TOKEN_RETURN, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_BREAK, 2, 0, TOKEN_BREAK, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_CONTINUE, 2, 0, TOKEN_CONTINUE, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_FOR, 7, 0, TOKEN_FOR, TOKEN_OPEN_PAREN, PARSER_FOR_PRE_STATEMENT_LIST, PARSER_EXPRESSION, PARSER_FOR_POST_STATEMENT_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
{PARSER_FOR_PRE_STATEMENT_LIST, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT},
{PARSER_FOR_POST_STATEMENT_LIST, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT},
{PARSER_FOR_PRE_STATEMENT_LIST, NODE_DISCARD_LAST, 2, 0, PARSER_FOR_SUB_STATEMENT_LIST, TOKEN_END_STATEMENT},
{PARSER_FOR_POST_STATEMENT_LIST, NODE_DISCARD_LAST, 2, 0, TOKEN_END_STATEMENT, PARSER_FOR_SUB_STATEMENT_LIST},
{PARSER_FOR_SUB_STATEMENT_LIST, NODE_NONE, 1, 0, PARSER_EXPRESSION},
{PARSER_FOR_SUB_STATEMENT_LIST, NODE_DISCARD_FIRST, 3, 0, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_FOR_SUB_STATEMENT_LIST},
{PARSER_STATEMENT, NODE_WHILE, 5, 0, TOKEN_WHILE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
{PARSER_STATEMENT, NODE_DO_WHILE, 7, 0, TOKEN_DO, PARSER_STATEMENT, TOKEN_WHILE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, TOKEN_END_STATEMENT},
//{PARSER_IF, NODE_IF, 5, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
//{PARSER_IF_ELSE, NODE_IF_ELSE, 7, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT, TOKEN_ELSE, PARSER_STATEMENT},
{PARSER_STATEMENT, NODE_IF, 5, 0, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
{PARSER_STATEMENT, NODE_IF_ELSE, 7, 0, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT, TOKEN_ELSE, PARSER_STATEMENT},
{PARSER_EXPRESSION, NODE_NONE, 1, 0, PARSER_ASSIGN_EXPRESSION},
//{PARSER_ASSIGN_EXPRESSION, NODE_ASSIGN, 3, PARSER_LOCAL_INDEX_EXPRESSION, TOKEN_ASSIGN, PARSER_ADD_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_CONCAT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_CONCATE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MUL_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_MULE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_DIV_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_DIVE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MOD_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_MODE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_ADD_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ADDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_SUB_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_SUBE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_AND_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ANDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_XOR_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_XORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_OR_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_LSHIFT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_LSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_RSHIFT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_RSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_CONCAT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_CONCATE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MUL_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_MULE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_DIV_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_DIVE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MOD_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_MODE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_ADD_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ADDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_SUB_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_SUBE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_AND_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ANDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_XOR_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_XORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_OR_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_LSHIFT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_LSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_RSHIFT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_RSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ASSIGN, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ASSIGN, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_NONE, 1, 0, PARSER_APPEND_EXPRESSION},
{PARSER_APPEND_EXPRESSION, NODE_APPEND, 3, 1, PARSER_APPEND_EXPRESSION, TOKEN_APPEND, PARSER_BOOL_OR_EXPRESSION},
{PARSER_APPEND_EXPRESSION, NODE_NONE, 1, 0, PARSER_BOOL_OR_EXPRESSION},
{PARSER_BOOL_OR_EXPRESSION, NODE_BOOL_OR, 3, 1, PARSER_BOOL_OR_EXPRESSION, TOKEN_BOOL_OR, PARSER_BOOL_AND_EXPRESSION},
{PARSER_BOOL_OR_EXPRESSION, NODE_NONE, 1, 0, PARSER_BOOL_AND_EXPRESSION},
{PARSER_BOOL_AND_EXPRESSION, NODE_BOOL_AND, 3, 1, PARSER_BOOL_AND_EXPRESSION, TOKEN_BOOL_AND, PARSER_OR_EXPRESSION},
{PARSER_BOOL_AND_EXPRESSION, NODE_NONE, 1, 0, PARSER_OR_EXPRESSION},
{PARSER_OR_EXPRESSION, NODE_OR, 3, 1, PARSER_OR_EXPRESSION, TOKEN_OR, PARSER_XOR_EXPRESSION},
{PARSER_OR_EXPRESSION, NODE_NONE, 1, 0, PARSER_XOR_EXPRESSION},
{PARSER_XOR_EXPRESSION, NODE_XOR, 3, 1, PARSER_XOR_EXPRESSION, TOKEN_XOR, PARSER_AND_EXPRESSION},
{PARSER_XOR_EXPRESSION, NODE_NONE, 1, 0, PARSER_AND_EXPRESSION},
{PARSER_AND_EXPRESSION, NODE_AND, 3, 1, PARSER_AND_EXPRESSION, TOKEN_AND, PARSER_EQUALS_EXPRESSION},
{PARSER_AND_EXPRESSION, NODE_NONE, 1, 0, PARSER_EQUALS_EXPRESSION},
{PARSER_EQUALS_EXPRESSION, NODE_E, 3, 1, PARSER_EQUALS_EXPRESSION, TOKEN_E, PARSER_COMPARE_EXPRESSION},
{PARSER_EQUALS_EXPRESSION, NODE_NE, 3, 1, PARSER_EQUALS_EXPRESSION, TOKEN_NE, PARSER_COMPARE_EXPRESSION},
{PARSER_EQUALS_EXPRESSION, NODE_NONE, 1, 0, PARSER_COMPARE_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_L, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_L, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_LE, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_LE, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_G, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_G, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_GE, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_GE, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_NONE, 1, 0, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_E, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_NE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCINE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_L, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIL, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_LE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCILE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_G, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIG, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_GE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIGE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_E, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_NE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SNE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_L, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SL, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_LE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SLE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_G, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SG, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_GE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SGE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_NONE, 1, 0, PARSER_CONCAT_EXPRESSION},
{PARSER_CONCAT_EXPRESSION, NODE_CONCAT_STRING, 3, 1, PARSER_CONCAT_EXPRESSION, TOKEN_CONCAT, PARSER_SHIFT_EXPRESSION},
{PARSER_CONCAT_EXPRESSION, NODE_NONE, 1, 0, PARSER_SHIFT_EXPRESSION},
{PARSER_SHIFT_EXPRESSION, NODE_LSHIFT, 3, 1, PARSER_SHIFT_EXPRESSION, TOKEN_LSHIFT, PARSER_ADD_EXPRESSION},
{PARSER_SHIFT_EXPRESSION, NODE_RSHIFT, 3, 1, PARSER_SHIFT_EXPRESSION, TOKEN_RSHIFT, PARSER_ADD_EXPRESSION},
{PARSER_SHIFT_EXPRESSION, NODE_NONE, 1, 0, PARSER_ADD_EXPRESSION},
{PARSER_ADD_EXPRESSION, NODE_ADD, 3, 1, PARSER_ADD_EXPRESSION, TOKEN_ADD, PARSER_MUL_EXPRESSION},
{PARSER_ADD_EXPRESSION, NODE_SUB, 3, 1, PARSER_ADD_EXPRESSION, TOKEN_SUB, PARSER_MUL_EXPRESSION},
{PARSER_ADD_EXPRESSION, NODE_NONE, 1, 0, PARSER_MUL_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_MUL, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_MUL, PARSER_PREFIX_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_MOD, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_MOD, PARSER_PREFIX_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_DIV, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_DIV, PARSER_PREFIX_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_NONE, 1, 0, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NOT, 2, 0, TOKEN_NOT, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NEG, 2, 0, TOKEN_SUB, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_BIN_NEG, 2, 0, TOKEN_TILDE, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NONE, 2, 0, TOKEN_ADD, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_EXPRESSION},
//{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, PARSER_FUNCTION_CALL},
{PARSER_SIMPLE_EXPRESSION, NODE_INT, 1, 0, TOKEN_INT},
{PARSER_SIMPLE_EXPRESSION, NODE_DOUBLE, 1, 0, TOKEN_DOUBLE},
//{PARSER_SIMPLE_EXPRESSION, NODE_IDENTIFIER, 1, TOKEN_IDENTIFIER},
{PARSER_SIMPLE_EXPRESSION, NODE_STRING, 1, 0, TOKEN_STRING},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 3, 1, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_POSTMOD_EXPRESSION},
//{PARSER_SIMPLE_EXPRESSION2, NODE_NONE, 1, 0, PARSER_SIMPLE_EXPRESSION},
{PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_PREMOD_EXPRESSION},
{PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_SIMPLE_POST_INC, 2, 1, PARSER_SIMPLE_POSTMOD_EXPRESSION, TOKEN_INC},
{PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_SIMPLE_POST_DEC, 2, 1, PARSER_SIMPLE_POSTMOD_EXPRESSION, TOKEN_DEC},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_DEREFERENCE_EXPRESSION},
{PARSER_DEREFERENCE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_DEREFERENCE_EXPRESSION},
{PARSER_DEREFERENCE_EXPRESSION, NODE_DEREFERENCE, 1, 0, PARSER_IDENTIFIER_EXPRESSION},
{PARSER_DEREFERENCE_EXPRESSION, NODE_SUB_REFERENCE, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
{PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_DEREFERENCE, 1, 0, PARSER_IDENTIFIER_EXPRESSION},
{PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_SIMPLE_PRE_INC, 2, 0, TOKEN_INC, PARSER_SIMPLE_PREMOD_EXPRESSION},
{PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_SIMPLE_PRE_DEC, 2, 0, TOKEN_DEC, PARSER_SIMPLE_PREMOD_EXPRESSION},
//{PARSER_SIMPLE_EXPRESSION, NODE_DEREFERENCE, 1, PARSER_IDENTIFIER_EXPRESSION},
//{PARSER_INDEX_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_INDEX_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_SIMPLE_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_SIMPLE_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_ELEMENT_PREMOD_IDENTIFIER, NODE_NONE, 1, PARSER_SIMPLE_EXPRESSION},
//{PARSER_ELEMENT_PREPREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_ELEMENT_PREPREMOD_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_ELEMENT_PREPREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_ELEMENT_PREMOD_IDENTIFIER, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_ELEMENT_PREMOD_IDENTIFIER, NODE_DEREFERENCE, 1, PARSER_IDENTIFIER_EXPRESSION},
{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_ELEMENT_PRE_INC, 2, 0, TOKEN_INC, PARSER_ELEMENT_PREMOD_EXPRESSION},
{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_ELEMENT_PRE_DEC, 2, 0, TOKEN_DEC, PARSER_ELEMENT_PREMOD_EXPRESSION},
{PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_NONE, 1, 0, PARSER_ELEMENT_PREMOD_EXPRESSION},
{PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_ELEMENT_POST_INC, 2, 1, PARSER_ELEMENT_POSTMOD_EXPRESSION, TOKEN_INC},
{PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_ELEMENT_POST_DEC, 2, 1, PARSER_ELEMENT_POSTMOD_EXPRESSION, TOKEN_DEC},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_ELEMENT_POSTMOD_EXPRESSION},
//{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_NONE, 1, PARSER_ELEMENT_PREPREMOD_EXPRESSION},
//{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{SIMPLE_EXPRESSION, NODE_DEREFERENCE, 4, PARSER_IDENTIFIER_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 3, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 4, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_MOD, TOKEN_IDENTIFIER},
//{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 3, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_THIS_REFERENCE, 2, 0, TOKEN_MOD, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_LOCAL_REFERENCE, 2, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_GLOBAL_REFERENCE, 1, 0, TOKEN_IDENTIFIER},
//{PARSER_INDEX_EXPRESSION, NODE_REFERENCE, 4, PARSER_INDEX_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//*/
};
#define NUM_RULES (sizeof(rules)/sizeof(Rule))
struct Item {
int transition;
int rule;
int position;
};
struct ItemSet {
int numItems;
Item items[1];
};
int CalcClosure(ItemSet **s, int *mem, int id) {
int k = s[0]->numItems;
int maxSize = k;
int numCare = k;
for (int j=0; j<numCare; j++) {
int position = s[0]->items[j].position;
const Rule *rule = &rules[s[0]->items[j].rule];
if (position >= rule->numTerms) continue;
int term = rule->terms[position];
for (int i=1; i<NUM_RULES; i++) {
if (term != rules[i].result)
continue;
if (mem[i] == id)
break;
if (k < maxSize || (srealloc(s[0], sizeof(ItemSet)+sizeof(Item)*(maxSize+16)) && (maxSize+=16))) {
mem[i] = id;
int q;
for (q = 0; q<numCare; q++) {
if (rules[s[0]->items[q].rule].terms[s[0]->items[q].position] == rules[i].terms[0]) {
break;
}
}
int out = k;
if (q == numCare && rules[i].terms[0] > TOKEN_END) {
s[0]->items[k] = s[0]->items[numCare];
out = numCare++;
}
s[0]->items[out].rule = i;
s[0]->items[out].position = 0;
s[0]->items[out].transition = -1;
s[0]->numItems = ++k;
}
}
}
return 1;
}
void CleanupTree(ParseTree *t) {
if (t->val) free(t->val);
for (int i=0; i<t->numChildren; i++) {
if (t->children[i])
CleanupTree(t->children[i]);
}
free(t);
}
void ParseError(Token *token) {
errorPrintf(2, "Parse error, line %i:\r\n", token->line);
errors++;
DisplayErrorLine(token->start, token->pos);
}
int *actionTable = 0;
ParseTree * ParseScript(Token *tokens, int numTokens) {
int i;
if (numTokens == 1) {
CleanupTokens(tokens, numTokens);
return 0;
}
if (!actionTable) {
int numSets = 0;
ItemSet **set = (ItemSet**) malloc(sizeof(ItemSet*)*1000);
ItemSet **newSets = (ItemSet**) malloc(sizeof(ItemSet*)*1000);
if (!set || !newSets) {
free(set);
free(newSets);
return 0;
}
int changed = 1;
int *followSets = (int*) calloc(1, PARSER_NONE * sizeof(int) * PARSER_NONE);
int *firstSets = (int*) calloc(1, PARSER_NONE * sizeof(int) * PARSER_NONE);
for (i=0; i<PARSER_SCRIPT; i++) {
firstSets[PARSER_NONE*i+i] = 1;
}
while (changed) {
changed = 0;
for (int r = 0; r<NUM_RULES; r++) {
int R = rules[r].result;
int F = rules[r].terms[0];
for (i=0; i<PARSER_NONE;i++) {
if (firstSets[F*PARSER_NONE+i] && !firstSets[R*PARSER_NONE+i]) {
firstSets[R*PARSER_NONE+i] = 1;
changed = 1;
}
}
}
}
changed = 1;
while (changed) {
changed = 0;
for (int r = 0; r<NUM_RULES; r++) {
for (int p=0; p<rules[r].numTerms-1; p++) {
ScriptTokenType F = rules[r].terms[p];
ScriptTokenType S = rules[r].terms[p+1];
for (i=0; i<PARSER_NONE;i++) {
if (firstSets[S*PARSER_NONE+i] && !followSets[F*PARSER_NONE+i]) {
followSets[F*PARSER_NONE+i] = 1;
changed = 1;
}
}
}
ScriptTokenType F = rules[r].terms[rules[r].numTerms-1];
ScriptTokenType S = rules[r].result;
for (i=0; i<PARSER_NONE;i++) {
if (followSets[S*PARSER_NONE+i] && !followSets[F*PARSER_NONE+i]) {
followSets[F*PARSER_NONE+i] = 1;
changed = 1;
}
}
}
}
set[numSets++] = (ItemSet *) malloc(sizeof(ItemSet));
set[0]->numItems = 1;
set[0]->items[0].position = 0;
set[0]->items[0].rule = 0;
int closureId = 0;
int closureNotes[sizeof(rules) / sizeof(Rule)];
for (i=0; i<sizeof(closureNotes)/sizeof(int);i++)
closureNotes[i] = -1;
//memset(closureNotes, -1, sizeof(closureNotes));
CalcClosure(&set[0], closureNotes, closureId++);
for (i=0; i<numSets; i++) {
int numNewSets = 0;
int j;
for (j=0; j<set[i]->numItems; j++) {
set[i]->items[j].transition = -1;
if (set[i]->items[j].position != rules[set[i]->items[j].rule].numTerms) {
int q;
for (q=0; q<numNewSets; q++) {
if (rules[set[i]->items[j].rule].terms[set[i]->items[j].position] == rules[newSets[q]->items[0].rule].terms[newSets[q]->items[0].position-1]) {
srealloc(newSets[q] , sizeof(ItemSet) + sizeof(Item) * newSets[q]->numItems);
break;
}
}
if (q==numNewSets) {
newSets[q] = (ItemSet*) malloc(sizeof(ItemSet));
newSets[q]->numItems = 0;
numNewSets++;
}
newSets[q]->items[newSets[q]->numItems].position = set[i]->items[j].position+1;
newSets[q]->items[newSets[q]->numItems].rule = set[i]->items[j].rule;
newSets[q]->items[newSets[q]->numItems].transition = j;
newSets[q]->numItems++;
}
}
for (j=0; j<numNewSets; j++) {
CalcClosure(&newSets[j], closureNotes, closureId++);
int q = 0;
for (q = 0; q<numSets; q++) {
int match = 0;
if (set[q]->numItems == newSets[j]->numItems)
while (match < newSets[j]->numItems) {
int f;
for (f = 0; f<set[q]->numItems; f++) {
if (set[q]->items[f].rule == newSets[j]->items[match].rule &&
set[q]->items[f].position == newSets[j]->items[match].position)
break;
}
if (f == set[q]->numItems) break;
match++;
}
if (match == newSets[j]->numItems) break;
}
for (int w=0; w<newSets[j]->numItems; w++)
if (newSets[j]->items[w].transition >= 0)
set[i]->items[newSets[j]->items[w].transition].transition = q;
if (q<numSets) {
free(newSets[j]);
}
else {
set[numSets++] = newSets[j];
}
}
}
free(newSets);
actionTable = (int*) malloc(sizeof(int) * numSets*PARSER_NONE);
for (i=numSets*PARSER_NONE-1; i>=0;i--) {
actionTable[i] = -1;
}
for (i=0; i<numSets; i++) {
int reduce = 0;
for (int w=0; w<set[i]->numItems; w++) {
if (set[i]->items[w].position < rules[set[i]->items[w].rule].numTerms) {
int term = rules[set[i]->items[w].rule].terms[set[i]->items[w].position];
if (actionTable[i*PARSER_NONE+term]>=0&& (actionTable[i*PARSER_NONE+term]&0xFFFFFF)-set[i]->items[w].transition !=0) {
i=i;
}
actionTable[i*PARSER_NONE+term] = set[i]->items[w].transition;
if (term < PARSER_SCRIPT) {
if (term != TOKEN_END)
actionTable[i*PARSER_NONE+term] |= SHIFT;
else
actionTable[i*PARSER_NONE+term] = ACCEPT;
}
/*
if (rules[set[i]->items[w].rule].terms[set[i]->items[w].position] < S) {
actionTable[i*PARSER_NONE+set[i]->items[w].rule] = set[i]->items[w].transition;
else
actionTable[i*PARSER_NONE+set[i]->items[w].rule] |= SHIFT;
}//*/
}
else {
/*if (reduce && reduce != set[i]->items[w].rule) {
reduce = reduce;
}
reduce = set[i]->items[w].rule;
//*/
reduce = set[i]->items[w].rule;
for (int x = 0; x<PARSER_SCRIPT; x++) {
if (followSets[rules[reduce].result*PARSER_NONE+x]) {
if (actionTable[x+i*PARSER_NONE] == -1) {
actionTable[x+i*PARSER_NONE] = REDUCE | reduce;
}
else {
i=i;
}
}
}
}
}
/*if (reduce) {
for (int w = 0; w<PARSER_SCRIPT; w++) {
if (actionTable[w+i*PARSER_NONE] == -1) {
actionTable[w+i*PARSER_NONE] = REDUCE | reduce;
}
}
}*/
}
free(followSets);
free(firstSets);
for (i=0; i<numSets; i++) {
free(set[i]);
}
free(set);
}
int maxStackSize = 1000;
int *stack = (int*) malloc(sizeof(int) * 1000);
//int output[1000];
stack[0] = 0;
//int outputLen = 0;
int stackSize = 1;
int pos = 0;
int accept = 0;
int ParseTrees = 0;
int maxParseTrees = 1000;
ParseTree **tree = (ParseTree**) malloc(sizeof(ParseTree*) * 1000);
int error = 0;
while (pos < numTokens && stackSize > 0) {
int row = stack[stackSize-1];
ScriptTokenType token = tokens[pos].type;
int i = actionTable[token+row*PARSER_NONE];
if (i==-1) {
if (pos && !tokens[pos].line) {
ParseError(tokens+pos-1);
}
else {
ParseError(tokens+pos);
}
error = 1;
break;
}
else if ((i&ACTION_MASK) == SHIFT) {
i &= ~SHIFT;
if (stackSize == maxStackSize) {
if (!srealloc(stack, sizeof(int) * (maxStackSize*=2))) {
ParseError(tokens+pos);
error = 1;
break;
}
}
if (ParseTrees == maxParseTrees) {
if (!srealloc(tree, sizeof(ParseTree*) * (maxParseTrees*=2))) {
ParseError(tokens+pos);
error = 1;
break;
}
}
stack[stackSize++] = i;
tree[ParseTrees] = (ParseTree*) calloc(1, sizeof(ParseTree));
if (!tree[ParseTrees]) {
ParseError(tokens+pos);
error = 1;
break;
}
{
tree[ParseTrees]->line = tokens[pos].line;
tree[ParseTrees]->pos = tokens[pos].pos;
tree[ParseTrees]->start = tokens[pos].start;
}
// Temporary node. Will be eaten by another.
tree[ParseTrees]->type = NODE_LEAF;
tree[ParseTrees]->numChildren = 0;
tree[ParseTrees]->intVal = tokens[pos].intVal;
tree[ParseTrees++]->val = tokens[pos].val;
tokens[pos].val = 0;
pos++;
}
else if ((i&ACTION_MASK) == REDUCE) {
i &= ~REDUCE;
// output[outputLen++] = i;
ParseTree *children[5] = {0,0,0,0,0};
int numChildren = 0;
int nline;
unsigned char *npos;
unsigned char *nstart;
for (int j = 0; j<rules[i].numTerms; j++) {
if (j == rules[i].operatorPos) {
nline = tree[ParseTrees - rules[i].numTerms+j]->line;
npos = tree[ParseTrees - rules[i].numTerms+j]->pos;
nstart = tree[ParseTrees - rules[i].numTerms+j]->start;
}
if (rules[i].terms[j] <= TOKEN_IDENTIFIER || rules[i].terms[j]>=TOKEN_END) {
children[numChildren++] = tree[ParseTrees - rules[i].numTerms+j];
}
else {
free(tree[ParseTrees - rules[i].numTerms+j]);
tree[ParseTrees - rules[i].numTerms+j] = 0;
}
}
ParseTrees -= rules[i].numTerms;
if (rules[i].nodeType == NODE_NONE) {
tree[ParseTrees] = children[0];
}
else {
if (numChildren && children[0]->type == NODE_LEAF) {
tree[ParseTrees] = children[0];
}
else {
tree[ParseTrees] = (ParseTree*) calloc(1, sizeof(ParseTree));
if (!tree[ParseTrees]) {
ParseError(tokens+pos);
error = 1;
break;
}
tree[ParseTrees]->children[0] = children[0];
}
tree[ParseTrees]->numChildren = numChildren;
tree[ParseTrees]->children[1] = children[1];
tree[ParseTrees]->children[2] = children[2];
tree[ParseTrees]->children[3] = children[3];
tree[ParseTrees]->children[4] = children[4];
tree[ParseTrees]->type = rules[i].nodeType;
}
tree[ParseTrees]->line = nline;
tree[ParseTrees]->pos = npos;
tree[ParseTrees]->start = nstart;
ParseTrees++;
stackSize -= rules[i].numTerms;
if (stackSize <= 0) {
ParseError(tokens+pos);
error = 1;
break;
}
else {
int w = rules[i].result;
int t = actionTable[stack[stackSize-1]*PARSER_NONE + w];
if (t >= 0 && t < 0x1000000) {
stack[stackSize++] = t;
}
else {
ParseError(tokens+pos);
error = 1;
break;
}
}
}
else if (i == ACCEPT) {
accept = 1;
break;
}
else {
ParseError(tokens+pos);
error = 1;
break;
}
}
free(stack);
CleanupTokens(tokens, numTokens);
if (error) {
for (int i=0; i<ParseTrees; i++) {
CleanupTree(tree[i]);
}
free(tree);
return 0;
}
ParseTree *out = tree[0];
free(tree);
return out;
}
void CleanupParser() {
free(actionTable);
actionTable = 0;
}
| 49.791339 | 213 | 0.760048 | MichaelMCE |
9b7950992e4d849dbac86ca9d939085a949e337a | 19,891 | cpp | C++ | cplus/libcfint/CFIntSubProjectEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/CFIntSubProjectEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/CFIntSubProjectEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | // Description: C++18 edit object instance implementation for CFInt SubProject.
/*
* org.msscf.msscf.CFInt
*
* Copyright (c) 2020 Mark Stephen Sobkow
*
* MSS Code Factory CFInt 2.13 Internet Essentials
*
* Copyright 2020-2021 Mark Stephen Sobkow
*
* This file is part of MSS Code Factory.
*
* MSS Code Factory is available under dual commercial license from Mark Stephen
* Sobkow, or under the terms of the GNU General Public License, Version 3
* or later.
*
* MSS Code Factory is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MSS Code Factory 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 MSS Code Factory. If not, see <https://www.gnu.org/licenses/>.
*
* Donations to support MSS Code Factory can be made at
* https://www.paypal.com/paypalme2/MarkSobkow
*
* Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing.
*
* Manufactured by MSS Code Factory 2.12
*/
#include <cflib/ICFLibPublic.hpp>
using namespace std;
#include <cfint/ICFIntPublic.hpp>
#include <cfintobj/ICFIntObjPublic.hpp>
#include <cfintobj/CFIntSubProjectObj.hpp>
#include <cfintobj/CFIntSubProjectEditObj.hpp>
namespace cfint {
const std::string CFIntSubProjectEditObj::CLASS_NAME( "CFIntSubProjectEditObj" );
CFIntSubProjectEditObj::CFIntSubProjectEditObj( cfint::ICFIntSubProjectObj* argOrig )
: ICFIntSubProjectEditObj()
{
static const std::string S_ProcName( "CFIntSubProjectEditObj-construct" );
static const std::string S_OrigBuff( "origBuff" );
orig = argOrig;
cfint::CFIntSubProjectBuff* origBuff = orig->getBuff();
if( origBuff == NULL ) {
throw cflib::CFLibNullArgumentException( CLASS_NAME,
S_ProcName,
0,
S_OrigBuff );
}
buff = dynamic_cast<cfint::CFIntSubProjectBuff*>( origBuff->clone() );
}
CFIntSubProjectEditObj::~CFIntSubProjectEditObj() {
orig = NULL;
if( buff != NULL ) {
delete buff;
buff = NULL;
}
}
const std::string& CFIntSubProjectEditObj::getClassName() const {
return( CLASS_NAME );
}
cfsec::ICFSecSecUserObj* CFIntSubProjectEditObj::getCreatedBy() {
if( createdBy == NULL ) {
createdBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getSubProjectBuff()->getCreatedByUserId() );
}
return( createdBy );
}
const std::chrono::system_clock::time_point& CFIntSubProjectEditObj::getCreatedAt() {
return( getSubProjectBuff()->getCreatedAt() );
}
cfsec::ICFSecSecUserObj* CFIntSubProjectEditObj::getUpdatedBy() {
if( updatedBy == NULL ) {
updatedBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getSubProjectBuff()->getUpdatedByUserId() );
}
return( updatedBy );
}
const std::chrono::system_clock::time_point& CFIntSubProjectEditObj::getUpdatedAt() {
return( getSubProjectBuff()->getUpdatedAt() );
}
void CFIntSubProjectEditObj::setCreatedBy( cfsec::ICFSecSecUserObj* value ) {
createdBy = value;
if( value != NULL ) {
getSubProjectEditBuff()->setCreatedByUserId( value->getRequiredSecUserIdReference() );
}
}
void CFIntSubProjectEditObj::setCreatedAt( const std::chrono::system_clock::time_point& value ) {
getSubProjectEditBuff()->setCreatedAt( value );
}
void CFIntSubProjectEditObj::setUpdatedBy( cfsec::ICFSecSecUserObj* value ) {
updatedBy = value;
if( value != NULL ) {
getSubProjectEditBuff()->setUpdatedByUserId( value->getRequiredSecUserIdReference() );
}
}
void CFIntSubProjectEditObj::setUpdatedAt( const std::chrono::system_clock::time_point& value ) {
getSubProjectEditBuff()->setUpdatedAt( value );
}
const classcode_t CFIntSubProjectEditObj::getClassCode() const {
return( cfint::CFIntSubProjectBuff::CLASS_CODE );
}
bool CFIntSubProjectEditObj::implementsClassCode( const classcode_t value ) const {
if( value == cfint::CFIntSubProjectBuff::CLASS_CODE ) {
return( true );
}
else {
return( false );
}
}
std::string CFIntSubProjectEditObj::toString() {
static const std::string S_Space( " " );
static const std::string S_Preamble( "<CFIntSubProjectEditObj" );
static const std::string S_Postamble( "/>" );
static const std::string S_Revision( "Revision" );
static const std::string S_CreatedBy( "CreatedBy" );
static const std::string S_CreatedAt( "CreatedAt" );
static const std::string S_UpdatedBy( "UpdatedBy" );
static const std::string S_UpdatedAt( "UpdatedAt" );
static const std::string S_TenantId( "TenantId" );
static const std::string S_Id( "Id" );
static const std::string S_TopProjectId( "TopProjectId" );
static const std::string S_Name( "Name" );
static const std::string S_Description( "Description" );
std::string ret( S_Preamble );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_Revision, CFIntSubProjectEditObj::getRequiredRevision() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_CreatedBy, CFIntSubProjectEditObj::getCreatedBy()->toString() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_CreatedAt, CFIntSubProjectEditObj::getCreatedAt() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_UpdatedBy, CFIntSubProjectEditObj::getUpdatedBy()->toString() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_UpdatedAt, CFIntSubProjectEditObj::getUpdatedAt() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_TenantId, CFIntSubProjectEditObj::getRequiredTenantId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_Id, CFIntSubProjectEditObj::getRequiredId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_TopProjectId, CFIntSubProjectEditObj::getRequiredTopProjectId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Name, CFIntSubProjectEditObj::getRequiredName() ) );
if( ! CFIntSubProjectEditObj::isOptionalDescriptionNull() ) {
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Description, CFIntSubProjectEditObj::getOptionalDescriptionValue() ) );
}
ret.append( S_Postamble );
return( ret );
}
int32_t CFIntSubProjectEditObj::getRequiredRevision() const {
return( buff->getRequiredRevision() );
}
void CFIntSubProjectEditObj::setRequiredRevision( int32_t value ) {
getSubProjectEditBuff()->setRequiredRevision( value );
}
std::string CFIntSubProjectEditObj::getObjName() {
std::string objName( CLASS_NAME ); objName;
objName.clear();
objName.append( getRequiredName() );
return( objName );
}
const std::string CFIntSubProjectEditObj::getGenDefName() {
return( cfint::CFIntSubProjectBuff::GENDEFNAME );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getScope() {
cfint::ICFIntTopProjectObj* scope = getRequiredContainerParentTPrj();
return( scope );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getObjScope() {
cfint::ICFIntTopProjectObj* scope = getRequiredContainerParentTPrj();
return( scope );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getObjQualifier( const classcode_t* qualifyingClass ) {
cflib::ICFLibAnyObj* container = this;
if( qualifyingClass != NULL ) {
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
break;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
break;
}
else if( container->implementsClassCode( *qualifyingClass ) ) {
break;
}
container = container->getObjScope();
}
}
else {
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
break;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
break;
}
container = container->getObjScope();
}
}
return( container );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getNamedObject( const classcode_t* qualifyingClass, const std::string& objName ) {
cflib::ICFLibAnyObj* topContainer = getObjQualifier( qualifyingClass );
if( topContainer == NULL ) {
return( NULL );
}
cflib::ICFLibAnyObj* namedObject = topContainer->getNamedObject( objName );
return( namedObject );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getNamedObject( const std::string& objName ) {
std::string nextName;
std::string remainingName;
cflib::ICFLibAnyObj* subObj = NULL;
cflib::ICFLibAnyObj* retObj;
int32_t nextDot = objName.find( '.' );
if( nextDot >= 0 ) {
nextName = objName.substr( 0, nextDot );
remainingName = objName.substr( nextDot + 1 );
}
else {
nextName.clear();
nextName.append( objName );
remainingName.clear();
}
if( subObj == NULL ) {
subObj = dynamic_cast<ICFIntSchemaObj*>( getSchema() )->getMajorVersionTableObj()->readMajorVersionByLookupNameIdx( getRequiredTenantId(),
getRequiredId(),
nextName,
false );
}
if( remainingName.length() <= 0 ) {
retObj = subObj;
}
else if( subObj == NULL ) {
retObj = NULL;
}
else {
retObj = subObj->getNamedObject( remainingName );
}
return( retObj );
}
std::string CFIntSubProjectEditObj::getObjQualifiedName() {
const static std::string S_Dot( "." );
std::string qualName( getObjName() );
cflib::ICFLibAnyObj* container = getObjScope();
std::string containerName;
std::string buildName;
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->implementsClassCode( cfsec::CFSecTenantBuff::CLASS_CODE ) ) {
container = NULL;
}
else {
containerName = container->getObjName();
buildName.clear();
buildName.append( containerName );
buildName.append( S_Dot );
buildName.append( qualName );
qualName.clear();
qualName.append( buildName );
container = container->getObjScope();
}
}
return( qualName );
}
std::string CFIntSubProjectEditObj::getObjFullName() {
const static std::string S_Dot( "." );
std::string fullName = getObjName();
cflib::ICFLibAnyObj* container = getObjScope();
std::string containerName;
std::string buildName;
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
container = NULL;
}
else {
containerName = container->getObjName();
buildName.clear();
buildName.append( containerName );
buildName.append( S_Dot );
buildName.append( fullName );
fullName.clear();
fullName.append( buildName );
container = container->getObjScope();
}
}
return( fullName );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::realize() {
// We realize this so that it's buffer will get copied to orig during realization
cfint::ICFIntSubProjectObj* retobj = getSchema()->getSubProjectTableObj()->realizeSubProject( dynamic_cast<cfint::ICFIntSubProjectObj*>( this ) );
return( retobj );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::read( bool forceRead ) {
cfint::ICFIntSubProjectObj* retval = getOrigAsSubProject()->read( forceRead );
if( retval != orig ) {
throw cflib::CFLibUsageException( CLASS_NAME,
"read",
"retval != orig" );
}
copyOrigToBuff();
return( retval );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::create() {
cfint::ICFIntSubProjectObj* retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getSubProjectTableObj()->createSubProject( this );
// Note that this instance is usually discarded during the creation process,
// and retobj now references the cached instance of the created object.
return( retobj );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::update() {
getSchema()->getSubProjectTableObj()->updateSubProject( this );
return( NULL );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::deleteInstance() {
static const std::string S_MethodName( "deleteInstance" );
static const std::string S_CannotDeleteNewInstance( "Cannot delete a new instance" );
if( getIsNew() ) {
throw cflib::CFLibUsageException( CLASS_NAME, S_MethodName, S_CannotDeleteNewInstance );
}
getSchema()->getSubProjectTableObj()->deleteSubProject( this );
return( NULL );
}
cfint::ICFIntSubProjectTableObj* CFIntSubProjectEditObj::getSubProjectTable() {
return( orig->getSchema()->getSubProjectTableObj() );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::getEdit() {
return( this );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::getSubProjectEdit() {
return( (cfint::ICFIntSubProjectEditObj*)this );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::beginEdit() {
static const std::string S_ProcName( "beginEdit" );
static const std::string S_Message( "Cannot edit an edition" );
throw cflib::CFLibUsageException( CLASS_NAME,
S_ProcName,
S_Message );
}
void CFIntSubProjectEditObj::endEdit() {
orig->endEdit();
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::getOrig() {
return( orig );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::getOrigAsSubProject() {
return( dynamic_cast<cfint::ICFIntSubProjectObj*>( orig ) );
}
cfint::ICFIntSchemaObj* CFIntSubProjectEditObj::getSchema() {
return( orig->getSchema() );
}
cfint::CFIntSubProjectBuff* CFIntSubProjectEditObj::getBuff() {
return( buff );
}
void CFIntSubProjectEditObj::setBuff( cfint::CFIntSubProjectBuff* value ) {
if( buff != value ) {
if( ( buff != NULL ) && ( buff != value ) ) {
delete buff;
buff = NULL;
}
buff = value;
}
}
cfint::CFIntSubProjectPKey* CFIntSubProjectEditObj::getPKey() {
return( orig->getPKey() );
}
void CFIntSubProjectEditObj::setPKey( cfint::CFIntSubProjectPKey* value ) {
if( orig->getPKey() != value ) {
orig->setPKey( value );
}
copyPKeyToBuff();
}
bool CFIntSubProjectEditObj::getIsNew() {
return( orig->getIsNew() );
}
void CFIntSubProjectEditObj::setIsNew( bool value ) {
orig->setIsNew( value );
}
const int64_t CFIntSubProjectEditObj::getRequiredTenantId() {
return( getPKey()->getRequiredTenantId() );
}
const int64_t* CFIntSubProjectEditObj::getRequiredTenantIdReference() {
return( getPKey()->getRequiredTenantIdReference() );
}
const int64_t CFIntSubProjectEditObj::getRequiredId() {
return( getPKey()->getRequiredId() );
}
const int64_t* CFIntSubProjectEditObj::getRequiredIdReference() {
return( getPKey()->getRequiredIdReference() );
}
const int64_t CFIntSubProjectEditObj::getRequiredTopProjectId() {
return( getSubProjectBuff()->getRequiredTopProjectId() );
}
const int64_t* CFIntSubProjectEditObj::getRequiredTopProjectIdReference() {
return( getSubProjectBuff()->getRequiredTopProjectIdReference() );
}
const std::string& CFIntSubProjectEditObj::getRequiredName() {
return( getSubProjectBuff()->getRequiredName() );
}
const std::string* CFIntSubProjectEditObj::getRequiredNameReference() {
return( getSubProjectBuff()->getRequiredNameReference() );
}
void CFIntSubProjectEditObj::setRequiredName( const std::string& value ) {
if( getSubProjectBuff()->getRequiredName() != value ) {
getSubProjectEditBuff()->setRequiredName( value );
}
}
bool CFIntSubProjectEditObj::isOptionalDescriptionNull() {
return( getSubProjectBuff()->isOptionalDescriptionNull() );
}
const std::string& CFIntSubProjectEditObj::getOptionalDescriptionValue() {
return( getSubProjectBuff()->getOptionalDescriptionValue() );
}
const std::string* CFIntSubProjectEditObj::getOptionalDescriptionReference() {
return( getSubProjectBuff()->getOptionalDescriptionReference() );
}
void CFIntSubProjectEditObj::setOptionalDescriptionNull() {
if( ! getSubProjectBuff()->isOptionalDescriptionNull() ) {
getSubProjectEditBuff()->setOptionalDescriptionNull();
}
}
void CFIntSubProjectEditObj::setOptionalDescriptionValue( const std::string& value ) {
if( getSubProjectBuff()->isOptionalDescriptionNull() ) {
getSubProjectEditBuff()->setOptionalDescriptionValue( value );
}
else if( getSubProjectBuff()->getOptionalDescriptionValue() != value ) {
getSubProjectEditBuff()->setOptionalDescriptionValue( value );
}
}
cfsec::ICFSecTenantObj* CFIntSubProjectEditObj::getRequiredOwnerTenant( bool forceRead ) {
cfsec::ICFSecTenantObj* retobj = NULL;
bool anyMissing = false;
if( ! anyMissing ) {
retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getTenantTableObj()->readTenantByIdIdx( getPKey()->getRequiredTenantId() );
}
return( retobj );
}
void CFIntSubProjectEditObj::setRequiredOwnerTenant( cfsec::ICFSecTenantObj* value ) {
if( value != NULL ) {
getPKey()->setRequiredTenantId
( value->getRequiredId() );
getSubProjectEditBuff()->setRequiredTenantId( value->getRequiredId() );
}
}
cfint::ICFIntTopProjectObj* CFIntSubProjectEditObj::getRequiredContainerParentTPrj( bool forceRead ) {
cfint::ICFIntTopProjectObj* retobj = NULL;
bool anyMissing = false;
if( ! anyMissing ) {
retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getTopProjectTableObj()->readTopProjectByIdIdx( getPKey()->getRequiredTenantId(),
getSubProjectBuff()->getRequiredTopProjectId() );
}
return( retobj );
}
void CFIntSubProjectEditObj::setRequiredContainerParentTPrj( cfint::ICFIntTopProjectObj* value ) {
if( value != NULL ) {
getPKey()->setRequiredTenantId
( value->getRequiredTenantId() );
getSubProjectEditBuff()->setRequiredTenantId( value->getRequiredTenantId() );
getSubProjectEditBuff()->setRequiredTopProjectId( value->getRequiredId() );
}
}
std::vector<cfint::ICFIntMajorVersionObj*> CFIntSubProjectEditObj::getOptionalComponentsMajorVer( bool forceRead ) {
std::vector<cfint::ICFIntMajorVersionObj*> retval;
retval = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getMajorVersionTableObj()->readMajorVersionBySubProjectIdx( getPKey()->getRequiredTenantId(),
getPKey()->getRequiredId(),
forceRead );
return( retval );
}
void CFIntSubProjectEditObj::copyPKeyToBuff() {
cfint::CFIntSubProjectPKey* tablePKey = getPKey();
cfint::CFIntSubProjectBuff* tableBuff = getSubProjectEditBuff();
tableBuff->setRequiredTenantId( tablePKey->getRequiredTenantId() );
tableBuff->setRequiredId( tablePKey->getRequiredId() );
}
void CFIntSubProjectEditObj::copyBuffToPKey() {
cfint::CFIntSubProjectPKey* tablePKey = getPKey();
cfint::CFIntSubProjectBuff* tableBuff = getSubProjectBuff();
tablePKey->setRequiredTenantId( tableBuff->getRequiredTenantId() );
tablePKey->setRequiredId( tableBuff->getRequiredId() );
}
void CFIntSubProjectEditObj::copyBuffToOrig() {
cfint::CFIntSubProjectBuff* origBuff = getOrigAsSubProject()->getSubProjectEditBuff();
cfint::CFIntSubProjectBuff* myBuff = getSubProjectBuff();
if( origBuff != myBuff ) {
*origBuff = *myBuff;
}
}
void CFIntSubProjectEditObj::copyOrigToBuff() {
cfint::CFIntSubProjectBuff* origBuff = getOrigAsSubProject()->getSubProjectBuff();
cfint::CFIntSubProjectBuff* myBuff = getSubProjectEditBuff();
if( origBuff != myBuff ) {
*myBuff = *origBuff;
}
}
}
| 34.413495 | 181 | 0.727062 | msobkow |
f926c57c62e11c0191895d80560b45d9e36323fa | 19,255 | cpp | C++ | kernel/Scheduler.cpp | SmkViper/CranberryOS | ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6 | [
"MIT"
] | null | null | null | kernel/Scheduler.cpp | SmkViper/CranberryOS | ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6 | [
"MIT"
] | null | null | null | kernel/Scheduler.cpp | SmkViper/CranberryOS | ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6 | [
"MIT"
] | null | null | null | #include "Scheduler.h"
#include <cstring>
#include <new>
#include "ARM/SchedulerDefines.h"
#include "IRQ.h"
#include "MemoryManager.h"
#include "Timer.h"
// How the scheduler currently works:
//
// CopyProcess creates a new memory page and puts the task struct at the bottom of the page, with the stack pointer
// pointing at a certain distance above it.
//
// 0xXXXXXXXX +--------------------+ ^
// | TaskStruct | |
// +--------------------+ | One page
// | | |
// | Stack (grows up) | |
// +--------------------+ |
// | ProcessState | |
// 0xXXXX1000 +--------------------+ v
//
// ScheduleImpl is called, either voluntarily or via timer
// cpu_switch_to saves all callee-saved registers in the current task to the TaskStruct context member
// cpu_switch_to "restores" all callee-saved registers for the new task, setting sp to 0xXXXX1000, the link register
// to ret_from_create, x19 to the task's process function, and x20 to the process function parameter
// cpu_switch_to returns, loading ret_from_create's address from the link register
// ret_from_create reads from x19 and x20, and calls to the function in x19, passing it x20
//
// Eventually a timer interrupt happens, saving all registers + elr_el1 and spsr_el1 to the bottom of the current
// task's stack
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
//
// The current task is now handling an interrupt, and grows a little bit more on the stack to pick the task to resume
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
//
// The interrupt picks a second new task to run, repeating the process performed for the first task to set up the
// second new task. This task begins executing and growing its own stack. Note that execution is still in the timer
// interrupt handler, but interrupts have been re-enabled at this point, so another timer can come in again.
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// Another timer interrupt happens, and the process repeats to save off all the registers, elr_el1 and spsr_el1 at the
// bottom of the second task's stack, and the interrupt stack for that task starts to grow
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// ScheduleImpl is now called, and notes that both tasks have their counter at 0. It then sets the counters to their
// priority and picks the first task to run again. (Though it could pick either if their priorities were the same)
// cpu_switch_to is called and it restores all the callee-saved registers from the first task context. The link
// register now points at the end of the SwitchTo function, since that's what it was the last time this task was
// running. The stack pointer also is set to point at the bottom of the first task's interrupt stack.
// The TimerTick function now resumes execution, disabling interrupts again and returns to the interrupt handler,
// collapsing the interrupt stack to 0.
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// The interrupt cleans up, restoring all the regsters that were saved from the stack, including the elr_el1 and
// spsr_el1 registers. elr_el1 now points somewhere in the middle of the process function (wherever the interrupt)
// originally happened. And sp now points at the bottom of the task's original stack
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// The eret instruction is executed, using the saved elr_el1 register to jump back to whatever the first task was doing
namespace
{
// SPSR_EL1 bits - See section C5.2.18 in the ARMv8 manual
constexpr uint64_t PSRModeEL0tC = 0x00000000;
struct CPUContext
{
// ARM calling conventions allow registers x0-x18 to be overwritten by a called function,
// so we don't need to save those off
//
// #TODO: May need to save off additional registers (i.e. SIMD/FP registers?)
uint64_t x19 = 0;
uint64_t x20 = 0;
uint64_t x21 = 0;
uint64_t x22 = 0;
uint64_t x23 = 0;
uint64_t x24 = 0;
uint64_t x25 = 0;
uint64_t x26 = 0;
uint64_t x27 = 0;
uint64_t x28 = 0;
uint64_t fp = 0; // x29
uint64_t sp = 0;
uint64_t pc = 0; // x30
};
enum class TaskState : int64_t
{
Running,
Zombie
};
struct TaskStruct
{
CPUContext Context;
TaskState State = TaskState::Running;
int64_t Counter = 0; // decrements each timer tick. When reaches 0, another task will be scheduled
int64_t Priority = 1; // copied to Counter when a task is scheduled, so higher priority will run for longer
int64_t PreemptCount = 0; // If non-zero, task will not be preempted
void* pStack = nullptr; // pointer to the stack root so it can be cleaned up if necessary
uint64_t Flags = 0;
};
// Expected to match what is put on the stack via the kernel_entry macro in the exception handler so it can
// "restore" the processor state we want
struct ProcessState
{
uint64_t Registers[31] = {0u};
uint64_t StackPointer = 0u;
uint64_t ProgramCounter = 0u;
uint64_t ProcessorState = 0u;
};
static_assert(offsetof(TaskStruct, Context) == TASK_STRUCT_CONTEXT_OFFSET, "Unexpected offset of context in task struct");
}
extern "C"
{
/**
* Return to the newly created task (Defined in ExceptionVectors.S)
*/
extern void ret_from_create();
/**
* Switch the CPU from running the previous task to the next task
*
* @param apPrev The previously running task
* @param apNext The new task to resume
*/
extern void cpu_switch_to(TaskStruct* apPrev, TaskStruct* apNext);
}
namespace
{
constexpr auto TimerTickMSC = 200; // tick every 200ms
constexpr auto ThreadSizeC = 4096; // 4k stack size (#TODO: Pull from page size?)
constexpr auto NumberOfTasksC = 64u;
TaskStruct InitTask; // task running kernel init
TaskStruct* pCurrentTask = &InitTask;
TaskStruct* Tasks[NumberOfTasksC] = {&InitTask, nullptr};
auto NumberOfTasks = 1;
/**
* Enable scheduler preemption in the current task
*/
void PreemptEnable()
{
// #TODO: Assert/error when we have it
--pCurrentTask->PreemptCount;
}
/**
* Disable scheduler preemption in the current task
*/
void PreemptDisable()
{
++pCurrentTask->PreemptCount;
}
/**
* Helper to disable scheduler preempting in the current scope
*/
struct DisablePreemptingInScope
{
/**
* Constructor - disables scheduler preempting
*/
[[nodiscard]] DisablePreemptingInScope()
{
PreemptDisable();
}
/**
* Destructor - reenables scheduler preempting
*/
~DisablePreemptingInScope()
{
PreemptEnable();
}
// Disable copying
DisablePreemptingInScope(const DisablePreemptingInScope&) = delete;
DisablePreemptingInScope& operator=(const DisablePreemptingInScope&) = delete;
};
/**
* Switch from running the current task to the next task
*
* @param apNextTask The next task to run
*/
void SwitchTo(TaskStruct* const apNextTask)
{
if (pCurrentTask == apNextTask)
{
return;
}
const auto pprevTask = pCurrentTask;
pCurrentTask = apNextTask;
cpu_switch_to(pprevTask, apNextTask);
}
/**
* Find and resume a running task
*/
void ScheduleImpl()
{
// Make sure we don't get called while we're in the middle of picking a task
DisablePreemptingInScope disablePreempt;
auto foundTask = false;
auto taskToResume = 0u;
while (!foundTask)
{
// Find the task with the largest counter value (i.e. the one that has the highest priority that has
// not run in a while)
auto largestCounter = -1ll;
taskToResume = 0;
for (auto curTask = 0u; curTask < NumberOfTasksC; ++curTask)
{
const auto ptask = Tasks[curTask];
if (ptask && (ptask->State == TaskState::Running) && (ptask->Counter > largestCounter))
{
largestCounter = ptask->Counter;
taskToResume = curTask;
}
}
// If we don't find any running task with a non-zero counter, then we need to go and reset all their
// counters according to their priority
foundTask = (largestCounter > 0);
if (!foundTask)
{
for (const auto pcurTask : Tasks)
{
if (pcurTask)
{
// Increment the counter by the priority, ensuring that we don't go above 2 * priority
// So the longer the task has been waiting, the higher the counter should be.
pcurTask->Counter = (pcurTask->Counter / 1) + pcurTask->Priority;
}
}
}
// If at least one task is running, then we should only loop around once. If all tasks are not running
// then we keep looping until a task changes its state to running again (i.e. via an interrupt)
}
SwitchTo(Tasks[taskToResume]);
}
/**
* Triggered by the timer interrupt to schedule a new task
*
* @param apParam The parameter registered for our callback
*/
void TimerTick(const void* /*apParam*/)
{
// Only switch task if the counter has run out and it hasn't been blocked
--pCurrentTask->Counter;
if ((pCurrentTask->Counter > 0) || (pCurrentTask->PreemptCount > 0))
{
return;
}
pCurrentTask->Counter = 0;
// Interrupts are disabled while handing one, so re-enable them for the schedule call because some tasks
// might be waiting from an interrupt and we want them to be able to get them while the scheduler is trying
// to find a task (otherwise we might just have all tasks waiting for interrupts and loop forever without
// finding a task to run)
enable_irq();
ScheduleImpl();
// And re-disable them before returning to the interrupt handler (which will deal with re-enabling them later)
disable_irq();
}
/**
* Extract the state memory from the stack for the given task
*
* @param apTask Task to get the state for
* @return The process state for the task
*/
void* GetTargetStateMemoryForTask(TaskStruct* apTask)
{
const auto state = reinterpret_cast<uintptr_t>(apTask) + ThreadSizeC - sizeof(ProcessState);
return reinterpret_cast<void*>(state);
}
}
extern "C"
{
/**
* Called by assembly to finish any work up before staring the process call
*/
void schedule_tail()
{
PreemptEnable();
}
}
namespace Scheduler
{
void InitTimer()
{
// We're using a local timer instead of the global timer because it works on both QEMU and real hardware
LocalTimer::RegisterCallback(TimerTickMSC, TimerTick, nullptr);
}
void Schedule()
{
pCurrentTask->Counter = 0;
ScheduleImpl();
}
int CreateProcess(const uint32_t aCreateFlags, ProcessFunctionPtr apProcessFn, const void* apParam, void* apStack)
{
// Make sure we don't get preempted in the middle of making a new task
DisablePreemptingInScope disablePreempt;
auto pmemory = reinterpret_cast<uint8_t*>(MemoryManager::GetFreePage());
if (pmemory == nullptr)
{
return -1;
}
auto pnewTask = new (pmemory) TaskStruct{};
const auto puninitializedState = reinterpret_cast<uint8_t*>(GetTargetStateMemoryForTask(pnewTask));
const auto pnewState = new (puninitializedState) ProcessState{};
if ((aCreateFlags & CreationFlags::KernelThreadC) == CreationFlags::KernelThreadC)
{
pnewTask->Context.x19 = reinterpret_cast<uint64_t>(apProcessFn);
pnewTask->Context.x20 = reinterpret_cast<uint64_t>(apParam);
}
else
{
// extract and clone the current processor state
const auto psourceState = reinterpret_cast<ProcessState*>(GetTargetStateMemoryForTask(pCurrentTask));
*pnewState = *psourceState;
pnewState->Registers[0] = 0; // make sure ret_from_create knows this is the new user process
pnewState->StackPointer = reinterpret_cast<uint64_t>(apStack) + ThreadSizeC;
pnewTask->pStack = apStack;
}
pnewTask->Flags = aCreateFlags;
pnewTask->Priority = pCurrentTask->Priority;
pnewTask->Counter = pnewTask->Priority;
pnewTask->PreemptCount = 1; // disable preemption until schedule_tail
pnewTask->Context.pc = reinterpret_cast<uint64_t>(ret_from_create);
pnewTask->Context.sp = reinterpret_cast<uint64_t>(pnewState);
const auto processID = NumberOfTasks++;
Tasks[processID] = pnewTask;
return processID;
}
bool MoveToUserMode(UserModeFunctionPtr apUserModeFn)
{
const auto puninitializedState = reinterpret_cast<uint8_t*>(GetTargetStateMemoryForTask(pCurrentTask));
auto pstate = new (puninitializedState) ProcessState{};
static_assert(sizeof(UserModeFunctionPtr) == sizeof(uint64_t), "Unexpected pointer size");
pstate->ProgramCounter = reinterpret_cast<uint64_t>(apUserModeFn);
pstate->ProcessorState = PSRModeEL0tC;
const auto pstack = MemoryManager::GetFreePage();
if (pstack == nullptr)
{
pstate->~ProcessState();
return false;
}
pstate->StackPointer = reinterpret_cast<uint64_t>(pstack) + ThreadSizeC;
pCurrentTask->pStack = pstack;
return true;
}
void ExitProcess()
{
{
// Make sure we don't get preempted in the middle of cleaning up the task
DisablePreemptingInScope disablePreempt;
// Flag the task as a zombie so it isn't rescheduled
for (const auto pcurTask : Tasks)
{
if (pcurTask == pCurrentTask)
{
pcurTask->State = TaskState::Zombie;
break;
}
}
if (pCurrentTask->pStack)
{
MemoryManager::FreePage(pCurrentTask->pStack);
}
}
// Won't ever return because a new task will be scheduled and this one is now flagged as a zombie
Schedule();
}
} | 36.746183 | 126 | 0.513944 | SmkViper |
f935d5845c9b02a9c2aca16f33c9703cce725ceb | 1,475 | cpp | C++ | Deprecated/Debug/Debug.cpp | Theundeadwarrior/Casiope | f21b53b8e51adb9b341269471443b9dc0f61e9d8 | [
"MIT"
] | 3 | 2016-08-04T05:08:59.000Z | 2018-03-28T04:40:43.000Z | Deprecated/Debug/Debug.cpp | Theundeadwarrior/Casiope | f21b53b8e51adb9b341269471443b9dc0f61e9d8 | [
"MIT"
] | 6 | 2016-08-05T17:57:51.000Z | 2018-03-28T04:41:09.000Z | Deprecated/Debug/Debug.cpp | Theundeadwarrior/Casiope | f21b53b8e51adb9b341269471443b9dc0f61e9d8 | [
"MIT"
] | 1 | 2016-08-16T05:40:59.000Z | 2016-08-16T05:40:59.000Z | #include "Debug.h"
#include <assert.h>
#include <stdio.h>
#include <stdarg.h>
#include <string>
#include <Windows.h>
#include <iostream>
namespace Atum
{
namespace Utilities
{
void OutputTrace(char* text, ...)
{
char buffer[256];
va_list args;
va_start (args, text);
vsprintf_s (buffer, text, args);
OutputDebugString (buffer);
va_end (args);
}
void OutputError(char* text, ...)
{
char buffer[256];
va_list args;
va_start (args, text);
vsprintf_s (buffer,text, args);
perror (buffer);
// Make crash?
va_end (args);
}
void OutputAssert( const char* _condition, const char* _message, char* _filename, char* _line )
{
std::string condition(_condition);
std::string message(_message);
std::string file(_filename);
std::string line(_line);
// Remove the path if there is a path
int fileNameBeginPosition = file.find_last_of("\\");
if(fileNameBeginPosition != file.size())
{
file.erase(0,fileNameBeginPosition + 1);
file.erase(file.size() - 1, 1);
}
std::string errorMessage("[ASSERT] Condition: ");
errorMessage.append(condition);
errorMessage.append(" failed. ");
errorMessage.append("Error in file ");
errorMessage.append(file);
errorMessage.append(" at line ");
errorMessage.append(line);
errorMessage.append(". ");
errorMessage.append(message);
OutputDebugString(errorMessage.c_str());
perror(errorMessage.c_str());
// make crash?
}
}
}
| 22.014925 | 97 | 0.660339 | Theundeadwarrior |
f93cbce816eabe0acb98a508a6479f13f027ed1c | 2,930 | cpp | C++ | Rasterizer/src/Light.cpp | litelawliet/ISARTRasterizer | 329ed70ea830cfff286c01d8efa5e726276f1fcd | [
"MIT"
] | 1 | 2020-03-23T14:36:02.000Z | 2020-03-23T14:36:02.000Z | Rasterizer/src/Light.cpp | litelawliet/ISARTRasterizer | 329ed70ea830cfff286c01d8efa5e726276f1fcd | [
"MIT"
] | null | null | null | Rasterizer/src/Light.cpp | litelawliet/ISARTRasterizer | 329ed70ea830cfff286c01d8efa5e726276f1fcd | [
"MIT"
] | null | null | null | #include "Light.h"
#include "Color.h"
#include "Vertex.h"
#include "Maths/Vec4.h"
#include <iostream>
#include <algorithm>
using namespace Maths::Vector;
//ADD LIGHTING HERE EVENTUALLY
Light::Light(const Maths::Vector::Vec3 p_position, const float p_ambient, const float p_diffuse, const float p_specular)
: m_position{ p_position }, m_ambientComponent{ p_ambient }, m_diffuseComponent{ p_diffuse }, m_specularComponent{ p_specular }
{}
Light::Light(const float p_x, const float p_y, const float p_z, const float p_ambient, const float p_diffuse, const float p_specular)
: m_position{ p_x, p_y, p_z }, m_ambientComponent{ p_ambient }, m_diffuseComponent{ p_diffuse }, m_specularComponent{ p_specular }
{}
Vec3& Light::GetPosition()
{
return { m_position };
}
float Light::GetAmbientComponent() const
{
return m_ambientComponent;
}
float Light::GetDiffuseComponent() const
{
return m_diffuseComponent;
}
float Light::GetSpecularComponent() const
{
return m_specularComponent;
}
void Light::SetPosition(const Vec3 & p_position)
{
m_position = p_position;
}
void Light::SetPosition(const float p_x, const float p_y, const float p_z)
{
m_position.m_x = p_x;
m_position.m_y = p_x;
m_position.m_z = p_z;
}
void Light::SetAmbientComponent(const float p_value)
{
m_ambientComponent = p_value;
}
void Light::SetDiffuseComponent(const float p_value)
{
m_diffuseComponent = p_value;
}
void Light::SetSpecularComponent(const float p_value)
{
m_specularComponent = p_value;
}
Color Light::CalculateColor(const Color p_color, const Vec3 p_surface, Vec4 p_vertex)
{
Vec3 normalSurface = p_surface;
//normalSurface.Normalize();
Vec3 homogenizedVec = Vec3{ p_vertex.m_x / p_vertex.m_w, p_vertex.m_y / p_vertex.m_w, p_vertex.m_z / p_vertex.m_w };
Vec3 lightPosNormal = m_position - homogenizedVec;
lightPosNormal.Normalize();
Vec3 reflectedLightVector = GetLightReflection(lightPosNormal, normalSurface);
float specAngle = std::max(Vec3::GetDotProduct(reflectedLightVector, homogenizedVec), 0.0f);
float lambertian = std::max(Vec3::GetDotProduct(normalSurface, lightPosNormal), 0.0f);
float specular = std::powf(specAngle, 1.0);
float r = (m_ambientComponent * p_color.m_r) + (m_diffuseComponent * lambertian * p_color.m_r) + (m_specularComponent * specular * p_color.m_r);
float g = (m_ambientComponent * p_color.m_g) + (m_diffuseComponent * lambertian * p_color.m_g) + (m_specularComponent * specular * p_color.m_g);
float b = (m_ambientComponent * p_color.m_b) + (m_diffuseComponent * lambertian * p_color.m_b) + (m_specularComponent * specular * p_color.m_b);
return { Color { static_cast<unsigned char>(r), static_cast<unsigned char>(g), static_cast<unsigned char>(b), p_color.m_a} };
}
Vec3 Light::GetLightReflection(Vec3 p_v0, Vec3 p_v1)
{
Vec3 negatedP0 = p_v0 * -1;
float dotProductResult = Vec3::GetDotProduct(negatedP0, p_v1);
return { negatedP0 - (p_v1 * (2 * dotProductResult)) };
} | 30.206186 | 145 | 0.757679 | litelawliet |
f946696a7d0623b6cb4cc3138e4b97679ef3ab6d | 8,891 | hpp | C++ | test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter_linear_vs_x_test_suite.hpp
* \date July 2015
* \author Jan Issac (jan.issac@gmail.com)
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <fl/util/math/linear_algebra.hpp>
#include <fl/filter/filter_interface.hpp>
#include <fl/filter/gaussian/gaussian_filter_linear.hpp>
#include <fl/model/transition/linear_transition.hpp>
#include <fl/model/sensor/linear_gaussian_sensor.hpp>
#include <fl/model/sensor/linear_decorrelated_gaussian_sensor.hpp>
enum : signed int
{
DecorrelatedGaussianModel,
GaussianModel
};
static constexpr double epsilon = 0.1;
template <typename TestType>
class GaussianFilterLinearVsXTest
: public ::testing::Test
{
protected:
typedef typename TestType::Parameter Configuration;
enum: signed int
{
StateDim = Configuration::StateDim,
InputDim = Configuration::InputDim,
ObsrvDim = Configuration::ObsrvDim,
StateSize = fl::TestSize<StateDim, TestType>::Value,
InputSize = fl::TestSize<InputDim, TestType>::Value,
ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value
};
enum ModelSetup
{
Random,
Identity
};
typedef Eigen::Matrix<fl::Real, StateSize, 1> State;
typedef Eigen::Matrix<fl::Real, InputSize, 1> Input;
typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv;
typedef fl::IntegerTypeMap<
fl::IntegerTypePair<
DecorrelatedGaussianModel,
fl::LinearDecorrelatedGaussianSensor<Obsrv, State>
>,
fl::IntegerTypePair<
GaussianModel,
fl::LinearGaussianSensor<Obsrv, State>
>
> SensorMap;
typedef fl::LinearTransition<State, State, Input> LinearTransition;
typedef typename SensorMap::template Select<
Configuration::SelectedModel
>::Type LinearSensor;
typedef fl::GaussianFilter<
LinearTransition, LinearSensor
> KalmanFilter;
typedef typename Configuration::template FilterDefinition<
LinearTransition,
LinearSensor
> FilterDefinition;
typedef typename FilterDefinition::Type Filter;
GaussianFilterLinearVsXTest()
: predict_steps_(200),
predict_update_steps_(30)
{ }
KalmanFilter create_kalman_filter() const
{
return KalmanFilter(
LinearTransition(StateDim, InputDim),
LinearSensor(ObsrvDim, StateDim));
}
Filter create_filter() const
{
return Configuration::create_filter(
LinearTransition(StateDim, InputDim),
LinearSensor(ObsrvDim, StateDim));
}
void setup_models(
KalmanFilter& kalman_filter, Filter& other_filter, ModelSetup setup)
{
auto A = kalman_filter.transition().create_dynamics_matrix();
auto B = kalman_filter.transition().create_input_matrix();
auto Q = kalman_filter.transition().create_noise_matrix();
auto H = kalman_filter.sensor().create_sensor_matrix();
auto R = kalman_filter.sensor().create_noise_matrix();
Q.setZero();
R.setZero();
B.setZero();
switch (setup)
{
case Random:
A.diagonal().setRandom();
H.diagonal().setRandom();
Q.diagonal().setRandom(); Q *= Q.transpose().eval();
R.diagonal().setRandom(); R *= R.transpose().eval();
break;
case Identity:
A.setIdentity();
H.setIdentity();
Q.setIdentity();
R.setIdentity();
break;
}
kalman_filter.transition().dynamics_matrix(A);
kalman_filter.transition().input_matrix(B);
kalman_filter.transition().noise_matrix(Q);
kalman_filter.sensor().sensor_matrix(H);
kalman_filter.sensor().noise_matrix(R);
other_filter.transition().dynamics_matrix(A);
other_filter.transition().input_matrix(B);
other_filter.transition().noise_matrix(Q);
other_filter.sensor().sensor_matrix(H);
other_filter.sensor().noise_matrix(R);
}
State zero_state() { return State::Zero(StateDim); }
Input zero_input() { return Input::Zero(InputDim); }
Obsrv zero_obsrv() { return Obsrv::Zero(ObsrvDim); }
State rand_state() { return State::Random(StateDim); }
Input rand_input() { return Input::Random(InputDim); }
Obsrv rand_obsrv() { return Obsrv::Random(ObsrvDim); }
protected:
int predict_steps_;
int predict_update_steps_;
};
TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest);
//TYPED_TEST_P(GaussianFilterLinearVsXTest, predict)
//{
// typedef TestFixture This;
// auto other_filter = This::create_filter();
// auto kalman_filter = This::create_kalman_filter();
// This::setup_models(kalman_filter, other_filter, This::Random);
// auto belief_other = other_filter.create_belief();
// auto belief_kf = kalman_filter.create_belief();
// for (int i = 0; i < This::predict_steps_; ++i)
// {
// other_filter.predict(belief_other, This::zero_input(), belief_other);
// kalman_filter.predict(belief_kf, This::zero_input(), belief_kf);
// if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))
// {
// std::cout << "i = " << i << std::endl;
// PV(belief_kf.mean());
// PV(belief_other.mean());
// }
// if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))
// {
// std::cout << "i = " << i << std::endl;
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// }
// ASSERT_TRUE(
// fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon));
// ASSERT_TRUE(
// fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon));
// }
// PV(belief_kf.mean());
// PV(belief_other.mean());
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
//}
TYPED_TEST_P(GaussianFilterLinearVsXTest, predict_and_update)
{
typedef TestFixture This;
auto other_filter = This::create_filter();
auto kalman_filter = This::create_kalman_filter();
This::setup_models(kalman_filter, other_filter, This::Random);
auto belief_other = other_filter.create_belief();
auto belief_kf = kalman_filter.create_belief();
for (int i = 0; i < This::predict_update_steps_; ++i)
{
auto y = This::rand_obsrv();
kalman_filter.predict(belief_kf, This::zero_input(), belief_kf);
other_filter.predict(belief_other, This::zero_input(), belief_other);
// if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))
// {
// std::cout << "predict i = " << i << std::endl;
// PV(belief_kf.mean());
// PV(belief_other.mean());
// }
// if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))
// {
// std::cout << "predict i = " << i << std::endl;
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// }
kalman_filter.update(belief_kf, y, belief_kf);
other_filter.update(belief_other, y, belief_other);
// if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))
// {
// std::cout << "update i = " << i << std::endl;
// PV(belief_kf.mean());
// PV(belief_other.mean());
// }
// if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))
// {
// std::cout << "update i = " << i << std::endl;
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// }
ASSERT_TRUE(
fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon));
ASSERT_TRUE(
fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon));
}
// PV(belief_kf.mean());
// PV(belief_other.mean());
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// std::cout << other_filter.name() << std::endl;
}
REGISTER_TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest,
predict_and_update);
| 30.44863 | 91 | 0.614554 | aeolusbot-tommyliu |
f94e38df5799ef9f869a4654054e011cac6b46a3 | 13,307 | hpp | C++ | common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <string>
#include <vector>
#include "adstlog_cxx/p7_trace_wrapper.hpp"
// clang-format off
// Actor module registers all of these channels
#define ADSTLOG_ACTOR_CH p7ActorCh_
#define ADSTLOG_MSG_TX_CH p7MsgTxCh_
#define ADSTLOG_MSG_RX_CH p7MsgRxCh_
#define ADSTLOG_GRPC_RX_CH p7GrpcRxCh_
#define ADSTLOG_GRPC_TX_CH p7GrpcTxCh_
#define ADSTLOG_GRPC_CH p7GrpcCh_
#define ADSTLOG_CORE_CH p7CoreCh_
// channel names to be used for set trace level on channels
#define ADSTLOG_MSG_TX_CH_NAME "msg_tx" // message published internal dispatch
#define ADSTLOG_MSG_RX_CH_NAME "msg_rx" // message consumed internal dispatch
#define ADSTLOG_GRPC_RX_CH_NAME "grpc_rx" // message received between processes
#define ADSTLOG_GRPC_TX_CH_NAME "grpc_tx" // message transmitted between processes
#define ADSTLOG_GRPC_CH_NAME "grpc" // used in gRPC boarder actors debugging
#define ADSTLOG_CORE_CH_NAME "core" // used by all framework classes
#define ADSTLOG_ACTOR_CH_NAME "actor" // all user modules are on this channel
// helper to be used in for loops to iterate over on channels.
#define ADSTLOG_TRACE_CHANNELS \
ADSTLOG_MSG_TX_CH_NAME, \
ADSTLOG_MSG_RX_CH_NAME, \
ADSTLOG_GRPC_RX_CH_NAME, \
ADSTLOG_GRPC_TX_CH_NAME, \
ADSTLOG_GRPC_CH_NAME, \
ADSTLOG_CORE_CH_NAME, \
ADSTLOG_ACTOR_CH_NAME
// the actual call for the trace function
#define ADSTLOG_LOG_ON(OBJ, LVL, CHANNEL, MODULE, ...) \
OBJ->CHANNEL->getObj()->Trace(0, \
LVL, \
OBJ->MODULE, \
(tUINT16)__LINE__, \
(const char*)__FILE__, \
(const char*)__FUNCTION__, \
__VA_ARGS__)
// then the logging is happening in a class where trace defined
#define ADSTLOG_LOG(...) \
ADSTLOG_LOG_ON(this, __VA_ARGS__)
// helper macros
#define ADSTLOG_CH(CH) ADSTLOG_##CH##_CH
#define ADSTLOG_CH_MOD(CH, MOD) p7_##CH##_##MOD##_
// Helper macros for define / declare traces in actor base
#define ADSTLOG_GET_CH(CH) mutable adst::common::Logger::ChannelUPtr ADSTLOG_CH(CH) = \
std::make_unique<adst::common::ManageTraceObj<IP7_Trace>>(&P7_Get_Shared_Trace, \
ADSTLOG_##CH##_CH_NAME, &IP7_Trace::Release)
#define ADSTLOG_DEFINE_CH(CH) mutable adst::common::Logger::ChannelUPtr ADSTLOG_CH(CH) = nullptr
#define ADSTLOG_INIT_CH(CH) ADSTLOG_CH(CH) = \
std::make_unique<adst::common::ManageTraceObj<IP7_Trace>>(&P7_Get_Shared_Trace, \
ADSTLOG_##CH##_CH_NAME, &IP7_Trace::Release)
#define ADSTLOG_REGISTER_MODULE(CH, MOD, NAME) \
mutable IP7_Trace::hModule ADSTLOG_CH_MOD(CH, MOD) = nullptr; \
tBOOL isNewModule_##CH##_##MOD = ADSTLOG_CH(CH)->getObj()->Register_Module(NAME, &ADSTLOG_CH_MOD(CH, MOD))
#define ADSTLOG_DEFINE_MODULE(CH, MOD) mutable IP7_Trace::hModule ADSTLOG_CH_MOD(CH, MOD) = nullptr
#define ADSTLOG_INIT_MODULE(CH, MOD, NAME) ADSTLOG_CH(CH)->getObj()->Register_Module(NAME, &ADSTLOG_CH_MOD(CH, MOD))
#define TEST_HELPER_ADSTLOG_UNUSED(CH, MOD) \
mutable (void)isNewModule_##CH##_##MOD
// public macros
#define TEST_HELPER_ADSTLOG_UNUSED_ALL() \
TEST_HELPER_ADSTLOG_UNUSED(ACTOR, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(MSG_TX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(MSG_RX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(GRPC_RX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(GRPC_TX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(GRPC, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(CORE, ACTOR)
/**
* Generic trace macros can be used in ADST FW to log on non actor channel and non actor.name_ module.
* The need for this is very rare. Normally, user shall not use these.
*
* They are used by the more restrictive trace macros like LOG_I(...), and LOG_CH_I(...), etc.
*/
#define LOG_CH_MOD_E(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_ERROR, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_W(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_WARNING, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_I(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_INFO, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_D(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_DEBUG, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_T(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_TRACE, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_E_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_ERROR, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_W_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_WARNING, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_I_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_INFO, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_D_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_DEBUG, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_T_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG(OBJ, EP7TRACE_LEVEL_TRACE, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
/**
* Log macro meant to be used within the ADST FW for tracing
* on actor.name_ channel instead of actor or core.
*
* Mostly used in fw to log gRPC and dispatch message tx/rx.
*/
#define LOG_CH_E(CH, ...) LOG_CH_MOD_E(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_W(CH, ...) LOG_CH_MOD_W(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_I(CH, ...) LOG_CH_MOD_I(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_D(CH, ...) LOG_CH_MOD_D(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_T(CH, ...) LOG_CH_MOD_T(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_E_ON(OBJ, CH, ...) LOG_CH_MOD_E_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_W_ON(OBJ, CH, ...) LOG_CH_MOD_W_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_I_ON(OBJ, CH, ...) LOG_CH_MOD_I_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_D_ON(OBJ, CH, ...) LOG_CH_MOD_D_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_T_ON(OBJ, CH, ...) LOG_CH_MOD_T_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
/**
* Logging macro meant to be used within the ADST FW for logging on core channel and on actor.name_ module
* main macro used for tracing within the fw for debug
*/
#define LOG_C_E(...) LOG_CH_E(CORE, __VA_ARGS__)
#define LOG_C_W(...) LOG_CH_W(CORE, __VA_ARGS__)
#define LOG_C_I(...) LOG_CH_I(CORE, __VA_ARGS__)
#define LOG_C_D(...) LOG_CH_D(CORE, __VA_ARGS__)
// core trace TRACE_LEVEL very verbose and has performance penalty it is not compiled in by default.
#ifdef ADSTLOG_TRACE_LEVEL_CORE_COMPILED_IN
#define LOG_C_T(...) LOG_CH_T(CORE, __VA_ARGS__)
#else
#define LOG_C_T(...)
#endif
/**
* Default logging macros. Shall be used by components and all code logic outside of ADST FW. Logs
* on actor channel on Actor.name_ module
*/
#define LOG_E(...) LOG_CH_E(ACTOR, __VA_ARGS__)
#define LOG_W(...) LOG_CH_W(ACTOR, __VA_ARGS__)
#define LOG_I(...) LOG_CH_I(ACTOR, __VA_ARGS__)
#define LOG_D(...) LOG_CH_D(ACTOR, __VA_ARGS__)
#define LOG_T(...) LOG_CH_T(ACTOR, __VA_ARGS__)
/**
* Default logging macros. Shall be used by components and all code logic outside of ADST FW. Logs
* on actor channel on Actor.name_ module
*/
#define LOG_E_ON(OBJ, ...) LOG_CH_E_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_W_ON(OBJ, ...) LOG_CH_W_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_I_ON(OBJ, ...) LOG_CH_I_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_D_ON(OBJ, ...) LOG_CH_D_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_T_ON(OBJ, ...) LOG_CH_T_ON(OBJ, ACTOR, __VA_ARGS__)
// Every Class which works in actor context shall use this trace macro to enable tracing within the class
/**
* Only defines the member variables for tracing but does not initialize them this might be
* necessary in case of template classes.
*
* If this macro is used, the constructor must call ADSTLOG_INIT_ACTOR_TRACE_MODULES.
* *Before* considering to use this macro, make sure that ADSTLOG_DEF_DEC_ACTOR_TRACE_MODULES is not
* suitable.
*/
#define ADSTLOG_DEF_ACTOR_TRACE_MODULES() \
ADSTLOG_DEFINE_CH(ACTOR); \
ADSTLOG_DEFINE_CH(MSG_TX); \
ADSTLOG_DEFINE_CH(MSG_RX); \
ADSTLOG_DEFINE_CH(GRPC_RX); \
ADSTLOG_DEFINE_CH(GRPC_TX); \
ADSTLOG_DEFINE_CH(GRPC); \
ADSTLOG_DEFINE_CH(CORE); \
ADSTLOG_DEFINE_MODULE(ACTOR, ACTOR); \
ADSTLOG_DEFINE_MODULE(MSG_TX, ACTOR); \
ADSTLOG_DEFINE_MODULE(MSG_RX, ACTOR); \
ADSTLOG_DEFINE_MODULE(GRPC_RX, ACTOR); \
ADSTLOG_DEFINE_MODULE(GRPC_TX, ACTOR); \
ADSTLOG_DEFINE_MODULE(GRPC, ACTOR); \
ADSTLOG_DEFINE_MODULE(CORE, ACTOR)
/**
* The macro is meant to used together with ADSTLOG_DEF_ACTOR_TRACE_MODULES. It shall be used in
* class constructor when ADSTLOG_DEF_ACTOR_TRACE_MODULES was used in the class declaration.
*/
#define ADSTLOG_INIT_ACTOR_TRACE_MODULES(NAME) \
ADSTLOG_INIT_CH(ACTOR); \
ADSTLOG_INIT_CH(MSG_TX); \
ADSTLOG_INIT_CH(MSG_RX); \
ADSTLOG_INIT_CH(GRPC_RX); \
ADSTLOG_INIT_CH(GRPC_TX); \
ADSTLOG_INIT_CH(GRPC); \
ADSTLOG_INIT_CH(CORE); \
ADSTLOG_INIT_MODULE(ACTOR, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(MSG_TX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(MSG_RX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(GRPC_RX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(GRPC_TX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(GRPC, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(CORE, ACTOR, NAME)
/**
* Register threads used by ADST FW (user shall not create threads).
*/
#define ADSTLOG_REGISTER_THREAD(THREAD_ID, NAME) \
ADSTLOG_CH(ACTOR)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(MSG_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(MSG_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(GRPC_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(GRPC_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(GRPC)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(CORE)->getObj()->Register_Thread(NAME, THREAD_ID)
#define ADSTLOG_REGISTER_THREAD_ON(OBJ, THREAD_ID, NAME) \
OBJ.ADSTLOG_CH(ACTOR)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(CORE)->getObj()->Register_Thread(NAME, THREAD_ID)
/**
* Unregister threads used by ADST FW (user shall not create threads).
*/
#define ADSTLOG_UNREGISTER_THREAD(THREAD_ID) \
ADSTLOG_CH(ACTOR)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(MSG_TX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(MSG_RX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(GRPC_RX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(GRPC_TX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(GRPC)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(CORE)->getObj()->Unregister_Thread(THREAD_ID)
// clang-format on
#define ADSTLOG_UNREGISTER_THREAD_ON(OBJ, THREAD_ID) \
OBJ.ADSTLOG_CH(ACTOR)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_TX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_RX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_RX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_TX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(CORE)->getObj()->Unregister_Thread(THREAD_ID)
// clang-format on
namespace adst::common {
struct Config;
/**
* Only one single instance of logger shall exist in any ADST c++ process.
*/
class Logger
{
// not copyable or movable
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
Logger(Logger&&) = delete;
Logger& operator=(Logger&&) = delete;
public:
using ClientUPtr = std::unique_ptr<ManageTraceObj<IP7_Client>>;
using ChannelUPtr = std::unique_ptr<ManageTraceObj<IP7_Trace>>;
Logger(const Config& config);
// there is no flush is needed when the logger is recycled flush is called from the trance Object destructor.
~Logger() = default;
private:
std::string getClientConfigStr(const Config& config);
ClientUPtr client_ = nullptr;
std::vector<ChannelUPtr> channels_;
};
} // namespace adst::common
| 46.044983 | 116 | 0.690915 | csitarichie |
f952d5cc45ae8b814c1940f16c5fc9eda719b50a | 6,025 | cpp | C++ | src/SearchRange.cpp | emweb/aga | bd7ad699e901168fe1658bea7c3c5d53fa5938e5 | [
"OML",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 13 | 2017-10-12T10:10:55.000Z | 2020-11-12T08:28:43.000Z | src/SearchRange.cpp | emweb/aga | bd7ad699e901168fe1658bea7c3c5d53fa5938e5 | [
"OML",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/SearchRange.cpp | emweb/aga | bd7ad699e901168fe1658bea7c3c5d53fa5938e5 | [
"OML",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 6 | 2018-09-13T04:49:10.000Z | 2020-11-12T08:28:45.000Z | #include "SearchRange.h"
#include "Cigar.h"
SearchRangeItem::SearchRangeItem(Type aType, int aStartColumn, int anEndColumn,
int aStartRow, int anEndRow)
: type(aType),
startRow(aStartRow),
endRow(anEndRow),
startColumn(aStartColumn),
endColumn(anEndColumn)
{ }
std::ostream& operator<<(std::ostream& o, const SearchRangeItem& sri)
{
switch (sri.type) {
case SearchRangeItem::Rectangle:
o << "rect Start=(" << sri.startColumn << "," << sri.startRow << ") "
<< "End=(" << sri.endColumn << "," << sri.endRow << ")";
break;
case SearchRangeItem::Parallelogram:
o << "para Start=(" << sri.startColumn << "," << sri.startRow << " - " << sri.endRow << ") "
<< "End=(" << sri.endColumn << "," << sri.startRow + (sri.endColumn - sri.startColumn)
<< " - " << sri.endRow + (sri.endColumn - sri.startColumn) << ")";
}
return o;
}
SearchRange::SearchRange()
: columns(0),
rows(0)
{ }
SearchRange::SearchRange(int aColumns, int aRows)
: columns(aColumns),
rows(aRows)
{
items.push_back(SearchRangeItem(SearchRangeItem::Rectangle,
0, columns,
0, rows));
}
int SearchRange::startRow(int column) const
{
for (const auto& i : items) {
if (column < i.endColumn) {
switch (i.type) {
case SearchRangeItem::Rectangle:
return std::max(0, i.startRow);
case SearchRangeItem::Parallelogram:
return std::max(0, i.startRow + (column - i.startColumn));
}
}
}
throw std::runtime_error("Incomplete search range not covering " + std::to_string(column));
}
int SearchRange::endRow(int column) const
{
for (const auto& i : items) {
if (column < i.endColumn) {
switch (i.type) {
case SearchRangeItem::Rectangle:
return std::min(rows, i.endRow);
case SearchRangeItem::Parallelogram:
return std::min(rows, i.endRow + (column - i.startColumn));
}
}
}
throw std::runtime_error("Incomplete search range not covering " +
std::to_string(column));
}
int SearchRange::maxRowCount() const
{
int result = 0;
for (const auto& i : items) {
int h = i.endRow - i.startRow;
if (h > result)
result = h;
}
return result;
}
long SearchRange::size() const
{
long result = 0;
for (const auto& i : items) {
long h = i.endRow - i.startRow;
long w = i.endColumn - i.startColumn;
result += h * w;
}
return result;
}
SearchRange getSearchRange(const Cigar& seed,
int refSize, int querySize, int margin)
{
if (seed.empty())
return SearchRange(refSize + 1, querySize + 1);
else {
SearchRange result(refSize + 1, querySize + 1);
result.items.clear();
SearchRangeItem::Type currentType = SearchRangeItem::Rectangle;
int currentRefStart = 0;
int currentQueryStart = 0;
int refI = 1;
int queryI = 1;
const int MARGIN = margin;
for (const auto& i : seed) {
if (i.op() == CigarItem::RefSkipped ||
i.op() == CigarItem::QuerySkipped) {
// terminate current aligned block
if (currentType == SearchRangeItem::Parallelogram) {
if (refI > currentRefStart && queryI > currentQueryStart) {
int deviation = std::abs((queryI - currentQueryStart) -
(refI - currentRefStart));
deviation += MARGIN;
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
refI,
currentQueryStart - deviation,
currentQueryStart + deviation));
}
currentType = SearchRangeItem::Rectangle;
currentRefStart = refI;
currentQueryStart = queryI - MARGIN;
}
if (i.op() == CigarItem::RefSkipped)
refI += i.length();
else
queryI += i.length();
} else {
// terminate current non-aligned block
if (currentType == SearchRangeItem::Rectangle) {
if (result.items.empty()) {
int s = refI - queryI - 10 * MARGIN;
if (s > MARGIN) {
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
s,
currentQueryStart,
1));
currentRefStart = s;
}
}
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
refI,
currentQueryStart,
queryI + MARGIN));
currentType = SearchRangeItem::Parallelogram;
currentRefStart = refI;
currentQueryStart = queryI;
}
switch (i.op()) {
case CigarItem::Match:
refI += i.length();
queryI += i.length();
break;
case CigarItem::RefGap:
queryI += i.length();
break;
case CigarItem::QueryGap:
refI += i.length();
break;
default:
break;
}
}
refI = std::min(refI, refSize);
queryI = std::min(queryI, querySize);
}
// Terminate last block
if (currentType == SearchRangeItem::Parallelogram) {
if (refI > currentRefStart && queryI > currentQueryStart) {
int deviation = std::abs((queryI - currentQueryStart) -
(refI - currentRefStart));
deviation += MARGIN;
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
refI,
currentQueryStart - deviation,
currentQueryStart + deviation));
currentRefStart = refI;
currentQueryStart = queryI - MARGIN;
}
}
if (currentRefStart < refSize + 1) {
int s = currentRefStart + (querySize - queryI + 10 * MARGIN);
if (s < refSize + 1 - MARGIN) {
result.items.push_back
(SearchRangeItem(SearchRangeItem::Rectangle,
currentRefStart, s,
currentQueryStart, querySize + 1));
currentRefStart = s;
currentQueryStart = querySize;
}
result.items.push_back
(SearchRangeItem(SearchRangeItem::Rectangle,
currentRefStart, refSize + 1,
currentQueryStart, querySize + 1));
}
return result;
}
}
std::ostream& operator<<(std::ostream& o, const SearchRange& sr)
{
std::cerr << "SearchRange [";
bool first = true;
for (const auto& i : sr.items) {
if (!first)
std::cerr << ",";
std::cerr << std::endl << " " << i;
first = false;
}
std::cerr << std::endl << "]" << std::endl;
return o;
}
| 23.720472 | 99 | 0.618257 | emweb |
f953fc44bb7d10293222e69195cbc3c3cdbb7bee | 13,193 | cpp | C++ | samples/examples/imkRecognizeObject-file.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 2 | 2021-02-22T11:36:33.000Z | 2021-07-20T11:31:08.000Z | samples/examples/imkRecognizeObject-file.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | null | null | null | samples/examples/imkRecognizeObject-file.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 3 | 2018-10-19T10:39:23.000Z | 2021-04-07T13:39:03.000Z | /******************************************************************************
* Copyright (c) 2017 Johann Prankl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
******************************************************************************/
#include <float.h>
#include <pcl/common/centroid.h>
#include <pcl/common/time.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <v4r/config.h>
#include <v4r/io/filesystem.h>
#include <v4r/recognition/IMKRecognizer.h>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdexcept>
#include <v4r/keypoints/impl/PoseIO.hpp>
#include <v4r/keypoints/impl/invPose.hpp>
#include <v4r/keypoints/impl/toString.hpp>
#include <v4r/reconstruction/impl/projectPointToImage.hpp>
#include "pcl/common/transforms.h"
//#include <v4r/features/FeatureDetector_KD_FAST_IMGD.h>
#if HAVE_SIFTGPU
#define USE_SIFT_GPU
#include <v4r/features/FeatureDetector_KD_SIFTGPU.h>
#else
#include <v4r/features/FeatureDetector_KD_CVSIFT.h>
#endif
#include <pcl/common/time.h>
using namespace std;
namespace po = boost::program_options;
void drawConfidenceBar(cv::Mat &im, const double &conf);
cv::Point2f drawCoordinateSystem(cv::Mat &im, const Eigen::Matrix4f &pose, const cv::Mat_<double> &intrinsic,
const cv::Mat_<double> &dist_coeffs, double size, int thickness);
void convertImage(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, cv::Mat &image);
//--------------------------- default configuration -------------------------------
void InitParameter();
void InitParameter() {}
//------------------------------ helper methods -----------------------------------
// static void onMouse(int event, int x, int y, int flags, void *);
void setup(int argc, char **argv);
//----------------------------- data containers -----------------------------------
cv::Mat_<cv::Vec3b> image;
cv::Mat_<cv::Vec3b> im_draw;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
cv::Mat_<double> dist_coeffs; // = cv::Mat::zeros(4, 1, CV_64F);
cv::Mat_<double> intrinsic = cv::Mat_<double>::eye(3, 3);
Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();
int ul_lr = 0;
int start = 0, end_idx = 10;
cv::Point track_win[2];
std::string cam_file;
string filenames, base_dir, codebook_filename;
std::vector<std::string> object_names;
std::vector<v4r::triple<std::string, double, Eigen::Matrix4f>> objects;
double thr_conf = 0;
int live = -1;
bool loop = false;
/******************************************************************
* MAIN
*/
int main(int argc, char *argv[]) {
int sleep = 0;
char filename[PATH_MAX];
track_win[0] = cv::Point(0, 0);
track_win[1] = cv::Point(640, 480);
// config
InitParameter();
setup(argc, argv);
intrinsic(0, 0) = intrinsic(1, 1) = 525;
intrinsic(0, 2) = 320, intrinsic(1, 2) = 240;
if (cam_file.size() > 0) {
cv::FileStorage fs(cam_file, cv::FileStorage::READ);
fs["camera_matrix"] >> intrinsic;
fs["distortion_coefficients"] >> dist_coeffs;
}
cv::namedWindow("image", CV_WINDOW_AUTOSIZE);
// init recognizer
v4r::IMKRecognizer::Parameter param;
param.pnp_param.eta_ransac = 0.01;
param.pnp_param.max_rand_trials = 10000;
param.pnp_param.inl_dist_px = 2;
param.pnp_param.inl_dist_z = 0.02;
param.vc_param.cluster_dist = 40;
#ifdef USE_SIFT_GPU
param.cb_param.nnr = 1.000001;
param.cb_param.thr_desc_rnn = 0.25;
param.cb_param.max_dist = FLT_MAX;
v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_SIFTGPU());
#else
v4r::KeypointObjectRecognizer::Parameter param;
param.cb_param.nnr = 1.000001;
param.cb_param.thr_desc_rnn = 250.;
param.cb_param.max_dist = FLT_MAX;
v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_CVSIFT());
#endif
// // -- test imgd --
// param.cb_param.nnr = 1.000001;
// param.cb_param.thr_desc_rnn = 0.25;
// param.cb_param.max_dist = FLT_MAX;
// v4r::FeatureDetector_KD_FAST_IMGD::Parameter imgd_param(1000, 1.3, 4, 15);
// v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_FAST_IMGD(imgd_param));
// // -- end --
v4r::IMKRecognizer recognizer(param, detector, detector);
recognizer.setCameraParameter(intrinsic, dist_coeffs);
recognizer.setDataDirectory(base_dir);
if (!codebook_filename.empty())
recognizer.setCodebookFilename(codebook_filename);
if (object_names.size() == 0) { // take all direcotry names from the base_dir
object_names = v4r::io::getFoldersInDirectory(base_dir);
}
for (unsigned i = 0; i < object_names.size(); i++)
recognizer.addObject(object_names[i]);
std::cout << "Number of models: " << object_names.size() << std::endl;
recognizer.initModels();
cv::VideoCapture cap;
if (live != -1) {
cap.open(live);
cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
loop = true;
if (!cap.isOpened()) {
cout << "Could not initialize capturing...\n";
return 0;
}
}
// ---------------------- recognize object ---------------------------
for (int i = start; i <= end_idx || loop; i++) {
cout << "---------------- FRAME #" << i << " -----------------------" << endl;
if (live != -1) {
cap >> image;
} else {
snprintf(filename, PATH_MAX, filenames.c_str(), i);
cout << filename << endl;
image = cv::Mat_<cv::Vec3b>();
if (filenames.compare(filenames.size() - 3, 3, "pcd") == 0) {
if (pcl::io::loadPCDFile(filename, *cloud) == -1)
continue;
convertImage(*cloud, image);
} else {
image = cv::imread(filename, 1);
}
}
image.copyTo(im_draw);
recognizer.dbg = im_draw;
// cloud->clear();
// track
{
pcl::ScopeTime t("overall time");
if (cloud->width != (unsigned)image.cols || cloud->height != (unsigned)image.rows) {
recognizer.recognize(image, objects);
cout << "Use image only!" << endl;
} else {
recognizer.recognize(*cloud, objects);
cout << "Use image and cloud!" << endl;
}
} //-- overall time --
// debug out draw
// cv::addText( image, P::toString(1000./time)+std::string(" fps"), cv::Point(25,35), font);
cout << "Confidence value threshold for visualization: " << thr_conf << endl;
cout << "Found objects:" << endl;
for (unsigned j = 0; j < objects.size(); j++) {
cout << j << ": name= " << objects[j].first << ", conf= " << objects[j].second << endl;
if (objects[j].second >= thr_conf) {
cv::Point2f origin = drawCoordinateSystem(im_draw, objects[j].third, intrinsic, dist_coeffs, 0.1, 4);
// cv::addText( im_draw, objects[i].first+std::string(" (")+v4r::toString(objects[i].second)<<std::string(")"),
// origin+cv::Point(0,-10), font);
std::string txt = v4r::toString(j) + std::string(": ") + objects[j].first + std::string(" (") +
v4r::toString(objects[j].second) + std::string(")");
cv::putText(im_draw, txt, origin + cv::Point2f(0, 10), cv::FONT_HERSHEY_PLAIN, 1.5, CV_RGB(255, 255, 255), 2,
CV_AA);
}
}
cv::imshow("image", im_draw);
int key = cv::waitKey(sleep);
if (((char)key) == 27)
break;
if (((char)key) == 'r')
sleep = 1;
if (((char)key) == 's')
sleep = 0;
}
cv::waitKey(0);
return 0;
}
/******************************** SOME HELPER METHODS **********************************/
/*
* static void onMouse(int event, int x, int y, int flags, void *) {
if (x < 0 || x >= im_draw.cols || y < 0 || y >= im_draw.rows)
return;
if (event == CV_EVENT_LBUTTONUP && (flags & CV_EVENT_FLAG_LBUTTON)) {
track_win[ul_lr % 2] = cv::Point(x, y);
if (ul_lr % 2 == 0)
cout << "upper left corner: " << track_win[ul_lr % 2] << endl;
else
cout << "lower right corner: " << track_win[ul_lr % 2] << endl;
ul_lr++;
}
}
*/
/**
* setup
*/
void setup(int argc, char **argv) {
po::options_description general("General options");
general.add_options()("help,h", "show help message")("filenames,f",
po::value<std::string>(&filenames)->default_value(filenames),
"Input filename for recognition (printf-style)")(
"base_dir,d", po::value<std::string>(&base_dir)->default_value(base_dir), "Object model directory")(
"codebook_filename,c", po::value<std::string>(&codebook_filename), "Optional filename for codebook")(
"object_names,n", po::value<std::vector<std::string>>(&object_names)->multitoken(), "Object names")(
"start,s", po::value<int>(&start)->default_value(start), "start index")(
"end,e", po::value<int>(&end_idx)->default_value(end_idx), "end index")(
"cam_file,a", po::value<std::string>(&cam_file)->default_value(cam_file),
"camera calibration files (opencv format)")("live,l", po::value<int>(&live)->default_value(live),
"use live camera (OpenCV)")(
"thr_conf,t", po::value<double>(&thr_conf)->default_value(thr_conf),
"Confidence value threshold (visualization)");
po::options_description all("");
all.add(general);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(all).run(), vm);
po::notify(vm);
std::string usage = "";
if (vm.count("help")) {
std::cout << usage << std::endl;
std::cout << all;
return;
}
return;
}
/**
* drawConfidenceBar
*/
void drawConfidenceBar(cv::Mat &im, const double &conf) {
int bar_start = 50, bar_end = 200;
int diff = bar_end - bar_start;
int draw_end = diff * conf;
double col_scale = 255. / (double)diff;
cv::Point2f pt1(0, 30);
cv::Point2f pt2(0, 30);
cv::Vec3b col(0, 0, 0);
if (draw_end <= 0)
draw_end = 1;
for (int i = 0; i < draw_end; i++) {
col = cv::Vec3b(255 - (i * col_scale), i * col_scale, 0);
pt1.x = bar_start + i;
pt2.x = bar_start + i + 1;
cv::line(im, pt1, pt2, CV_RGB(col[0], col[1], col[2]), 8);
}
}
cv::Point2f drawCoordinateSystem(cv::Mat &im, const Eigen::Matrix4f &_pose, const cv::Mat_<double> &_intrinsic,
const cv::Mat_<double> &_dist_coeffs, double size, int thickness) {
Eigen::Matrix3f R = _pose.topLeftCorner<3, 3>();
Eigen::Vector3f t = _pose.block<3, 1>(0, 3);
Eigen::Vector3f pt0 = R * Eigen::Vector3f(0, 0, 0) + t;
Eigen::Vector3f pt_x = R * Eigen::Vector3f(size, 0, 0) + t;
Eigen::Vector3f pt_y = R * Eigen::Vector3f(0, size, 0) + t;
Eigen::Vector3f pt_z = R * Eigen::Vector3f(0, 0, size) + t;
cv::Point2f im_pt0, im_pt_x, im_pt_y, im_pt_z;
if (!_dist_coeffs.empty()) {
v4r::projectPointToImage(&pt0[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt0.x);
v4r::projectPointToImage(&pt_x[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_x.x);
v4r::projectPointToImage(&pt_y[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_y.x);
v4r::projectPointToImage(&pt_z[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_z.x);
} else {
v4r::projectPointToImage(&pt0[0], &_intrinsic(0), &im_pt0.x);
v4r::projectPointToImage(&pt_x[0], &_intrinsic(0), &im_pt_x.x);
v4r::projectPointToImage(&pt_y[0], &_intrinsic(0), &im_pt_y.x);
v4r::projectPointToImage(&pt_z[0], &_intrinsic(0), &im_pt_z.x);
}
cv::line(im, im_pt0, im_pt_x, CV_RGB(255, 0, 0), thickness);
cv::line(im, im_pt0, im_pt_y, CV_RGB(0, 255, 0), thickness);
cv::line(im, im_pt0, im_pt_z, CV_RGB(0, 0, 255), thickness);
return im_pt0;
}
void convertImage(const pcl::PointCloud<pcl::PointXYZRGB> &_cloud, cv::Mat &_image) {
_image = cv::Mat_<cv::Vec3b>(_cloud.height, _cloud.width);
for (unsigned v = 0; v < _cloud.height; v++) {
for (unsigned u = 0; u < _cloud.width; u++) {
cv::Vec3b &cv_pt = _image.at<cv::Vec3b>(v, u);
const pcl::PointXYZRGB &pt = _cloud(u, v);
cv_pt[2] = pt.r;
cv_pt[1] = pt.g;
cv_pt[0] = pt.b;
}
}
}
| 35.560647 | 119 | 0.612901 | v4r-tuwien |
f9567c21e5efba5d8f92be3281a01b12c87beb69 | 485 | cpp | C++ | src/tema fisa for/ex 4 e/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | 2 | 2021-11-27T18:29:32.000Z | 2021-11-28T14:35:47.000Z | src/tema fisa for/ex 4 e/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | src/tema fisa for/ex 4 e/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int a,b,x,i=0,cx;
cout<<"a= ";
cin>>a;
cout<<"b= ";
cin>>b;
x=a;
cx=x;
for(x; x<=b; x++)
{
cx=x;
while(cx!=0)
{
if(cx%10==0)
{
i=i+1;
cx=0;
}
else
{
cx=cx/10;
}
}
}
cout<<"Sunt "<<i<<" numere care contin cifra 0";
return 0;
}
| 13.472222 | 52 | 0.31134 | andrew-miroiu |
f959c903e7d50b358684b12ef918d3179555705b | 4,509 | cpp | C++ | unit_tests/main.cpp | obhi-d/hfn | 692203a25a13214ba8a0e2feddb8d6e78275c860 | [
"MIT"
] | null | null | null | unit_tests/main.cpp | obhi-d/hfn | 692203a25a13214ba8a0e2feddb8d6e78275c860 | [
"MIT"
] | null | null | null | unit_tests/main.cpp | obhi-d/hfn | 692203a25a13214ba8a0e2feddb8d6e78275c860 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "hfn/config.hpp"
#include "hfn/cxstring.hpp"
#include "hfn/digest.hpp"
#include "hfn/fnv1a.hpp"
#include "hfn/murmur3.hpp"
#include "hfn/rhid.hpp"
#include "hfn/type_hash.hpp"
#include "hfn/wyhash.hpp"
#include "hfn/xxhash.hpp"
#include <catch2/catch.hpp>
#include <iostream>
class type_name_test
{};
TEST_CASE("Asserts", "[asserts]")
{
static_assert(sizeof(hfn::uhash128_t) == 16, "Size is incorrect");
CHECK(hfn::digest<std::uint64_t>(0) == "0");
CHECK(hfn::type_name<type_name_test>() == "class type_name_test");
constexpr std::uint32_t cth = hfn::type_hash<std::string_view>();
static_assert(cth == 787592100);
CHECK(hfn::digest<std::uint64_t>(0xff64ffaadd41) == "1anlqvjcv7");
}
TEST_CASE("Murmur3", "[murmur]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
std::string combined = text + first + second;
hfn::murmur3_32 hash32;
hash32(text.c_str(), text.length());
CHECK(hash32() == hfn::murmur3::compute32(text.c_str(), text.length()));
hfn::murmur3_128 hash128;
hash128(text.c_str(), text.length());
CHECK(hash128() == hfn::murmur3::compute128(text.c_str(), text.length()));
std::string_view conflict1 = "vertexColor";
std::string_view conflict2 = "userDefined";
CHECK(hfn::murmur3::compute32(conflict2.data(), conflict2.length()) !=
hfn::murmur3::compute32(conflict1.data(), conflict1.length()));
hfn::cxstring s = "fixdStrinTest";
CHECK(s.hash() == hfn::murmur3::compute32(s.data(), s.size()));
}
TEST_CASE("Fnv1a", "[fnv1a]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
std::string combined = text + first + second;
hfn::fnv1a_32 hash32;
hash32(text.c_str(), text.length());
CHECK(hash32() == hfn::fnv1a::compute32(text.c_str(), text.length()));
hfn::fnv1a_64 hash64;
hash64(text.c_str(), text.length());
CHECK(hash64() == hfn::fnv1a::compute64(text.c_str(), text.length()));
hash32(first.c_str(), first.length());
hash32(second.c_str(), second.length());
CHECK(hash32() == hfn::fnv1a::compute32(combined.c_str(), combined.length()));
hash64(first.c_str(), first.length());
hash64(second.c_str(), second.length());
CHECK(hash64() == hfn::fnv1a::compute64(combined.c_str(), combined.length()));
}
TEST_CASE("Wyhash", "[wyhash]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
hfn::wyhash_32 hash32;
hash32(text.c_str(), text.length());
CHECK(hash32() == hfn::wyhash::compute32(text.c_str(), text.length()));
hfn::wyhash_64 hash64;
hash64(text.c_str(), text.length());
CHECK(hash64() == hfn::wyhash::compute64(text.c_str(), text.length()));
hash32 = hfn::wyhash_32();
hash32(text.c_str(), 10);
hash32(text.c_str() + 10, text.length() - 10);
// CHECK(hash32() == hfn::wyhash::compute32(text.c_str(), text.length()));
hash64 = hfn::wyhash_64();
hash64(text.c_str(), 10);
hash64(text.c_str() + 10, text.length() - 10);
// CHECK(hash64() == hfn::wyhash::compute64(text.c_str(), text.length()));
}
TEST_CASE("X3hash", "[xxhash]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
std::string combined = text + first + second;
hfn::xxhash_64 hash64;
hash64(text.c_str(), text.length());
CHECK(hash64() == hfn::xxhash::compute64(text.c_str(), text.length()));
hfn::xxhash_128 hash128;
hash64(text.c_str(), text.length());
// CHECK(hash128() == hfn::xxhash::compute128(text.c_str(), text.length()));
hash64(first.c_str(), first.length());
hash64(second.c_str(), second.length());
// CHECK(hash64() == hfn::xxhash::compute64(combined.c_str(), combined.length()));
hash128(first.c_str(), first.length());
hash128(second.c_str(), second.length());
// CHECK(hash128() == hfn::xxhash::compute128(combined.c_str(), combined.length()));
}
TEST_CASE("RHID", "[rhid]")
{
std::string text = "The director instructed us to do batshit crazy things in the past.";
std::string first = "First string.";
std::string second = "Second string.";
CHECK(hfn::rhid() == hfn::null_rhid);
hfn::rhid rhid;
rhid.update(text.c_str(), text.length());
CHECK((std::string)rhid == "mkjl131");
}
| 32.673913 | 92 | 0.664005 | obhi-d |
f959e804126995f18a040d22d82f3909666733f0 | 511 | cpp | C++ | Util/WebUrl.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 150 | 2015-01-14T15:06:38.000Z | 2018-08-28T09:34:17.000Z | Util/WebUrl.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 28 | 2015-05-11T02:45:39.000Z | 2018-08-24T11:43:17.000Z | Util/WebUrl.cpp | SoftlySpoken/gStore | b2cf71288ccef376640000965aff7c430101446a | [
"BSD-3-Clause"
] | 91 | 2015-05-04T09:52:41.000Z | 2018-08-18T13:02:15.000Z | #include "WebUrl.h"
using namespace std;
WebUrl::WebUrl() {}
WebUrl::~WebUrl() {}
string WebUrl::CutParam(string url, string param)
{
int index = url.find("?" + param + "=");
if (index < 0)
{
index = url.find("&" + param + "=");
}
if (index < 0)
return string();
int index2 = index + 1 + (param + "=").length();
string substr = url.substr(index2);
int endindex = substr.find("&");
if (endindex > 0)
{
string substr2 = substr.substr(0, endindex);
return substr2;
}
else
return substr;
} | 18.25 | 49 | 0.60274 | SoftlySpoken |
f9601f472091e6a18894fa6522a21e9160e64b8c | 4,786 | cpp | C++ | PageRepository/Source/Page.cpp | DiplodocusDB/PhysicalStorage | 9b110471d14300873a9067b25b0825727c178549 | [
"MIT"
] | null | null | null | PageRepository/Source/Page.cpp | DiplodocusDB/PhysicalStorage | 9b110471d14300873a9067b25b0825727c178549 | [
"MIT"
] | 19 | 2018-01-20T14:38:20.000Z | 2018-01-26T22:58:52.000Z | PageRepository/Source/Page.cpp | DiplodocusDB/PhysicalStorage | 9b110471d14300873a9067b25b0825727c178549 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018-2019 Xavier Leclercq
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "Page.h"
#include "PageFileRepository.h"
#include "Ishiko/Errors/IOErrorExtension.h"
#include <sstream>
namespace DiplodocusDB
{
Page::Page(size_t index)
: m_index(index), m_dataSize(0), m_availableSpace(sm_size - sm_startMarkerSize - sm_endMarkerSize), m_nextPage(0)
{
}
void Page::init()
{
memset(m_buffer, 0, sm_size);
}
size_t Page::index() const
{
return m_index;
}
size_t Page::dataSize() const
{
return m_dataSize;
}
size_t Page::maxDataSize() const
{
return (sm_size - sm_startMarkerSize - sm_endMarkerSize);
}
size_t Page::availableSpace() const
{
return m_availableSpace;
}
size_t Page::nextPage() const
{
return m_nextPage;
}
void Page::setNextPage(size_t index)
{
m_nextPage = index;
}
void Page::get(char* buffer,
size_t pos,
size_t n,
Ishiko::Error& error) const
{
if ((pos + n) <= m_dataSize)
{
memcpy(buffer, m_buffer + sm_startMarkerSize + pos, n);
}
else
{
std::stringstream message;
message << "Page::get (m_index: " << m_index << ", pos:" << pos << ", n:" << n
<< ") exceeds data size (m_datasize: " << m_dataSize << ")";
error.fail(-1, message.str(), __FILE__, __LINE__);
}
}
void Page::insert(const char* buffer, size_t bufferSize, size_t pos, Ishiko::Error& error)
{
if (bufferSize <= m_availableSpace)
{
char* p = (m_buffer + sm_startMarkerSize);
if (pos != m_dataSize)
{
memmove(p + pos + bufferSize, p + pos, (m_dataSize - pos));
}
memcpy(p + pos, buffer, bufferSize);
m_dataSize += bufferSize;
m_availableSpace -= bufferSize;
}
else
{
// TODO : add page details
error.fail(-1, "Failed to insert page", __FILE__, __LINE__);
}
}
void Page::erase(size_t pos, size_t n, Ishiko::Error& error)
{
memmove(m_buffer + sm_startMarkerSize + pos, m_buffer + sm_startMarkerSize + pos + n,
m_dataSize + sm_endMarkerSize - pos - n);
memset(m_buffer + sm_startMarkerSize + m_dataSize + sm_endMarkerSize - n, 0, n);
m_dataSize -= n;
m_availableSpace += n;
}
void Page::moveTo(size_t pos, size_t n, Page& targetPage, Ishiko::Error& error)
{
targetPage.insert(m_buffer + sm_startMarkerSize + pos, n, 0, error);
if (!error)
{
erase(pos, n, error);
}
}
void Page::write(std::ostream& output, Ishiko::Error& error) const
{
output.seekp(m_index * sm_size);
Ishiko::IOErrorExtension::Fail(error, output, __FILE__, __LINE__);
if (!error)
{
memcpy(m_buffer, "\xF0\x06\x00\x00\x00\x00", 6);
*((uint16_t*)(m_buffer + 6)) = (uint16_t)m_dataSize;
memcpy(m_buffer + sm_startMarkerSize + m_dataSize, "\xF1\x06\x00\x00\x00\x00\x00\x00", 8);
*((uint32_t*)(m_buffer + sm_startMarkerSize + m_dataSize + 2)) = m_nextPage;
output.write(m_buffer, sm_size);
Ishiko::IOErrorExtension::Fail(error, output, __FILE__, __LINE__);
}
}
void Page::read(std::istream& input, Ishiko::Error& error)
{
input.seekg(m_index * sm_size);
Ishiko::IOErrorExtension::Fail(error, input, __FILE__, __LINE__);
if (!error)
{
input.read(m_buffer, sm_size);
Ishiko::IOErrorExtension::Fail(error, input, __FILE__, __LINE__);
if (!error)
{
m_dataSize = *((uint16_t*)(m_buffer + 6));
m_availableSpace = sm_size - sm_startMarkerSize - sm_endMarkerSize - m_dataSize;
uint32_t nextPage = *((uint32_t*)(m_buffer + sm_startMarkerSize + m_dataSize + 2));
m_nextPage = nextPage;
}
}
}
}
| 29.361963 | 117 | 0.649603 | DiplodocusDB |
f96c117a5b81a2b6b456ee21a20b141634852997 | 8,129 | cpp | C++ | d20/a.cpp | webdeveloperukraine/adventofcode2020 | 4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34 | [
"MIT"
] | null | null | null | d20/a.cpp | webdeveloperukraine/adventofcode2020 | 4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34 | [
"MIT"
] | null | null | null | d20/a.cpp | webdeveloperukraine/adventofcode2020 | 4d4f36437da0fd4889f0fcbe28cad8fecb6f6f34 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#include "../helpers/string_helpers.cpp"
typedef long long int ll;
struct Tile{
ll id;
vector<string> pattern;
int width, height;
Tile(){ throw runtime_error("No Way!"); }
Tile(ll id, vector<string> pattern) : id(id), pattern(pattern){
height = pattern.size();
width = pattern[0].size();
}
void flipx(){
for(int i=0;i<height;i++){
for(int j=0;j<width/2;j++){
swap(pattern[i][j], pattern[i][width-j-1]);
}
}
}
void flipy(){
for(int i=0;i<height/2;i++){
swap(pattern[i], pattern[height-i-1]);
}
}
void rotate()
{
vector<string> res;
for(int i=0;i<width;i++){
string s;
for(int j=0;j<height;j++){
s.push_back(pattern[j][i]);
}
reverse(s.begin(), s.end());
res.push_back(s);
}
pattern = res;
}
};
unordered_map<ll, Tile> input;
void prepare()
{
string s;
vector<string> pat;
ll id;
while(getline(cin, s)){
if(s[0] == 'T'){
string str = split_line(s, " ")[1];
id = stoll(str.substr(0, str.size()-1));
continue;
}
if(s == ""){
input.insert(make_pair(id, Tile(id, pat)));
pat.resize(0);
continue;
}
pat.push_back(s);
}
input.insert(make_pair(id, Tile(id, pat)));
}
string get_top_line(Tile& t)
{
return t.pattern[0];
}
string get_left_line(Tile& t)
{
string s;
for(int i=t.height-1;i>=0;i--){
s.push_back(t.pattern[i][0]);
}
return s;
}
string get_bottom_line(Tile& t)
{
string s = t.pattern[t.pattern.size()-1];
reverse(s.begin(), s.end());
return s;
}
string get_right_line(Tile& t)
{
string s;
for(int i=0;i<t.height;i++){
s.push_back(t.pattern[i][9]);
}
return s;
}
ll line_to_num(string s)
{
ll n = 0;
for(int i=0;i<s.size();i++){
if(s[i] == '#') n = n | 1;
if(s.size()-1 != i) n <<= 1;
}
return n;
}
unordered_map<ll, ll> arr;
unordered_map<ll, vector<int>> cnts;
void prepare_other()
{
if(arr.size()) return;
string s;
for(auto& itt : input){
auto& it = itt.second;
s = get_top_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
s = get_bottom_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
s = get_left_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
s = get_right_line(it);
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
reverse(s.begin(), s.end());
arr.insert(make_pair(line_to_num(s), it.id));
cnts[line_to_num(s)].push_back(it.id);
}
}
ll first()
{
prepare_other();
unordered_map<ll, int> garr;
for(auto& it : cnts){
if(it.second.size() == 1){
garr[arr[it.first]]++;
}
}
ll res = 1;
for(auto& it : garr){
if(it.second == 4){
res *= it.first;
}
}
return res;
}
//////////////////////////////////////////////////////////
struct MT{
MT *top=nullptr, *right=nullptr, *bottom=nullptr, *left=nullptr;
ll id;
};
unordered_map<ll, MT*> mt_map;
ll get_else_id(ll a, ll id)
{
auto& v = cnts[a];
if(v[0] == id) return v[1];
return v[0];
}
void transform(ll id, ll a, string side)
{
Tile& t = input[id];
for(int i=0;i<8;i++){
ll b;
if(side == "top") b = line_to_num(get_top_line(t));
if(side == "right") b = line_to_num(get_right_line(t));
if(side == "bottom") b = line_to_num(get_bottom_line(t));
if(side == "left") b = line_to_num(get_left_line(t));
if(b == a){
if(side == "top" || side == "bottom"){
t.flipx();
} else {
t.flipy();
}
return;
}
t.rotate();
if(i == 3){
t.flipx();
}
}
throw runtime_error("No Way!");
}
unordered_set<ll> r_done;
void req(MT* a)
{
if(!a) return;
if(r_done.count(a->id)) return;
r_done.insert(a->id);
Tile& t = input[a->id];
ll top = line_to_num(get_top_line(t));
ll right = line_to_num(get_right_line(t));
ll bottom = line_to_num(get_bottom_line(t));
ll left = line_to_num(get_left_line(t));
MT *mt_top = nullptr, *mt_right = nullptr, *mt_bottom = nullptr, *mt_left = nullptr;
if(cnts[top].size() > 1){
ll id = get_else_id(top, a->id);
if(mt_map.count(id)){
a->top = mt_map[id];
} else {
mt_top = new MT;
mt_map[id] = mt_top;
mt_top->id = id;
a->top = mt_top;
transform(id, top, "bottom");
}
}
if(cnts[right].size() > 1){
ll id = get_else_id(right, a->id);
if(mt_map.count(id)){
a->right = mt_map[id];
} else {
mt_right = new MT;
mt_map[id] = mt_right;
mt_right->id = id;
a->right = mt_right;
transform(id, right, "left");
}
}
if(cnts[bottom].size() > 1){
ll id = get_else_id(bottom, a->id);
if(mt_map.count(id)){
a->bottom = mt_map[id];
} else {
mt_bottom = new MT;
mt_map[id] = mt_bottom;
mt_bottom->id = id;
a->bottom = mt_bottom;
transform(id, bottom, "top");
}
}
if(cnts[left].size() > 1){
ll id = get_else_id(left, a->id);
if(mt_map.count(id)){
a->left = mt_map[id];
} else {
mt_left = new MT;
mt_map[id] = mt_left;
mt_left->id = id;
a->left = mt_left;
transform(id, left, "right");
}
}
req(a->top);
req(a->right);
req(a->bottom);
req(a->left);
}
bool done[12][12];
char image[12*8][12*8];
void fill(Tile& t, int x, int y)
{
if(x > 11 || y > 11) throw runtime_error("No Way!");
for(int i=1;i<t.height-1;i++){
for(int j=1;j<t.width-1;j++){
image[y*8+i-1][x*8+j-1] = t.pattern[i][j];
}
}
}
void req_build(MT* a, int x, int y)
{
if(!a) return;
if(done[x][y]) return;
done[x][y] = true;
fill(input[a->id], x, y);
req_build(a->right, x+1, y);
req_build(a->bottom, x, y+1);
}
void print_image()
{
for(int i=0;i<12*8;i++){
cout << "_";
}
cout << endl;
for(int i=0;i<12*8;i++){
for(int j=0;j<12*8;j++){
cout << image[i][j];
}
cout << endl;
}
}
void rotate_image()
{
int W = 8*12;
char new_image[W][W];
for(int i=0;i<W;i++){
for(int j=0;j<W;j++){
new_image[i][j] = image[j][i];
}
for(int j=0;j<W/2;j++){
swap(new_image[i][j], new_image[i][W-j-1]);
}
}
for(int i=0;i<W;i++){
for(int j=0;j<W;j++){
image[i][j] = new_image[i][j];
}
}
}
void flip_image()
{
int W = 8*12;
for(int i=0;i<W;i++){
for(int j=0;j<W/2;j++){
swap(image[i][j], image[i][W-j-1]);
}
}
}
vector<string> monster = {
" # ",
"# ## ## ###",
" # # # # # # "
};
int find_monsters()
{
int res = 0;
int W = 8*12;
int MW = monster[0].size();
int MH = monster.size();
for(int i=0;i<W;i++){
for(int j=0;j<W;j++){
if(W-i >= MH && W-j >= MW){
bool found = true;
for(int ii=0;ii<MH;ii++){
for(int jj=0;jj<MW;jj++){
if(monster[ii][jj] == '#' && image[i+ii][j+jj] != '#'){
found = false;
break;
}
}
}
if(found){
res++;
for(int ii=0;ii<MH;ii++){
for(int jj=0;jj<MW;jj++){
if(monster[ii][jj] == '#'){
image[i+ii][j+jj] = 'O';
}
}
}
}
}
}
}
return res;
}
ll second()
{
// preapre other things
prepare_other();
// Build an image
ll one_id = input.begin()->first;
MT* part = new MT;
part->id = one_id;
mt_map[one_id] = part;
req(part);
// write image to array
while(part->top){ part = part->top; }
while(part->left){ part = part->left; }
req_build(part,0,0);
// Find monsters
bool found = false;
for(int i=0;i<10;i++){
if(find_monsters()){
found = true;
break;
}
rotate_image();
if(i == 4) flip_image();
}
if(!found){
throw runtime_error("Not Found Monsters :(");
}
int res = 0;
for(int i=0;i<8*12;i++){
for(int j=0;j<8*12;j++){
if(image[i][j] == '#') res++;
}
}
return res;
}
int main()
{
prepare();
cout << "First: " << first() << endl;
cout << "Second: " << second() << endl;
// Print image with monsters
print_image();
return 0;
}
| 17.905286 | 85 | 0.558986 | webdeveloperukraine |
f96c326286a20d184db4bb728848da1abf9f28fe | 2,663 | cpp | C++ | source/line.cpp | Zylon-D-Lite/drawingPrototype | 60caa86e72ad7fd36aed15679b003747c69e81c6 | [
"MIT"
] | null | null | null | source/line.cpp | Zylon-D-Lite/drawingPrototype | 60caa86e72ad7fd36aed15679b003747c69e81c6 | [
"MIT"
] | null | null | null | source/line.cpp | Zylon-D-Lite/drawingPrototype | 60caa86e72ad7fd36aed15679b003747c69e81c6 | [
"MIT"
] | null | null | null | #include "./line.hpp"
const png::rgba_pixel Line::WHITE_PIXEL = png::rgba_pixel(255, 255, 255, 255);
const png::rgba_pixel Line::BLACK_PIXEL = png::rgba_pixel(0, 0, 0, 255);
const png::rgba_pixel Line::TRANSPARENT_PIXEL = png::rgba_pixel(0, 0, 0, 0);
const png::rgba_pixel Line::RED_PIXEL = png::rgba_pixel(255, 0, 0, 255);
const png::rgba_pixel Line::GREEN_PIXEL = png::rgba_pixel(0, 255, 0, 255);
const png::rgba_pixel Line::BLUE_PIXEL = png::rgba_pixel(0, 0, 255, 255);
bool Line::isAdjacent(Coordinate i_curr, Coordinate i_adjacent) {
if (abs(i_curr.x - i_adjacent.x) <= 1 &&
abs(i_curr.y - i_adjacent.y) <= 1) {
return true;
}
return false;
}
std::pair<bool, std::string> Line::check(const png::image<png::rgba_pixel>& i_image,
png::rgba_pixel i_on_pixel) {
auto firstCheck = check();
bool noProblems = true;
if (firstCheck.first == true) {
return firstCheck;
}
std::string returnMessage{};
for (auto coordinate : lineData) {
if (i_image[coordinate.y][coordinate.x].red != i_on_pixel.red ||
i_image[coordinate.y][coordinate.x].green != i_on_pixel.green ||
i_image[coordinate.y][coordinate.x].blue != i_on_pixel.blue) {
returnMessage += "Pixel value mismatch at: x = "
+ std::to_string(coordinate.x) + ", y = "
+ std::to_string(coordinate.y) + "\n";
noProblems = false;
}
}
if (!noProblems)
return std::pair<bool, std::string>(false, firstCheck.second + returnMessage);
return std::pair<bool, std::string>(true, "No problems detected");
}
std::pair<bool, std::string> Line::check() {
bool noProblems = true;
std::string returnMessage{};
for (size_t i = 0; i < lineData.size() - 1; ++i) {
if (!isAdjacent(lineData[i], lineData[i+1])) {
returnMessage += "Discontinued line at: x1 = "
+ std::to_string(lineData[i].x) + ", y1 = "
+ std::to_string(lineData[i].y) + ", x2 = "
+ std::to_string(lineData[i + 1].x) + ", y2 = "
+ std::to_string(lineData[i + 1].y) + "\n";
noProblems = false;
}
}
if (!noProblems)
return std::pair<bool, std::string>(false, returnMessage);
return std::pair<bool, std::string>(true, "No problems detected");
}
inline void Line::insert(size_t offset, const Coordinate& input) {
lineData.insert(lineData.begin() + offset, input);
}
void Line::append(const std::vector<Coordinate>::iterator& beg_it,
const std::vector<Coordinate>::iterator& end_it)
{
lineData.insert(lineData.end(), beg_it, end_it);
}
| 39.161765 | 86 | 0.607585 | Zylon-D-Lite |
f96d0aa3ae182e22ac149151167544afb5674954 | 15,323 | cpp | C++ | ppm_image.cpp | gulesh/pixmap-ops | 573afdd349d7e4913d7dbc60f0b9d3edd33b39ca | [
"MIT"
] | null | null | null | ppm_image.cpp | gulesh/pixmap-ops | 573afdd349d7e4913d7dbc60f0b9d3edd33b39ca | [
"MIT"
] | null | null | null | ppm_image.cpp | gulesh/pixmap-ops | 573afdd349d7e4913d7dbc60f0b9d3edd33b39ca | [
"MIT"
] | null | null | null | #include "ppm_image.h"
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace agl;
using namespace std;
ppm_image::ppm_image()
{
imageWidth = 0;
imageHeight = 0;
pixelArray= nullptr;
}
ppm_image::ppm_image(int w, int h)
{
imageWidth = w;
imageHeight =h;
//clear();
pixelArray = new ppm_pixel*[h];
for (int i =0; i<h ;i++)
{
pixelArray[i] = new ppm_pixel[w];
}
}
ppm_image::ppm_image(const ppm_image& orig)
{
//clear();
imageWidth = orig.imageWidth;
imageHeight = orig.imageHeight;
pixelArray = new ppm_pixel*[imageHeight];
for (int i =0; i<imageHeight ;i++)
{
pixelArray[i] = new ppm_pixel[imageWidth];
}
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
pixelArray[j][k]= orig.pixelArray[j][k];
}
}
}
ppm_image& ppm_image::operator=(const ppm_image& orig)
{
if (&orig == this) // protect against self-assignment
{
return *this;
}
//clear();
imageHeight = orig.imageHeight;
imageWidth = orig.imageWidth;
pixelArray = new ppm_pixel*[imageHeight];
for (int i =0; i<imageHeight ;i++)
{
pixelArray[i] = new ppm_pixel[imageWidth];
}
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
pixelArray[j][k]= orig.pixelArray[j][k];
}
}
return *this;
}
void ppm_image::clear()
{
//pixelArray = nullptr;
}
ppm_image::~ppm_image()
{
for (int i = 0; i < imageHeight; i++)
{
delete[] pixelArray[i];
}
delete[] pixelArray;
}
bool ppm_image::load(const std::string& filename)
{
ifstream file(filename);
cout<<"filename " << filename <<endl;
string p3;
int value;
if (!file) // true if the file is valid
{
cout << "Cannot load file: " << filename << endl;
return 1;
}
file >> p3; //this will store "P3"
file >> value; //width
imageWidth = value;
file >> value; //height
imageHeight = value;
file >> value; //this will give the number 255
//memory cleaning
//clear();
pixelArray = new ppm_pixel*[imageHeight];
for (int i =0; i<imageHeight ;i++)
{
pixelArray[i] = new ppm_pixel[imageWidth];
}
while(file)
{
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
ppm_pixel tempPixel;
int pixel;
//r value of the pixel
file >> pixel ;
tempPixel.r = (unsigned char) pixel;
//g value of the pixel
file >> pixel ;
tempPixel.g = (unsigned char) pixel;
//b value of the pixel
file >> pixel ;
tempPixel.b = (unsigned char) pixel;
//pixel with r,g,b valus stored in the 2D array
pixelArray[j][k]= tempPixel;
}
}
return 0;
}
return 0;
}
bool ppm_image::save(const std::string& filename) const
{
ofstream file(filename);
if(!file)
{
return 1;
}
string p3 = "P3";
file << p3 << endl; //this will store "P3"
file << imageWidth << endl; //width
file << imageHeight << endl; //height
int value = 255;
file << value << endl;//this will give the number 255
for (int j = 0; j < imageHeight; j++) //rows
{
for (int k = 0; k < imageWidth; k++) //columns
{
ppm_pixel tempPixel;
tempPixel = pixelArray[j][k];
//r value of the pixel stored in the file
file << (int) tempPixel.r <<endl;
//cout << (int) tempPixel.r <<endl;
//g value of the pixel stored in the file
file << (int) tempPixel.g << endl;
//cout << (int) tempPixel.g <<endl;
//b value of the pixel stored in the file
file << (int) tempPixel.b << endl;
//cout << (int) tempPixel.b <<endl;
}
}
file.close();
return 0;
}
ppm_image ppm_image::resize(int w, int h) const
{
int oldPixelC, oldPixelR;
ppm_image result = ppm_image( w, h);
for (int i = 0 ; i < h; i++)
{
for (int j = 0; j < w ;j++)
{
oldPixelR = floor( (i * (imageHeight - 1))/(h-1) );
oldPixelC = floor( (j * (imageWidth - 1))/(w-1) );
result.pixelArray[i][j].r = pixelArray[oldPixelR][oldPixelC].r;
result.pixelArray[i][j].g = pixelArray[oldPixelR][oldPixelC].g;
result.pixelArray[i][j].b = pixelArray[oldPixelR][oldPixelC].b;
}
}
return result;
}
//got a unique image
// ppm_image ppm_image::flip_horizontal() const
// {
// ppm_image result = ppm_image(imageWidth,imageHeight);
// for (int i = 0 ; i <imageHeight; i++)
// {
// for (int j = 0 ; j < imageWidth ;j++)
// {
// result.pixelArray[i][j]= pixelArray[imageHeight - j - 1][j];
// }
// }
// return result;
// }
ppm_image ppm_image::flip_horizontal() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i <imageHeight; i++)
{
for (int j = 0 ; j < imageWidth ;j++)
{
result.pixelArray[i][j]= pixelArray[imageHeight - i - 1][j];
}
}
return result;
}
ppm_image ppm_image::subimage(int startx, int starty, int w, int h) const
{
ppm_image result = ppm_image(w,h);
for (int i = 0 ; i < h; i++)
{
for (int j = 0; j < w ;j++)
{
result.pixelArray[i][j].r = pixelArray[i+startx][j+starty].r;
result.pixelArray[i][j].g = pixelArray[i+startx][j+starty].g;
result.pixelArray[i][j].b = pixelArray[i+startx][j+starty].b;
}
}
return result;
}
void ppm_image::replace(const ppm_image& image, int startx, int starty)
{
for (int i = 0 ; i < image.imageHeight; i++)
{
for (int j = 0; j < image.imageWidth ;j++)
{
pixelArray[i+starty][j+startx] = image.pixelArray[i][j];
}
}
}
ppm_image ppm_image::alpha_blend(const ppm_image& other, float alpha) const
{
int blendedR, blendedG, blendedB;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
blendedR = (int) ( ((float) (pixelArray[i][j].r )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].r)) * alpha ) ;
blendedG = (int) ( ((float) (pixelArray[i][j].g )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].g)) * alpha ) ;
blendedB = (int) ( ((float) (pixelArray[i][j].b )) * (1 - alpha) + ((float) ( other.pixelArray[i][j].b)) * alpha ) ;
//setting new pixel color
result.pixelArray[i][j].r = (unsigned char) blendedR;
result.pixelArray[i][j].g = (unsigned char) blendedG;
result.pixelArray[i][j].b = (unsigned char) blendedB;
}
}
return result;
}
ppm_image ppm_image::gammaCorrect(float gamma) const
{
int gCorrectedR, gCorrectedG, gCorrectedB;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
gCorrectedR = 255 * pow(((float) pixelArray[i][j].r)/255, 1/gamma);
gCorrectedG = 255 * pow(((float) pixelArray[i][j].g)/255, 1/gamma);
gCorrectedB = 255 * pow(((float) pixelArray[i][j].b)/255, 1/gamma);
//setting new pixel color
result.pixelArray[i][j].r = (unsigned char) gCorrectedR;
result.pixelArray[i][j].g = (unsigned char) gCorrectedG;
result.pixelArray[i][j].b = (unsigned char) gCorrectedB;
}
}
return result;
}
ppm_image ppm_image::grayscale() const
{
int r,g,b,weightedAvg;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0 ; j < imageWidth ;j++)
{
ppm_pixel modifyingPixel = pixelArray[i][j];
r = modifyingPixel.r;
g = modifyingPixel.g;
b = modifyingPixel.b;
weightedAvg = 0.3 * r + 0.59 * g + 0.11 * b;
modifyingPixel.b = weightedAvg;
modifyingPixel.g = weightedAvg;
modifyingPixel.r = weightedAvg;
result.pixelArray[i][j] = modifyingPixel;
}
}
return result;
}
ppm_pixel ppm_image::get(int row, int col) const
{
return pixelArray[row][col];
}
void ppm_image::set(int row, int col, const ppm_pixel& c)
{
pixelArray[row][col].r = c.r;
pixelArray[row][col].g = c.g;
pixelArray[row][col].b = c.b;
}
int ppm_image::height() const
{
return imageHeight;
}
int ppm_image::width() const
{
return imageWidth;
}
ppm_image ppm_image::swirlColors() const
{
ppm_pixel tempPixel;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j] = pixelArray[i][j];
tempPixel.r = result.pixelArray[i][j].r ;
result.pixelArray[i][j].r = result.pixelArray[i][j].g;
result.pixelArray[i][j].g = result.pixelArray[i][j].b;
result.pixelArray[i][j].b = tempPixel.r;
}
}
return result;
}
ppm_image ppm_image::distortImage() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
int distorted_j = (j + (int) (20*sin(i/10)) + imageWidth) % imageWidth;
int distorted_i = (i + (int) (20*cos(j/10)) + imageHeight) % imageHeight;
result.pixelArray[i][j] = pixelArray[distorted_i][distorted_j];
}
}
return result;
}
ppm_image ppm_image::invertColor() const
{
int modifiedR, modifiedG, modifiedB;
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
modifiedR = 255 - (int) pixelArray[i][j].r ;
modifiedG = 255 - (int) pixelArray[i][j].g ;
modifiedB = 255 - (int) pixelArray[i][j].b ;
//setting new pixel color
result.pixelArray[i][j].r = (unsigned char) modifiedR;
result.pixelArray[i][j].g = (unsigned char) modifiedG;
result.pixelArray[i][j].b = (unsigned char) modifiedB;
}
}
return result;
}
ppm_image ppm_image::rotate90() const
{
int oldPixelC = 0;
ppm_image result = ppm_image(imageHeight,imageWidth);
for (int i = 0 ; i < imageWidth; i++)
{
int oldPixelR = imageHeight -1;
for (int j = 0; j < imageHeight ;j++)
{
result.pixelArray[i][j] = pixelArray[oldPixelR][oldPixelC];
oldPixelR -= 1;
}
oldPixelC += 1;
}
return result;
}
ppm_image ppm_image::lightest(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::max(pixelArray[i][j].r, other.pixelArray[i][j].r);
result.pixelArray[i][j].g = std::max(pixelArray[i][j].g, other.pixelArray[i][j].g);
result.pixelArray[i][j].b = std::max(pixelArray[i][j].b, other.pixelArray[i][j].b);
}
}
return result;
}
ppm_image ppm_image::darkest(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::min(pixelArray[i][j].r, other.pixelArray[i][j].r);
result.pixelArray[i][j].g = std::min(pixelArray[i][j].g, other.pixelArray[i][j].g);
result.pixelArray[i][j].b = std::min(pixelArray[i][j].b, other.pixelArray[i][j].b);
}
}
return result;
}
ppm_image ppm_image::difference(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r);
result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r);
result.pixelArray[i][j].r = std::min(0, pixelArray[i][j].r - other.pixelArray[i][j].r);
}
}
return result;
}
ppm_image ppm_image::multiply(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].r * other.pixelArray[i][j].r);
result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].g * other.pixelArray[i][j].g);
result.pixelArray[i][j].r = std::max(255, pixelArray[i][j].b * other.pixelArray[i][j].b);
}
}
return result;
}
ppm_image ppm_image::redOnly(const ppm_image& other) const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = std::max(pixelArray[i][j].r, other.pixelArray[i][j].r);
}
}
return result;
}
//not working as expected need to edit
ppm_image ppm_image::addBorder() const
{
int resultImageH = imageHeight+2;
int resultImageW = imageWidth+2 ;
ppm_pixel p{(unsigned char)255,(unsigned char) 255,(unsigned char) 255};
ppm_image result = ppm_image(resultImageW,resultImageH);
for (int i = 0 ; i < resultImageH; i++)
{
if(i == 0 || i == resultImageH -1)
{
for (int j = 0; j < resultImageW ;j++)
{
result.pixelArray[i][j] = p;
}
}
else
{
for (int j = 0; j < resultImageW ;j++)
{
if((j == 0) || (j == resultImageW-1))
{
result.pixelArray[i][j] = p;
}
else
{
result.pixelArray[i][j] = pixelArray[i+1][j+1];
}
}
}
}
return result;
}
ppm_image ppm_image::redExtract() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = pixelArray[i][j].r;
result.pixelArray[i][j].g = 0;
result.pixelArray[i][j].b = 0;
}
}
return result;
}
ppm_image ppm_image::greenExtract() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r =
result.pixelArray[i][j].g = pixelArray[i][j].g;
result.pixelArray[i][j].b = 0;
}
}
return result;
}
ppm_image ppm_image::blueExtract() const
{
ppm_image result = ppm_image(imageWidth,imageHeight);
for (int i = 0 ; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth ;j++)
{
result.pixelArray[i][j].r = 0;
result.pixelArray[i][j].g = 0;
result.pixelArray[i][j].b = pixelArray[i][j].b;
}
}
return result;
}
| 26.835377 | 125 | 0.559812 | gulesh |
f96f63c2c2a06f5743891f2fd243ece7b1615cb4 | 608 | cpp | C++ | server/src/extension_queue/queue.cpp | valmat/queueServer | 6626e99cd4fccca6f2ae17b8cc33ef151b651b5d | [
"BSD-3-Clause"
] | 4 | 2017-09-25T12:23:22.000Z | 2019-02-19T14:15:46.000Z | server/src/extension_queue/queue.cpp | valmat/queueServer | 6626e99cd4fccca6f2ae17b8cc33ef151b651b5d | [
"BSD-3-Clause"
] | 1 | 2019-02-25T17:53:32.000Z | 2019-02-27T06:57:35.000Z | server/src/extension_queue/queue.cpp | valmat/queueServer | 6626e99cd4fccca6f2ae17b8cc33ef151b651b5d | [
"BSD-3-Clause"
] | 1 | 2019-02-19T13:42:29.000Z | 2019-02-19T13:42:29.000Z | /**
* RocksServer plugin
* https://github.com/valmat/queueServer
*/
#include "../include.h"
#include "RequestMoveFirstPref.h"
#include "RequestFirstPref.h"
#include "RequestGetIncr.h"
using namespace RocksServer;
/*
* Create plugin
*
* @param extension object of Extension
* @param rdb wrapped object of RocksDB
*/
PLUGIN(Extension extension, RocksDBWrapper& rdb)
{
extension
.bind("/get-incr", new RequestGetIncr(rdb))
.bind("/first-pref", new RequestFirstPref(rdb))
.bind("/move-fpref", new RequestMoveFirstPref(rdb));
;
} | 20.266667 | 65 | 0.641447 | valmat |
f9711d8fdecf29560f186cbd4c4f86ee0342ff38 | 3,739 | cpp | C++ | Core-src/AnalyzeWindow.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 6 | 2015-03-04T19:41:12.000Z | 2022-03-27T09:44:25.000Z | Core-src/AnalyzeWindow.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 20 | 2015-03-03T21:02:20.000Z | 2021-08-02T13:26:59.000Z | Core-src/AnalyzeWindow.cpp | HaikuArchives/BeAE | b57860a81266dd465655ec98b7524406bfde27aa | [
"BSD-3-Clause"
] | 8 | 2015-02-23T19:10:32.000Z | 2020-10-26T08:03:00.000Z | /*
Copyright (c) 2003, Xentronix
Author: Frans van Nispen (frans@xentronix.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer. Redistributions in binary form must
reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of Xentronix nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Window.h>
#include <View.h>
#include <InterfaceKit.h>
#include <stdlib.h>
#include <stdio.h>
#include "Globals.h"
#include "AnalyzeWindow.h"
#include "main.h"
#define UPDATE 'updt'
#define QUIT 'quit'
#define SET 'setF'
/*******************************************************
*
*******************************************************/
AnalyzeWindow::AnalyzeWindow(BRect r, const char *name)
: BWindow(r,name, B_FLOATING_WINDOW_LOOK,B_FLOATING_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_AVOID_FOCUS)
{
// 25 frames per second by default
m_frames = 25;
m_count = 0;
// set the playHook
m_index = Pool.SetPlayHook( _PlayBuffer, PLAY_HOOKS/2, (void*)this);
SetPulseRate(50000);
Run();
Show();
}
/*******************************************************
*
*******************************************************/
void AnalyzeWindow::PlayBuffer(float *buffer, size_t size)
{
}
/*******************************************************
*
*******************************************************/
void AnalyzeWindow::_PlayBuffer(float *buffer, size_t size, void *cookie)
{
AnalyzeWindow *win = (AnalyzeWindow*)cookie; // cast to our own clas
// process effect
win->PlayBuffer(buffer, size);
// update with frames/second
win->m_count -= size;
if (win->m_count <0){
win->m_count = (int)Pool.system_frequency*2/win->m_frames;
win->PostMessage(UPDATE);
}
}
/*******************************************************
*
*******************************************************/
int32 AnalyzeWindow::FramesPerSecond()
{
return m_frames;
}
void AnalyzeWindow::SetFramesPerSecond(int32 frames)
{
m_frames = frames;
}
/*******************************************************
*
*******************************************************/
bool AnalyzeWindow::QuitRequested(){
Pool.RemovePlayHook( _PlayBuffer, m_index );
return true;
}
/*******************************************************
*
*******************************************************/
void AnalyzeWindow::MessageReceived(BMessage* msg){
BView *view;
switch(msg->what){
case UPDATE:
view = ChildAt(0);
if (view) view->Invalidate();
break;
default:
BWindow::MessageReceived(msg);
}
}
| 30.647541 | 101 | 0.61487 | HaikuArchives |
f972af1ee36532247bf190e9808e6e5d4a624d8e | 708 | hpp | C++ | include/RadonFramework/IO/ConsoleUI/With.hpp | tak2004/RF_Console | b2a1114b4e948281c64b085eb407926704ecc7cb | [
"Apache-2.0"
] | null | null | null | include/RadonFramework/IO/ConsoleUI/With.hpp | tak2004/RF_Console | b2a1114b4e948281c64b085eb407926704ecc7cb | [
"Apache-2.0"
] | null | null | null | include/RadonFramework/IO/ConsoleUI/With.hpp | tak2004/RF_Console | b2a1114b4e948281c64b085eb407926704ecc7cb | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <RadonFramework/IO/ConsoleUI/Component.hpp>
#include <RadonFramework/IO/ConsoleUI/ComponentOperator.hpp>
#include <RadonFramework/IO/ConsoleUI/State.hpp>
namespace RadonFramework::IO::ConsoleUI
{
template <class T>
struct With : public ComponentOperator
{
template <int N>
With(char const (&CString)[N], T&& Value)
: m_Temporary(Value), m_State(RF_HASH(CString))
{
}
void operator()(Component& Receiver) override
{
void* result;
if(Receiver.States().Get(m_State, result))
{
(*reinterpret_cast<State<T>*>(result)) = m_Temporary;
}
}
const T m_Temporary;
const RF_Type::UInt64 m_State;
};
}
namespace RF_CUI = RadonFramework::IO::ConsoleUI; | 21.454545 | 60 | 0.710452 | tak2004 |
f97a4336ab04e9446d773096c45ca5d954126da6 | 1,205 | cpp | C++ | Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-04/08_letter_combinations_of_a_phone_number.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "../header.h"
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.length() == 0) {
return {};
}
unordered_map<char, string> m;
m['2'] = "abc";
m['3'] = "def";
m['4'] = "ghi";
m['5'] = "jkl";
m['6'] = "mno";
m['7'] = "pqrs";
m['8'] = "tuv";
m['9'] = "wxyz";
vector<string> res;
int d_index = 0;
string current = "";
helper(digits, m, res, current, d_index);
return res;
}
private:
void helper(const string& digits, unordered_map<char, string>& m, vector<string>& res, string current, int d_index) {
if (current.length() == digits.length()) {
res.push_back(current);
return;
}
string candidate = m[digits[d_index]];
for (int i = 0; i < candidate.size(); ++i) {
current.push_back(candidate[i]);
helper(digits, m, res, current, d_index+1);
current.pop_back();
}
}
};
int main() {
string digits;
cin >> digits;
vector<string> res = Solution().letterCombinations(digits);
for (auto r: res) {
cout << r << endl;
}
return 0;
} | 25.104167 | 121 | 0.509544 | qiufengyu |
f97d1a9270894f9dc0a87e4b98415bcd3e15cd13 | 2,071 | hpp | C++ | Libs/SceneGraph/PlantNode.hpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | Libs/SceneGraph/PlantNode.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | Libs/SceneGraph/PlantNode.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#ifndef CAFU_TREE_NODE_HPP_INCLUDED
#define CAFU_TREE_NODE_HPP_INCLUDED
#include "Node.hpp"
#include "Plants/Tree.hpp"
struct PlantDescriptionT;
class PlantDescrManT;
namespace cf
{
namespace SceneGraph
{
class PlantNodeT : public GenericNodeT
{
public:
/// The constructor.
PlantNodeT();
/// Constructor for creating a PlantNodeT from parameters.
PlantNodeT(const PlantDescriptionT* PlantDescription, unsigned long RandomSeed, const Vector3dT& Position, const Vector3fT& Angles);
/// Named constructor.
static PlantNodeT* CreateFromFile_cw(std::istream& InFile, aux::PoolT& Pool, LightMapManT& LMM, SHLMapManT& SMM, PlantDescrManT& PDM);
/// The destructor.
~PlantNodeT();
// The NodeT interface.
void WriteTo(std::ostream& OutFile, aux::PoolT& Pool) const;
const BoundingBox3T<double>& GetBoundingBox() const;
// void InitDrawing();
bool IsOpaque() const { return false; };
void DrawAmbientContrib(const Vector3dT& ViewerPos) const;
//void DrawStencilShadowVolumes(const Vector3dT& LightPos, const float LightRadius) const;
//void DrawLightSourceContrib(const Vector3dT& ViewerPos, const Vector3dT& LightPos) const;
void DrawTranslucentContrib(const Vector3dT& ViewerPos) const;
private:
PlantNodeT(const PlantNodeT&); ///< Use of the Copy Constructor is not allowed.
void operator = (const PlantNodeT&); ///< Use of the Assignment Operator is not allowed.
TreeT m_Tree;
unsigned long m_RandomSeed;
Vector3dT m_Position;
Vector3fT m_Angles;
std::string m_DescrFileName;
BoundingBox3dT m_Bounds;
};
}
}
#endif
| 30.455882 | 146 | 0.633028 | dns |
f97f1b80cd830250828379c88056dfae3aa0c8f6 | 3,247 | hpp | C++ | modules/engine/include/randar/Render/Geometry.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | 1 | 2016-11-12T02:43:29.000Z | 2016-11-12T02:43:29.000Z | modules/engine/include/randar/Render/Geometry.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | modules/engine/include/randar/Render/Geometry.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | #ifndef RANDAR_RENDER_GEOMETRY_HPP
#define RANDAR_RENDER_GEOMETRY_HPP
#include <randar/Render/Primitive.hpp>
#include <randar/Render/ShaderProgram.hpp>
#include <randar/Render/VertexBuffer.hpp>
namespace randar
{
class Geometry : public GraphicsContextResource
{
public:
VertexBuffer vertices;
IndexBuffer indices;
/**
* Primitive used by the geometry.
*
* Describes how vertices should be interpreted.
*/
Primitive primitive = randar::Primitive::Triangle;
/**
* Constructors.
*/
Geometry();
Geometry(GraphicsContext& context);
/**
* Assignment.
*/
Geometry(const Geometry& other);
Geometry& operator =(const Geometry& other);
Geometry copy();
/**
* Destructor.
*/
~Geometry();
/**
* Identifies the Randar object type.
*/
std::string kind() const;
/**
* Initializes the geometry on a context.
*/
using GraphicsContextResource::initialize;
virtual void initialize() override;
/**
* Uninitializes the geometry from a context.
*
* Nothing happens if the geometry is not initialized. No exceptions are
* thrown upon failure.
*/
virtual void uninitialize() override;
/**
* Whether the geometry is initialized on a context.
*/
bool isInitialized();
/**
* Syncs local data to OpenGL.
*/
void sync();
/**
* Clears vertices and indices of the geometry.
*
* Primitive remains unchanged.
*/
void clear();
/**
* Adds a vertex to the geometry's available vertices.
*
* Returns an index that identifies the vertex in this geometry's
* available vertices, which is later used to construct a shape.
*
* If the vertex already exists in the available geometry, it is not
* appended and the existing index is returned.
*
* This does not manipulate the shape of the geometry.
*
* In most cases, you can use the simplified append method instead.
*/
uint32_t useVertex(const Vertex& vertex);
/**
* Appends a vertex to the geometry shape.
*
* This method simply calls appendVertex, captures the index of the
* vertex in this geometry's available vertices, and calls appendIndex
* with it.
*
* This is the preferred way to append a vertex to geometry.
*/
void append(const Vertex& vertex);
/**
* Appends another geometry to this geometry.
*/
void append(Geometry& other);
void append(Geometry& other, const Transform& transform);
/**
* Saves and loads the geometry from disk.
*/
void save(const randar::Path& filepath);
void load(const randar::Path& filepath);
};
/**
* Node.js helper.
*/
#ifdef SWIG
%newobject geometry;
#endif
Geometry* geometry();
}
#endif
| 25.769841 | 80 | 0.558978 | litty-studios |
f97f4fbe581321f5293e8955e8f7d600fd259aba | 13,240 | cpp | C++ | dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp | rudals0215/AR-streaming-with-MPEG-DASH | 7c9f24a2eed7f756e51451670286a11351a6b877 | [
"MIT"
] | null | null | null | dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp | rudals0215/AR-streaming-with-MPEG-DASH | 7c9f24a2eed7f756e51451670286a11351a6b877 | [
"MIT"
] | null | null | null | dependencies/HDRTools/common/src/DisplayGammaAdjustHLG.cpp | rudals0215/AR-streaming-with-MPEG-DASH | 7c9f24a2eed7f756e51451670286a11351a6b877 | [
"MIT"
] | 1 | 2021-07-07T00:53:49.000Z | 2021-07-07T00:53:49.000Z | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* <OWNER> = British Broadcasting Corporation (BBC).
* <ORGANIZATION> = BBC.
* <YEAR> = 2015
*
* Copyright (c) 2015, BBC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the <ORGANIZATION> nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
*************************************************************************************
* \file DisplayGammaAdjustHLG.cpp
*
* \brief
* DisplayGammaAdjustHLG class
* This is an implementation of the display gamma normalization process
* in BBC's Hybrid Log-Gamma system (HLG).
* A complete documentation of this process is available in
* the BBC's response to the MPEG call for evidence on HDR and WCG video coding
* (document m36249, available at:
* http://wg11.sc29.org/doc_end_user/documents/112_Warsaw/wg11/m36249-v2-m36249.zip)
*
* \author
* - Matteo Naccari <matteo.naccari@bbc.co.uk>
* - Manish Pindoria <manish.pindoria@bbc.co.uk>
*
*************************************************************************************
*/
#include "Global.H"
#include "DisplayGammaAdjustHLG.H"
#include "ColorTransformGeneric.H"
namespace hdrtoolslib {
//-----------------------------------------------------------------------------
// Constructor / destructor implementation
//-----------------------------------------------------------------------------
DisplayGammaAdjustHLG::DisplayGammaAdjustHLG(double gamma, double scale)
{
m_tfScale = 12.0; //19.6829249; // transfer function scaling - assuming super whites
m_linScale = scale;
m_gamma = gamma;
m_transformY = NULL;
}
DisplayGammaAdjustHLG::~DisplayGammaAdjustHLG()
{
m_transformY = NULL;
}
void DisplayGammaAdjustHLG::setup(Frame *frame) {
ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, (const double **) &m_transformY);
}
void DisplayGammaAdjustHLG::forward(double &comp0, double &comp1, double &comp2)
{
double vComp0, vComp1, vComp2;
//vComp0 = comp0 / m_tfScale;
//vComp1 = comp1 / m_tfScale;
//vComp2 = comp2 / m_tfScale;
vComp0 = comp0;
vComp1 = comp1;
vComp2 = comp2;
double ySignal = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
comp0 = (float) (vComp0 * yDisplay) ;
comp1 = (float) (vComp1 * yDisplay) ;
comp2 = (float) (vComp2 * yDisplay) ;
}
void DisplayGammaAdjustHLG::forward(const double iComp0, const double iComp1, const double iComp2, double *oComp0, double *oComp1, double *oComp2)
{
double vComp0, vComp1, vComp2;
//vComp0 = iComp0 / m_tfScale;
//vComp1 = iComp1 / m_tfScale;
//vComp2 = iComp2 / m_tfScale;
vComp0 = iComp0;
vComp1 = iComp1;
vComp2 = iComp2;
double ySignal = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
*oComp0 = (float) (vComp0 * yDisplay) ;
*oComp1 = (float) (vComp1 * yDisplay) ;
*oComp2 = (float) (vComp2 * yDisplay) ;
}
void DisplayGammaAdjustHLG::inverse(double &comp0, double &comp1, double &comp2)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
double vComp0, vComp1, vComp2;
vComp0 = dMax(0.0, (double) comp0 / m_linScale);
vComp1 = dMax(0.0, (double) comp1 / m_linScale);
vComp2 = dMax(0.0, (double) comp2 / m_linScale);
double yDisplay = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
comp0 = (float) (vComp0 * yDisplayGamma) ;
comp1 = (float) (vComp1 * yDisplayGamma) ;
comp2 = (float) (vComp2 * yDisplayGamma) ;
}
void DisplayGammaAdjustHLG::inverse(const double iComp0, const double iComp1, const double iComp2, double *oComp0, double *oComp1, double *oComp2)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
double vComp0, vComp1, vComp2;
vComp0 = dMax(0.0, (double) iComp0 / m_linScale);
vComp1 = dMax(0.0, (double) iComp1 / m_linScale);
vComp2 = dMax(0.0, (double) iComp2 / m_linScale);
double yDisplay = dMax(0.000001, m_transformY[R_COMP] * vComp0 + m_transformY[G_COMP] * vComp1 + m_transformY[B_COMP] * vComp2);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
*oComp0 = (float) (vComp0 * yDisplayGamma) ;
*oComp1 = (float) (vComp1 * yDisplayGamma) ;
*oComp2 = (float) (vComp2 * yDisplayGamma) ;
}
void DisplayGammaAdjustHLG::forward(Frame *frame)
{
if (frame->m_isFloat == TRUE && frame->m_compSize[Y_COMP] == frame->m_compSize[Cb_COMP]) {
if (frame->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, &transformY);
for (int index = 0; index < frame->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
//vComp[component] = frame->m_floatComp[component][index] / m_tfScale;
vComp[component] = frame->m_floatComp[component][index];
}
double ySignal = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
for(int component = 0; component < 3; component++) {
frame->m_floatComp[component][index] = (float) (vComp[component] * yDisplay) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
}
}
void DisplayGammaAdjustHLG::forward(Frame *out, const Frame *inp)
{
if (inp->m_isFloat == TRUE && out->m_isFloat == TRUE && inp->m_size == out->m_size && inp->m_compSize[Y_COMP] == inp->m_compSize[Cb_COMP]) {
if (inp->m_colorSpace == CM_RGB && out->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(inp->m_colorPrimaries, &transformY);
for (int index = 0; index < inp->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
//vComp[component] = inp->m_floatComp[component][index] / m_tfScale;
vComp[component] = inp->m_floatComp[component][index];
}
double ySignal = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
double yDisplay = m_linScale * pow(ySignal, m_gamma) / ySignal;
for(int component = 0; component < 3; component++) {
out->m_floatComp[component][index] = (float) (vComp[component] * yDisplay) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
else {
out->copy((Frame *) inp);
}
}
else if (inp->m_isFloat == FALSE && out->m_isFloat == FALSE && inp->m_size == out->m_size && inp->m_bitDepth == out->m_bitDepth) {
out->copy((Frame *) inp);
}
}
void DisplayGammaAdjustHLG::inverse(Frame *frame)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
if (frame->m_isFloat == TRUE && frame->m_compSize[Y_COMP] == frame->m_compSize[Cb_COMP]) {
if (frame->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(frame->m_colorPrimaries, &transformY);
for (int index = 0; index < frame->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
vComp[component] = dMax(0.0, (double) frame->m_floatComp[component][index] / m_linScale);
}
double yDisplay = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
for(int component = 0; component < 3; component++) {
frame->m_floatComp[component][index] = (float) (vComp[component] * yDisplayGamma) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
}
}
void DisplayGammaAdjustHLG::inverse(Frame *out, const Frame *inp)
{
// 1. reverse any "burnt-in" system gamma to remove any display reference and leave only scene referred linear light
// 2. scale RGB signals by a factor of m_tfscale (12 if not using super-white, otherwise 19.68)
// 3. apply OETF (signals now in the range of 0.0 to 1.00/1.09 (i.e. super white)
// Step 3 is not performed in this process, but instead it is done as part of the TransferFunction Class.
if (inp->m_isFloat == TRUE && out->m_isFloat == TRUE && inp->m_size == out->m_size && inp->m_compSize[Y_COMP] == inp->m_compSize[Cb_COMP]) {
if (inp->m_colorSpace == CM_RGB && out->m_colorSpace == CM_RGB) {
double vComp[3];
const double *transformY = NULL;
ColorTransformGeneric::setYConversion(inp->m_colorPrimaries, &transformY);
for (int index = 0; index < inp->m_compSize[Y_COMP]; index++) {
for(int component = 0; component < 3; component++) {
vComp[component] = dMax(0.0, (double) inp->m_floatComp[component][index] / m_linScale);
}
double yDisplay = dMax(0.000001, transformY[R_COMP] * vComp[R_COMP] + transformY[G_COMP] * vComp[G_COMP] + transformY[B_COMP] * vComp[B_COMP]);
//double yDisplayGamma = m_tfScale * pow(yDisplay,(1.0 - m_gamma) / m_gamma);
double yDisplayGamma = pow(yDisplay,(1.0 - m_gamma) / m_gamma);
for(int component = 0; component < 3; component++) {
out->m_floatComp[component][index] = (float) (vComp[component] * yDisplayGamma) ;
}
}
// reset the pointer (just for safety
transformY = NULL;
}
}
else if (inp->m_isFloat == FALSE && out->m_isFloat == FALSE && inp->m_size == out->m_size && inp->m_bitDepth == out->m_bitDepth) {
out->copy((Frame *) inp);
}
}
} // namespace hdrtoolslib
//-----------------------------------------------------------------------------
// End of file
//-----------------------------------------------------------------------------
| 43.84106 | 151 | 0.649245 | rudals0215 |
f98335835b564975be345d5087b058a382845d32 | 5,545 | cpp | C++ | src/TransitionHandler.cpp | MacaroniDamage/FabulousNeopixelFirmware | 4ebf638f9d053629dd2eb81039cc153755d55668 | [
"MIT"
] | 2 | 2021-06-05T15:26:29.000Z | 2021-06-05T23:50:09.000Z | src/TransitionHandler.cpp | MacaroniDamage/FabulousNeopixelFirmware | 4ebf638f9d053629dd2eb81039cc153755d55668 | [
"MIT"
] | null | null | null | src/TransitionHandler.cpp | MacaroniDamage/FabulousNeopixelFirmware | 4ebf638f9d053629dd2eb81039cc153755d55668 | [
"MIT"
] | null | null | null | /**
* @file TransitionHandler.cpp
* @author MacaroniDamage
* @brief Executes state machine that handel transitions to different
* stages
* @version 0.1
* @date 2020-12-18
*
*
*/
#include "TransitionHandler.h"
/** Configures the instace so that
* it triggers the wished state machine
**/
void TransitionHandler::playTransition(Transition transition, uint32_t targetColor)
{
this->targetColor = targetColor;
this->currentColor = _pController->getCurrentColor();
this->currentBrightness = _pController->getCurrentBrightness();
this->transition = transition;
this->transitionState = STATE_1;
}
//sets the target brightness and gets the current values from the controller
void TransitionHandler::playTransition(uint8_t targetBrightness, Transition transition)
{
this->targetBrightness = targetBrightness;
this->currentColor = _pController->getCurrentColor();
this->currentBrightness = _pController->getCurrentBrightness();
this->transition = transition;
this->transitionState = STATE_1;
}
//Just sets the transition values and gets the current values from the controller
void TransitionHandler::playTransition(Transition transition)
{
this->currentColor = _pController->getCurrentColor();
this->currentBrightness = _pController->getCurrentBrightness();
this->transition = transition;
this->transitionState = STATE_1;
Serial.println("Stage: " + String(transitionState));
}
void TransitionHandler::setTransitionMode(TransitionMode transitionMode)
{
this->transitionMode = transitionMode;
}
TransitionState TransitionHandler::getCurrentTransitionState()
{
return this->transitionState;
}
//Sets the targetBrightness to the minimun value sets the new color
//and set the targetBrigtness to the wished value
void TransitionHandler::Fade()
{
switch (transitionState)
{
case STDBY:
transitionState = STDBY;
break;
case STATE_1: //Fade_Out
//temporaily saves the brightness to set it later.
this->oldBrightness = this->currentBrightness;
//turns the brightness of the stripe to minimal brightness
this->targetBrightness = MIN_BRIGHTNESS;
//changes the state
transitionState = STATE_2;
break;
case STATE_2: //SET COLOR
if (currentBrightness <= targetBrightness)
{
//Tells the Controller what color is now the current one
//and dates the stripe up
transitionState = STATE_3;
//Dates the currentColor and currentBrightness up
this->currentColor = this->targetColor;
this->targetBrightness = this->oldBrightness;
//Executes the changeColor function if transitionMode is in
//a standart state so it won't be executed durig an animation
if (transitionMode == STANDARD)
_pController->changeColor(currentColor);
}
else
{
transitionState = STATE_2;
}
break;
case STATE_3: //Fade IN
if (currentBrightness < targetBrightness)
{
transitionState = STATE_3;
}
else
{
currentColor = targetColor;
transitionState = STDBY;
transitionisPlayed = false;
}
break;
default:
transitionState = STDBY;
}
}
// change to a target brightness
void TransitionHandler::gotoBrightness()
{
int16_t actBrightness = (int16_t)currentBrightness;
if (brightnessUpdateTimer.isTimerReady())
{
if (targetBrightness > currentBrightness)
{
actBrightness += BRIGHTNESS_STEP;
if (actBrightness > targetBrightness)
currentBrightness = targetBrightness;
else
currentBrightness = actBrightness;
}
else if (targetBrightness < currentBrightness)
{
actBrightness -= BRIGHTNESS_STEP;
if (actBrightness < targetBrightness)
currentBrightness = targetBrightness;
else
currentBrightness = (uint8_t)actBrightness;
}
//Refreshes the stripe
_pController->changeBrightness(currentBrightness);
//Refreshed the update timer
brightnessUpdateTimer.startTimer(BRIGHTNESS_UPDATE);
}
}
//Sets the targetBrightnes to the minimum brightness and waits until it is achieved
//set the transition state then to Standby
void TransitionHandler::FadeOut()
{
switch (transitionState)
{
case STATE_1:
this->targetBrightness = MIN_BRIGHTNESS;
this->transitionState = STATE_2;
break;
case STATE_2:
if (currentBrightness <= targetBrightness)
{
this->transitionState = STDBY;
}
break;
}
}
//Waits until the targetBrightness is equal or higher then the currentBrighness
//and the set the TargetHandler to Standby
void TransitionHandler::FadeIn()
{
switch (transitionState)
{
case STATE_1:
//Will be modified so the changeBrightness method
//refreshes the solid color
this->transitionState = STATE_3;
break;
case STATE_3:
if (currentBrightness >= targetBrightness)
{
this->transitionState = STDBY;
}
break;
}
}
uint8_t TransitionHandler::getCurrentBrightness(){
return currentBrightness;
}
uint8_t TransitionHandler::getTargetBrightness(){
return targetBrightness;
}
void TransitionHandler::loop()
{
if (transitionState != STDBY)
{
switch (transition)
{
case FADE_TO:
this->Fade();
this->gotoBrightness();
break;
case FADE_OUT:
this->FadeOut();
this->gotoBrightness();
break;
case FADE_IN:
this->FadeIn();
this->gotoBrightness();
break;
default:
_pController->changeColor(targetColor);
this->transitionState = STDBY;
break;
}
}
}
| 25.911215 | 87 | 0.70532 | MacaroniDamage |
f9847bb79e52b2a28bc39127617f9544416c7709 | 7,076 | cp | C++ | Win32/Sources/Application/SMTP_Queue/CSMTPView.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Win32/Sources/Application/SMTP_Queue/CSMTPView.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Win32/Sources/Application/SMTP_Queue/CSMTPView.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// Source for CSMTPView class
#include "CSMTPView.h"
#include "CFontCache.h"
#include "CMailboxWindow.h"
#include "CMbox.h"
#include "CMulberryApp.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSMTPToolbar.h"
#include "CSplitterView.h"
#include "CToolbarView.h"
// Static members
BEGIN_MESSAGE_MAP(CSMTPView, CMailboxView)
ON_WM_CREATE()
ON_WM_DESTROY()
END_MESSAGE_MAP()
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CSMTPView::CSMTPView()
{
mSender = NULL;
}
// Default destructor
CSMTPView::~CSMTPView()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
const int cTitleHeight = 16;
int CSMTPView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMailboxView::OnCreate(lpCreateStruct) == -1)
return -1;
int width = lpCreateStruct->cx;
int height = lpCreateStruct->cy;
UINT focus_indent = Is3Pane() ? 3 : 0;
// Create footer first so we get its scaled height
mFooter.CreateDialogItems(IDD_SMTPFOOTER, &mFocusRing);
mFooter.ModifyStyle(0, WS_CLIPSIBLINGS);
mFooter.ModifyStyleEx(0, WS_EX_DLGMODALFRAME);
CRect rect;
mFooter.GetWindowRect(rect);
mFooter.ExecuteDlgInit(MAKEINTRESOURCE(IDD_SMTPFOOTER));
mFooter.SetFont(CMulberryApp::sAppSmallFont);
mFooter.MoveWindow(CRect(focus_indent, height - focus_indent - rect.Height(), width - focus_indent, height - focus_indent));
mFooter.ShowWindow(SW_SHOW);
// Subclass footer controls for our use
mTotalText.SubclassDlgItem(IDC_SMTPTOTALTXT, &mFooter);
mTotalText.SetFont(CMulberryApp::sAppSmallFont);
// Server table
mSMTPTable.Create(NULL, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP,
CRect(focus_indent, focus_indent + cTitleHeight, width - focus_indent, height - focus_indent - rect.Height()), &mFocusRing, IDC_MAILBOXTABLE);
mSMTPTable.ModifyStyleEx(0, WS_EX_NOPARENTNOTIFY, 0);
mSMTPTable.ResetFont(CFontCache::GetListFont());
mSMTPTable.SetColumnInfo(mColumnInfo);
mSMTPTable.SetContextMenuID(IDR_POPUP_CONTEXT_MAILBOX);
mSMTPTable.SetContextView(static_cast<CView*>(GetOwningWindow()));
// Get titles
mSMTPTitles.Create(NULL, NULL, WS_CHILD | WS_VISIBLE, CRect(focus_indent, focus_indent, width - focus_indent - 16, focus_indent + cTitleHeight), &mFocusRing, IDC_STATIC);
mSMTPTitles.SetFont(CFontCache::GetListFont());
mFocusRing.AddAlignment(new CWndAlignment(&mSMTPTitles, CWndAlignment::eAlign_TopWidth));
PostCreate(&mSMTPTable, &mSMTPTitles);
// Create alignment details
mFocusRing.AddAlignment(new CWndAlignment(&mFooter, CWndAlignment::eAlign_BottomWidth));
mFocusRing.AddAlignment(new CWndAlignment(&mSMTPTable, CWndAlignment::eAlign_WidthHeight));
// Set status
SetOpen();
return 0;
}
void CSMTPView::OnDestroy(void)
{
// Do standard close behaviour
DoClose();
// Do default action now
CMailboxView::OnDestroy();
}
// Make a toolbar appropriate for this view
void CSMTPView::MakeToolbars(CToolbarView* parent)
{
// Create a suitable toolbar
CSMTPToolbar* tb = new CSMTPToolbar;
mToolbar = tb;
tb->InitToolbar(Is3Pane(), parent);
// Toolbar must listen to view to get activate/deactive broadcast
Add_Listener(tb);
// Now give toolbar to its view as standard buttons
parent->AddToolbar(tb, GetTable(), CToolbarView::eStdButtonsGroup);
}
// Set window state
void CSMTPView::ResetState(bool force)
{
if (!GetMbox())
return;
// Get name as cstr
CString name(GetMbox()->GetAccountName());
// Get visible state
bool visible = GetParentFrame()->IsWindowVisible();
// Get default state
CMailboxWindowState* state = &CPreferences::sPrefs->mSMTPWindowDefault.Value();
// Do not set if empty
CRect set_rect = state->GetBestRect(CPreferences::sPrefs->mSMTPWindowDefault.GetValue());
if (!set_rect.IsRectNull())
{
// Clip to screen
::RectOnScreen(set_rect, NULL);
// Reset bounds
GetParentFrame()->SetWindowPos(nil, set_rect.left, set_rect.top, set_rect.Width(), set_rect.Height(), SWP_NOACTIVATE | SWP_NOZORDER | (visible ? 0 : SWP_NOREDRAW));
}
// Prevent window updating while column info is invalid
bool locked = GetParentFrame()->LockWindowUpdate();
// Adjust size of tables
ResetColumns(state->GetBestColumnInfo(CPreferences::sPrefs->mServerWindowDefault.GetValue()));
// Adjust menus
SetSortBy(state->GetSortBy());
GetMbox()->ShowBy(state->GetShowBy());
// Sorting button
//mSortBtn.SetPushed(state->GetShowBy() == cShowMessageDescending);
if (force)
SaveDefaultState();
if (locked)
GetParentFrame()->UnlockWindowUpdate();
// Do zoom
if (state->GetState() == eWindowStateMax)
GetParentFrame()->ShowWindow(SW_SHOWMAXIMIZED);
// Init the preview state once if we're in a window
if (!Is3Pane() && !mPreviewInit)
{
mMessageView->ResetState();
mPreviewInit = true;
}
// Init splitter pos
if (!Is3Pane() && (state->GetSplitterSize() != 0))
GetMailboxWindow()->GetSplitter()->SetRelativeSplitPos(state->GetSplitterSize());
if (!force)
{
if (!GetParentFrame()->IsWindowVisible())
GetParentFrame()->ActivateFrame();
RedrawWindow();
}
else
RedrawWindow();
}
// Save current state as default
void CSMTPView::SaveDefaultState(void)
{
// Only do this if a mailbox has been set
if (!GetMbox())
return;
// Get bounds
CRect bounds;
WINDOWPLACEMENT wp;
GetParentFrame()->GetWindowPlacement(&wp);
bool zoomed = (wp.showCmd == SW_SHOWMAXIMIZED);
bounds = wp.rcNormalPosition;
// Sync column widths
for(int i = 0; i < mColumnInfo.size(); i++)
mColumnInfo[i].column_width = GetTable()->GetColWidth(i + 1);
// Get current match item
CMatchItem match;
// Check whether quitting
bool is_quitting = CMulberryApp::sApp->IsQuitting();
// Add info to prefs
CMailboxWindowState state(nil, &bounds, zoomed ? eWindowStateMax : eWindowStateNormal, &mColumnInfo,
(ESortMessageBy) GetMbox()->GetSortBy(),
(EShowMessageBy) GetMbox()->GetShowBy(),
is_quitting ? NMbox::eViewMode_ShowMatch : NMbox::eViewMode_All,
&match,
Is3Pane() ? 0 : GetMailboxWindow()->GetSplitter()->GetRelativeSplitPos());
if (CPreferences::sPrefs->mSMTPWindowDefault.Value().Merge(state))
CPreferences::sPrefs->mSMTPWindowDefault.SetDirty();
}
| 30.110638 | 172 | 0.71368 | mulberry-mail |
f988503b86a58fce537ef8d81853b4f82278da5b | 111,478 | cpp | C++ | src/newsview.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | 9 | 2020-04-01T04:15:22.000Z | 2021-09-26T21:03:47.000Z | src/newsview.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | 17 | 2020-04-02T19:38:40.000Z | 2020-04-12T05:47:08.000Z | src/newsview.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************/
/* SOURCE CONTROL VERSIONS */
/*---------------------------------------------------------------------------*/
/* */
/* Version Date Time Author / Comment (optional) */
/* */
/* $Log: newsview.cpp,v $
/* Revision 1.1 2010/07/21 17:14:57 richard_wood
/* Initial checkin of V3.0.0 source code and other resources.
/* Initial code builds V3.0.0 RC1
/*
/* Revision 1.3 2010/04/11 13:47:40 richard_wood
/* FIXED - Export custom headers does not work, they are lost
/* FIXED - Foreign month names cause crash
/* FIXED - Bozo bin not being exported / imported
/* FIXED - Watch & ignore threads not being imported / exported
/* FIXED - Save article (append to existing file) missing delimiters between existing text in file and new article
/* ADDED - Add ability to customise signature font size + colour
/* First build for 2.9.15 candidate.
/*
/* Revision 1.2 2009/07/08 18:32:32 richard_wood
/* Fixed lots of new installer bugs, spell checker dialog bug, updated the vcredist file to 2008 SP1 version, plus lots of other bug fixes.
/*
/* Revision 1.1 2009/06/09 13:21:29 richard_wood
/* *** empty log message ***
/*
/* Revision 1.6 2009/01/29 17:22:35 richard_wood
/* Tidying up source code.
/* Removing dead classes.
/*
/* Revision 1.5 2009/01/02 13:34:33 richard_wood
/* Build 6 : BETA release
/*
/* [-] Fixed bug in Follow up dialog - Quoted text should be coloured.
/* [-] Fixed bug in New post/Follow up dialog - if more than 1 page of text
/* and typing at or near top the text would jump around.
/*
/* Revision 1.4 2008/10/15 23:30:23 richard_wood
/* Fixed bug in EMail reply dialog, if a ReplyTo header was present, the email field in the dialog picked up the address from the previous email sent.
/*
/* Revision 1.3 2008/09/19 14:51:35 richard_wood
/* Updated for VS 2005
/*
/* */
/*****************************************************************************/
/**********************************************************************************
Copyright (c) 2003, Albert M. Choy
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Microplanet, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************/
// Newsview.cpp : implementation of the CNewsView class
//
// 4-18-96 amc When an article is destroyed by the DEL key, the Flatview
// and the thread view update each other. I am no longer
// using the odb callback stuff
//
#include "stdafx.h"
#include "News.h"
#include "Newsdoc.h"
#include "Newsview.h"
#include "mainfrm.h"
#include "globals.h"
#include "hints.h"
#include "hourglas.h"
#include "tmutex.h"
#include "posttmpl.h"
#include "custmsg.h"
#include "tglobopt.h"
#include "pobject.h"
#include "names.h"
#include "tasker.h"
#include "nggenpg.h"
#include "ngoverpg.h" // TNewsGroupOverrideOptions
#include "ngfltpg.h" // TNewsGroupFilterPage
#include "tsigpage.h" // TSigPage (per newsgroup sigs)
#include "warndlg.h"
#include "gotoart.h"
#include "ngpurg.h"
#include "ngutil.h"
#include "tnews3md.h" // TNews3MDIChildWnd
#include "mlayout.h" // TMdiLayout
#include "artview.h" // TArticleFormView
#include "statunit.h" // TStatusUnit
#include "thrdlvw.h" // TThreadListView
#include "utilrout.h"
#include "rgbkgrnd.h"
#include "rgwarn.h"
#include "rgfont.h"
#include "rgui.h"
#include "rgswit.h"
#include "log.h"
#include "utilsize.h"
//#include "hctldrag.h"
#include "rules.h" // DoRuleSubstitution()
#include "TAskFol.h" // how to handle "followup-to: poster"
#include "fileutil.h" // UseProgramPath
#include "genutil.h" // GetThreadView()
#include "licutil.h"
#include "nglist.h" // TNewsGroupUseLock
#include "server.h"
#include "newsdb.h" // gpStore
#include "vfilter.h" // TViewFilter
#include "utilerr.h"
#include "servcp.h" // TServerCountedPtr
#include "limithdr.h" // CPromptLimitHeaders
#include "usrdisp.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
extern TGlobalOptions * gpGlobalOptions;
extern TNewsTasker* gpTasker;
const UINT CNewsView::idCaptionTimer = 32100;
const UINT CNewsView::idSelchangeTimer = 32101;
enum MessageType {MESSAGE_TYPE_BUG, MESSAGE_TYPE_SUGGESTION,
MESSAGE_TYPE_SEND_TO_FRIEND};
MessageType giMessageType; // what type of message are we composing?
#define FLATHDR_ID 9001
#define SCROLL_BMP_CX 15
#define BASE_CLASS CListView
/////////////////////////////////////////////////////////////////////////////
// CNewsView
IMPLEMENT_DYNCREATE(CNewsView, CListView)
BEGIN_MESSAGE_MAP(CNewsView, BASE_CLASS)
ON_WM_CREATE()
ON_WM_SIZE()
ON_COMMAND(IDR_NGPOPUP_OPEN, OnNgpopupOpen)
ON_COMMAND(IDR_NGPOPUP_UNSUBSCRIBE, OnNewsgroupUnsubscribe)
ON_COMMAND(IDR_NGPOPUP_CATCHUPALLARTICLES, OnNgpopupCatchupallarticles)
ON_COMMAND(IDC_NGPOPUP_MANUAL_RULE, OnNgpopupManualRule)
ON_COMMAND(ID_NEWSGROUP_POSTARTICLE, OnNewsgroupPostarticle)
ON_COMMAND(ID_ARTICLE_FOLLOWUP, OnArticleFollowup)
ON_COMMAND(ID_ARTICLE_REPLYBYMAIL, OnArticleReplybymail)
ON_COMMAND(ID_ARTICLE_MAILTOFRIEND, OnArticleForward)
ON_COMMAND(ID_FORWARD_SELECTED, OnForwardSelectedArticles)
ON_UPDATE_COMMAND_UI(ID_ARTICLE_REPLYBYMAIL, OnUpdateArticleReplybymail)
ON_UPDATE_COMMAND_UI(ID_FORWARD_SELECTED, OnUpdateForwardSelectedArticles)
// ON_UPDATE_COMMAND_UI(ID_HELP_SENDBUGREPORT, OnUpdateHelpSendBugReport)
// ON_UPDATE_COMMAND_UI(ID_HELP_SENDPRODUCTSUGGESTION, OnUpdateHelpSendSuggestion)
ON_UPDATE_COMMAND_UI(ID_FILE_SEND_MAIL, OnUpdateSendToFriend)
ON_WM_DESTROY()
ON_UPDATE_COMMAND_UI(ID_ARTICLE_FOLLOWUP, OnUpdateArticleFollowup)
ON_UPDATE_COMMAND_UI(ID_NEWSGROUP_POSTARTICLE, OnUpdateNewsgroupPostarticle)
ON_COMMAND(IDR_NGPOPUP_PROPERTIES, OnNgpopupProperties)
// ON_COMMAND(ID_HELP_SENDBUGREPORT, OnHelpSendBugReport)
// ON_COMMAND(ID_HELP_SENDPRODUCTSUGGESTION, OnHelpSendSuggestion)
ON_COMMAND(ID_FILE_SEND_MAIL, OnSendToFriend)
ON_WM_TIMER()
ON_MESSAGE (WMU_NEWSVIEW_GOTOARTICLE, GotoArticle)
ON_MESSAGE (WMU_NEWSVIEW_PROCESS_MAILTO, ProcessMailTo)
ON_MESSAGE (WMC_DISPLAY_ARTCOUNT, OnDisplayArtcount)
ON_COMMAND (ID_ARTICLE_SAVE_AS, OnSaveToFile)
ON_UPDATE_COMMAND_UI (ID_ARTICLE_SAVE_AS, OnUpdateSaveToFile)
ON_COMMAND (ID_THREAD_CHANGETHREADSTATUSTO_READ, OnThreadChangeToRead)
ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_CATCHUPALLARTICLES, OnUpdateNewsgroupCatchup)
ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_UNSUBSCRIBE, OnUpdateNewsgroupUnsubscribe)
ON_UPDATE_COMMAND_UI (IDR_NGPOPUP_PROPERTIES, OnUpdateNewsgroupProperties)
ON_UPDATE_COMMAND_UI (ID_THREAD_CHANGETHREADSTATUSTO_READ, OnUpdateThreadChangeToRead)
ON_UPDATE_COMMAND_UI (IDC_VIEW_BINARY, OnUpdateDisable)
ON_COMMAND(ID_CMD_TABAROUND, OnCmdTabaround)
ON_COMMAND(ID_CMD_TABBACK, OnCmdTabBack)
ON_COMMAND(ID_GETHEADERS_ALLGROUPS, OnGetheadersAllGroups)
ON_UPDATE_COMMAND_UI(ID_GETHEADERS_ALLGROUPS, OnUpdateGetheadersAllGroups)
ON_COMMAND(ID_GETHEADERS_MGROUPS, OnGetHeadersMultiGroup)
ON_UPDATE_COMMAND_UI(ID_GETHEADERS_MGROUPS, OnUpdateGetHeadersMultiGroup)
ON_COMMAND(ID_GETHEADER_LIMITED, OnGetheaderLimited)
ON_UPDATE_COMMAND_UI(ID_GETHEADER_LIMITED, OnUpdateGetheaderLimited)
ON_COMMAND(WMC_DISPLAYALL_ARTCOUNT, OnDisplayAllArticleCounts)
ON_MESSAGE(WMU_MODE1_HDRS_DONE, OnMode1HdrsDone)
ON_MESSAGE(WMU_NGROUP_HDRS_DONE, OnNewsgroupHdrsDone)
ON_WM_CONTEXTMENU()
ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateEditSelectAll)
ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy)
ON_MESSAGE(WMU_ERROR_FROM_SERVER, OnErrorFromServer)
ON_MESSAGE(WMU_SELCHANGE_OPEN, OnSelChangeOpen)
ON_UPDATE_COMMAND_UI(ID_ARTICLE_DELETE_SELECTED, OnUpdateDeleteSelected)
ON_UPDATE_COMMAND_UI(IDC_NGPOPUP_MANUAL_RULE, OnUpdateNgpopupManualRule)
ON_UPDATE_COMMAND_UI(IDR_NGPOPUP_OPEN, OnUpdateNgpopupOpen)
ON_UPDATE_COMMAND_UI(ID_KEEP_SAMPLED, OnUpdateKeepSampled)
ON_COMMAND(ID_KEEP_SAMPLED, OnKeepSampled)
ON_UPDATE_COMMAND_UI(ID_KEEP_ALL_SAMPLED, OnUpdateKeepAllSampled)
ON_COMMAND(ID_KEEP_ALL_SAMPLED, OnKeepAllSampled)
ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll)
ON_UPDATE_COMMAND_UI(ID_POST_SELECTED, OnUpdatePostSelected)
ON_COMMAND(ID_POST_SELECTED, OnPostSelected)
ON_COMMAND(ID_ARTICLE_DELETE_SELECTED, OnArticleDeleteSelected)
ON_COMMAND(ID_VERIFY_HDRS, OnVerifyLocalHeaders)
ON_COMMAND(ID_HELP_RESYNC_STATI, OnHelpResyncStati)
ON_COMMAND(ID_NEWSGROUP_PINFILTER, OnNewsgroupPinfilter)
ON_UPDATE_COMMAND_UI(ID_NEWSGROUP_PINFILTER, OnUpdateNewsgroupPinfilter)
ON_UPDATE_COMMAND_UI(ID_ARTICLE_MORE, OnUpdateArticleMore)
ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDisplayInfo)
ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
ON_NOTIFY_REFLECT(NM_RETURN, OnReturn)
ON_NOTIFY_REFLECT(NM_RCLICK, OnRclick)
ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk)
ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
ON_WM_MOUSEWHEEL()
ON_UPDATE_COMMAND_UI(IDM_GETTAGGED_FORGROUPS, OnUpdateGettaggedForgroups)
ON_COMMAND(IDM_GETTAGGED_FORGROUPS, OnGettaggedForgroups)
ON_WM_VKEYTOITEM()
ON_WM_ERASEBKGND()
ON_COMMAND(ID_THREADLIST_REFRESH, OnRefreshCurrentNewsgroup)
ON_WM_LBUTTONDOWN()
ON_COMMAND(ID_NV_FORWARD_SELECTED, OnForwardSelectedArticles)
ON_UPDATE_COMMAND_UI(ID_THREADLIST_REPLYBYMAIL, OnUpdateArticleReplybymail)
ON_UPDATE_COMMAND_UI(ID_THREADLIST_POSTFOLLOWUP, OnUpdateArticleFollowup)
ON_UPDATE_COMMAND_UI(ID_THREADLIST_POSTNEWARTICLE, OnUpdateNewsgroupPostarticle)
ON_UPDATE_COMMAND_UI (IDC_DECODE, OnUpdateDisable)
ON_UPDATE_COMMAND_UI (IDC_MANUAL_DECODE, OnUpdateDisable)
ON_UPDATE_COMMAND_UI(ID_VERIFY_HDRS, OnUpdateGetHeadersMultiGroup)
ON_WM_MOUSEMOVE()
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnNeedText)
END_MESSAGE_MAP()
// ---------------------------------------------------------------------------
// utility function
void FreeGroupIDPairs (CPtrArray* pVec)
{
int tot = pVec->GetSize();
for (--tot; tot >= 0; --tot)
delete ((TGroupIDPair*) pVec->GetAt(tot));
}
/////////////////////////////////////////////////////////////////////////////
// CNewsView construction/destruction
CNewsView::CNewsView()
{
InitializeCriticalSection(&m_dbCritSect);
iLocalOpen = 0;
m_ngPopupMenu.LoadMenu (IDR_NGPOPUP);
m_imageList.Create (IDB_SCROLL,
SCROLL_BMP_CX, // width of frame
1, // gro factor
RGB(255,0,255) // transparent color (hot purple)
);
// setup the 1st overlay image
VERIFY(m_imageList.SetOverlayImage (6, 1));
m_curNewsgroupID = 0;
m_pBrowsePaneHeader = 0;
m_pBrowsePaneText = 0;
m_fLoadFreshData = TRUE;
m_hCaptionTimer = 0;
m_hSelchangeTimer = 0;
m_GotoArticle.m_articleNumber = -1;
m_fPinFilter = FALSE;
m_fTrackZoom = false;
m_iOneClickInterference = 0;
}
/////////////////////////////////////////////////////////////////////////////
CNewsView::~CNewsView()
{
if (m_pBrowsePaneText)
{
delete m_pBrowsePaneText;
m_pBrowsePaneText = 0;
}
DeleteCriticalSection(&m_dbCritSect);
}
/////////////////////////////////////////////////////////////////////////////
// CNewsView drawing
void CNewsView::OnDraw(CDC* pDC)
{
CNewsDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
}
/////////////////////////////////////////////////////////////////////////////
// CNewsView printing
BOOL CNewsView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CNewsView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CNewsView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
#if defined(OLAY_CRAP)
/////////////////////////////////////////////////////////////////////////////
// OLE Server support
// The following command handler provides the standard keyboard
// user interface to cancel an in-place editing session. Here,
// the server (not the container) causes the deactivation.
void CNewsView::OnCancelEditSrvr()
{
GetDocument()->OnDeactivateUI(FALSE);
}
#endif
/////////////////////////////////////////////////////////////////////////////
// CNewsView diagnostics
#ifdef _DEBUG
void CNewsView::AssertValid() const
{
BASE_CLASS::AssertValid();
}
void CNewsView::Dump(CDumpContext& dc) const
{
BASE_CLASS::Dump(dc);
}
CNewsDoc* CNewsView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CNewsDoc)));
return (CNewsDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CNewsView message handlers
int CNewsView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
LogString("Newsview start create");
if (BASE_CLASS::OnCreate(lpCreateStruct) == -1)
return -1;
SetupFont ();
GetListCtrl().SetImageList (&m_imageList, LVSIL_SMALL);
GetListCtrl().SetCallbackMask (LVIS_OVERLAYMASK);
// Strip CS_HREDRAW and CS_VREDRAW. We don't need to repaint everytime we
// are sized. (Tip from 'PC Magazine' May 6,1997)
DWORD dwStyle = GetClassLong (m_hWnd, GCL_STYLE);
SetClassLong (m_hWnd, GCL_STYLE, dwStyle & ~(CS_HREDRAW | CS_VREDRAW));
// OnInitialUpdate will Setup the columns in the header ctrl
// after the size has settled down.
// read from registry
m_fPinFilter = gpGlobalOptions->GetRegUI()->GetPinFilter ();
((CMainFrame*) AfxGetMainWnd())->UpdatePinFilter ( m_fPinFilter );
LogString("Newsview end create");
return 0;
}
/////////////////////////////////////////////////////////////////////////////
void CNewsView::OnSize(UINT nType, int cx, int cy)
{
BASE_CLASS::OnSize(nType, cx, cy);
Resize ( cx, cy );
}
// called from OnSize, and OnInitialUpdate
void CNewsView::Resize(int cx, int cy)
{
}
// ------------------------------------------------------------------------
//
void CNewsView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
{
if (VIEWHINT_SERVER_SWITCH == lHint)
return;
if (VIEWHINT_UNZOOM == lHint)
{
handle_zoom (false, pHint);
return;
}
if (VIEWHINT_ZOOM == lHint)
{
handle_zoom (true, pHint);
return;
}
if (VIEWHINT_SHOWARTICLE == lHint)
return;
if (VIEWHINT_SHOWGROUP == lHint)
return;
if (VIEWHINT_SHOWGROUP_NOSEL == lHint)
return;
if (VIEWHINT_EMPTY == lHint)
{
EmptyBrowsePointers ();
GetDocument()->EmptyArticleStatusChange();
sync_caption();
return;
}
// if an article's status changes it means nothing to us
if (VIEWHINT_STATUS_CHANGE == lHint ||
VIEWHINT_ERASE_OLDTHREADS == lHint)
return;
//if (VIEWHINT_NEWSVIEW_UNSUBSCRIBE == lHint)
// {
// Unsubscribing ((TNewsGroup*) pHint);
// return;
// }
// remember selected group-id
LONG iSelGroupID = GetSelectedGroupID();
CListCtrl & lc = GetListCtrl();
lc.DeleteAllItems ();
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
TNewsGroupArrayReadLock ngMgr(vNewsGroups);
int count = vNewsGroups->GetSize();
for (int j = 0; j < count; ++j)
{
TNewsGroup* pNG = vNewsGroups[j];
AddStringWithData ( pNG->GetBestname(), pNG->m_GroupID);
}
// restore selection
if (iSelGroupID)
{
if (0 != SetSelectedGroupID (iSelGroupID))
SetOneSelection (0);
}
}
// 5-8-96 change to fetch on zero
void CNewsView::OnNgpopupOpen()
{
OpenNewsgroup( kFetchOnZero, kPreferredFilter );
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateNgpopupOpen(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsExactlyOneNewsgroupSelected());
}
// ------------------------------------------------------------------------
// Returns -1 for failure
int CNewsView::GetSelectedIndex ()
{
CListCtrl & lc = GetListCtrl();
POSITION pos = lc.GetFirstSelectedItemPosition ();
if (pos)
return lc.GetNextSelectedItem (pos);
int iMark = lc.GetSelectionMark ();
if (-1 == iMark)
return -1;
return iMark;
}
// ------------------------------------------------------------------------
// Returns positive for success, 0 for failure
LONG CNewsView::GetSelectedGroupID ()
{
int idx = GetSelectedIndex ();
if (-1 == idx)
return 0;
return (LONG) GetListCtrl().GetItemData (idx);
}
// ------------------------------------------------------------------------
// Input: a group id
// Set the listbox selection to the newsgroup that has that id
// Returns: 0 for success, non-zero for error
int CNewsView::SetSelectedGroupID (int iGroupID)
{
CListCtrl & lc = GetListCtrl();
int idx = lc.GetItemCount();
for (--idx; idx >= 0; --idx)
{
if (iGroupID == (LONG) lc.GetItemData(idx))
{
SetOneSelection (idx);
return 0;
}
}
return 1;
}
// ------------------------------------------------------------------------
void CNewsView::OnNgpopupManualRule ()
{
AfxGetMainWnd ()->PostMessage (WM_COMMAND, ID_OPTIONS_MANUAL_RULE);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateNgpopupManualRule(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ------------------------------------------------------------------------
void CNewsView::OnInitialUpdate()
{
CListCtrl & lc = GetListCtrl();
LogString("newsview start initial update");
CNewsApp* pNewsApp = (CNewsApp*) AfxGetApp();
pNewsApp->SetGlobalNewsDoc( GetDocument() );
CNewsDoc::m_pDoc = GetDocument();
CRect rct; GetClientRect( &rct );
// load the widths from the registry
SetupReportColumns (rct.Width());
lc.SetExtendedStyle (LVS_EX_FULLROWSELECT);
// the header control is too tall unless we do this
Resize( rct.Width(), rct.Height() );
// setup columns before initial fill
BASE_CLASS::OnInitialUpdate();
// setup tool tips
VERIFY(m_sToolTips.Create (this, TTS_ALWAYSTIP));
VERIFY(m_sToolTips.AddTool (this, LPSTR_TEXTCALLBACK));
m_sToolTips.SetMaxTipWidth (SHRT_MAX);
m_sToolTips.SetDelayTime (TTDT_AUTOPOP, 10000); // go away after 10 secs
m_sToolTips.SetDelayTime (TTDT_INITIAL, 500);
m_sToolTips.SetDelayTime (TTDT_RESHOW, 1000);
// at this point the splash screen is gone and we are pretty much,
// up and running and willing to load the VCR file from the cmdline
CWnd::FromHandle(ghwndMainFrame)->PostMessage (WMU_READYTO_RUN);
int lastGID = gpGlobalOptions->GetRegUI()->GetLastGroupID();
if (lastGID < 0)
{
if (lc.GetItemCount() > 0)
lastGID = (int) lc.GetItemData( 0 );
}
TServerCountedPtr cpNewsServer;
// find it
bool fFoundValidGroup = false;
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, lastGID, &fUseLock, pNG);
if (fUseLock)
{
fFoundValidGroup = true;
// don't wait for mode-1 to load
if (TNewsGroup::kNothing == UtilGetStorageOption (pNG))
fFoundValidGroup = false;
}
}
if (fFoundValidGroup)
{
int tot = lc.GetItemCount();
for (--tot; tot >= 0; --tot)
{
if (lastGID == (int) lc.GetItemData( tot ))
{
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup())
{
SetOneSelection (tot);
// LVN_ITEMCHANGED notification does the rest....
}
else
{
SetOneSelection (tot);
OpenNewsgroup( kOpenNormal, kPreferredFilter, lastGID );
}
break;
}
}
}
LogString("newsview end initial update");
}
///////////////////////////////////////////////////////////////////////////
void CNewsView::SetupReportColumns (int iParentWidth)
{
TRegUI* pRegUI = gpGlobalOptions->GetRegUI();
int riWidths[3];
if (0 != pRegUI->LoadUtilHeaders("NGPane", riWidths, ELEM(riWidths)))
{
int avgChar = LOWORD(GetDialogBaseUnits());
riWidths[1] = avgChar * 6;
riWidths[2] = avgChar * 6;
int remainder = iParentWidth -riWidths[1] -riWidths[2]
-GetSystemMetrics(SM_CXVSCROLL);
riWidths[0] = max(remainder, avgChar*6);
}
CString strNewsgroups; strNewsgroups.LoadString (IDS_HEADER_NEWSGROUPS);
CString strLocal; strLocal.LoadString (IDS_HEADER_LOCAL);
CString strServer; strServer.LoadString (IDS_HEADER_SERVER);
CListCtrl & lc = GetListCtrl();
lc.InsertColumn (0, strNewsgroups, LVCFMT_LEFT, riWidths[0], 0);
lc.InsertColumn (1, strLocal, LVCFMT_RIGHT, riWidths[1], 1);
lc.InsertColumn (2, strServer, LVCFMT_RIGHT, riWidths[2], 2);
}
///////////////////////////////////////////////////////////////////////////
// CloseCurrentNewsgroup - this was factored out of OpenNewsgroup and
// made public so that it could be used by
// CMainFrame::OnDatePurgeAll
///////////////////////////////////////////////////////////////////////////
void CNewsView::CloseCurrentNewsgroup ()
{
BOOL fViewsEmptied = FALSE;
fViewsEmptied = ShutdownOldNewsgroup ();
gpUIMemory->SetLastGroup ( m_curNewsgroupID );
// the intent of this function is that there will be no
// current group afterwards...
SetCurNewsGroupID (0);
if (!fViewsEmptied)
{
EmptyBrowsePointers ();
// clear out TreeView, FlatView, ArtView
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
}
}
///////////////////////////////////////////////////////////////////////////
// OpenNewsgroup
// eOpenMode - kFetchOnZero if you want to Try to GetHeaders
// iInputGroupID - pass in a groupID, or function will use the cur Sel
//
// Changes:
// 4-09-96 For the Dying NG, Empty the View and then Close it.
// also call ::Empty to clean out the thread list
//
// 8-01-97 return 0 if loaded, 1 if started download, -1 for error
//
int CNewsView::OpenNewsgroup(EOpenMode eMode, EUseFilter eFilter, int iInputGroupID/*=-1*/)
{
int iFilterRC = 0;
BOOL fViewsEmptied = FALSE;
LONG newGroupID;
if (iInputGroupID > 0)
newGroupID = iInputGroupID;
else
{
newGroupID = GetSelectedGroupID ();
if (NULL == newGroupID)
return -1;
}
fViewsEmptied = ShutdownOldNewsgroup ();
SetCurNewsGroupID( newGroupID );
// set title on mdi-child
if (0 == m_hCaptionTimer)
m_hCaptionTimer = SetTimer (idCaptionTimer, 250, NULL);
if (!fViewsEmptied)
{
EmptyBrowsePointers ();
// clear out TreeView, FlatView, ArtView
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
fViewsEmptied = TRUE;
}
TServerCountedPtr cpNewsServer;
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (fUseLock)
{
// open this guy for business
protected_open ( pNG, TRUE );
if (kPreferredFilter == eFilter && (FALSE==m_fPinFilter))
{
// newsgroup may have a default filter. hand off to the Filterbar
int iWhatFilter = GetPreferredFilter ( pNG );
iFilterRC = ((CMainFrame*)AfxGetMainWnd())->SelectFilter ( iWhatFilter );
}
else
{
// if we are using GotoArticle, skip the preferred filter, use current
// if filters are pinned. Use current
}
// if the newsgrp is devoid of new articles, then Try downloading some
if ((kFetchOnZero == eMode) &&
(TNewsGroup::kHeadersOnly == UtilGetStorageOption (pNG) ||
TNewsGroup::kStoreBodies == UtilGetStorageOption (pNG)))
{
pNG->UpdateFilterCount (true);
TViewFilter * pVF = TNewsGroup::GetpCurViewFilter();
if (0 == pVF)
return -1;
TStatusUnit::ETriad eTri = pVF->GetNew();
if (TStatusUnit::kYes == eTri)
{
int iLocalNew, iServerNew, iLocalTotal;
iLocalNew = iServerNew = 100;
pNG->FormatNewArticles ( iLocalNew, iServerNew, iLocalTotal );
if (0 == iLocalNew)
{
// there's nothing in the DB to load - hit the server
GetHeadersOneGroup ();
return 1;
}
}
if (TStatusUnit::kMaybe == eTri)
{
// they are viewing both New and Read
if (0 == pNG->HdrRangeCount())
{
// there's absolutely nothing in the newgroup - hit server
GetHeadersOneGroup ();
return 1;
}
}
}
// when re-creating a new layout, we just use the old data.
if (m_fLoadFreshData) {
// when in mode 1, do all rule substitution before loading articles
// NOTE: This must be done before the hourglass icon is displayed
// (below)
if (pNG->GetStorageOption () == TNewsGroup::kNothing)
ResetAndPerformRuleSubstitution (NULL /* psHeader */, pNG);
// tell rules that an hourglass icon is going to appear, and not to
// bring up any dialogs (it will queue them and display them later)
RulesHourglassStart ();
// user waits....
{
CHourglass wait = this;
pNG->LoadArticles(FALSE);
}
// now that the hourglass icon is gone, we can let rules display any
// notification dialogs
RulesHourglassEnd ();
}
}
}
// fill thread view
please_update_views();
// allow the layout manager to see this action
CFrameWnd * pDadFrame = GetParentFrame();
if (pDadFrame)
pDadFrame->SendMessage (WMU_USER_ACTION, TGlobalDef::kActionOpenGroup);
if (iFilterRC)
AfxMessageBox (IDS_GRP_FILTERGONE);
return 0;
}
///////////////////////////////////////////////////////////////////////////
// Return TRUE if the views have been Emptied
//
BOOL CNewsView::ShutdownOldNewsgroup (void)
{
// We can't shut down a group if the servers not alive
if (!IsActiveServer())
return TRUE;
// save off status of old?
BOOL fViewsEmptied = FALSE;
TServerCountedPtr cpNewsServer;
LONG oldGroupID = m_curNewsgroupID;
BOOL fUseLock;
TNewsGroup* pOld = 0;
TNewsGroupUseLock useLock(cpNewsServer, oldGroupID, &fUseLock, pOld);
if (fUseLock)
{
TUserDisplay_UIPane sAutoDraw("Clear list...");
if (!fViewsEmptied)
{
// clear the threadview while the pointers are Valid
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
fViewsEmptied = TRUE;
}
// if (pOld->GetDirty())
pOld->TextRangeSave();
// Try closing the newsgroup
protected_open (pOld, FALSE);
// this is new (4/9) Empty the threadlist
pOld->Empty();
gpUserDisplay->SetCountFilter ( 0 );
gpUserDisplay->SetCountTotal ( 0 );
}
return fViewsEmptied;
}
void CNewsView::please_update_views(void)
{
TUserDisplay_UIPane sAutoDraw("Loading list...");
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP);
}
//-------------------------------------------------------------------------
// msg handler
void CNewsView::OnRefreshCurrentNewsgroup ()
{
RefreshCurrentNewsgroup ( );
}
//-------------------------------------------------------------------------
// Called by filter buttons, tmanrule.cpp
void CNewsView::RefreshCurrentNewsgroup (bool fMoveSelection /* = true */)
{
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (fUseLock)
{
CWaitCursor wait;
TSaveSelHint sSelHint;
if (fMoveSelection)
{
// Try to restore selection after change (do this before Emptying)
GetDocument()->UpdateAllViews (this, VIEWHINT_SAVESEL, &sSelHint);
}
if (true)
{
TUserDisplay_UIPane sAutoDraw("Emptying");
GetDocument()->UpdateAllViews (NULL, VIEWHINT_EMPTY);
}
// do not empty before reloading
pNG->ReloadArticles (FALSE);
TUserDisplay_UIPane sAutoDraw("Loading...");
if (fMoveSelection)
{
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews (this, VIEWHINT_SHOWGROUP);
// restore selection
GetDocument()->UpdateAllViews (this, VIEWHINT_SAVESEL, &sSelHint);
}
else
{
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews (this, VIEWHINT_SHOWGROUP_NOSEL);
}
}
}
//-------------------------------------------------------------------------
void CNewsView::OnContextMenu(CWnd* pWnd, CPoint point)
{
//TRACE0("caught WM_CONTEXTMENU\n");
CPoint anchor(point);
// weird coords if menu summoned with Shift-F10
if (-1 == anchor.x && -1 == anchor.y)
{
// do the best we can - top left corner of listbox
anchor.x = anchor.y = 2;
this->ClientToScreen( &anchor );
}
context_menu( anchor );
}
// ------------------------------------------------------------------------
//
void CNewsView::context_menu(CPoint & ptScreen)
{
CListCtrl & lc = GetListCtrl();
// multiple selection is OK for everything except 'Properties...'
if (lc.GetSelectedCount () <= 0)
return;
// get the group name so we can do the op...
int idx = GetSelectedIndex ();
if (idx < 0)
return;
TServerCountedPtr cpNewsServer;
LONG id = (LONG) lc.GetItemData( idx );
BOOL fUseLock;
TNewsGroup * pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG);
if (!fUseLock)
return;
CMenu * pTrackMenu = m_ngPopupMenu.GetSubMenu ( 0 );
ProbeCmdUI (this, pTrackMenu);
pTrackMenu->TrackPopupMenu( TPM_LEFTALIGN | TPM_RIGHTBUTTON, ptScreen.x, ptScreen.y, this);
}
// ------------------------------------------------------------------------
void CNewsView::UnsubscribeGroups (const CPtrArray &vec)
{
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
for (int i = 0; i < vec.GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]);
bool fDemoted = false; // TRUE if lbx-string is deleted
{
BOOL fUseLock = FALSE;
TNewsGroup* pNG;
TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG);
// kill any queued jobs
if (fUseLock)
fDemoted = demote_newsgroup ( pNG );
}
// Try to get destroy lock on it
if (0 == vNewsGroups.ReserveGroup (pPair->id))
{
cpNewsServer->UnsubscribeGroup (pPair->id);
}
else
{
// yikes. add string back into listbox.
if (fDemoted)
AddStringWithData (pPair->ngName, pPair->id);
CString pattern; pattern.LoadString (IDS_ERR_GROUP_IN_USE);
CString msg; msg.Format (pattern, (LPCTSTR) pPair->ngName);
NewsMessageBox (this, msg, MB_OK | MB_ICONSTOP);
}
}
// find new selection, open next newsgroup etc...
finish_unsubscribe();
}
// ------------------------------------------------------------------------
void CNewsView::DoUnsubscribe (BOOL bAlwaysAsk)
{
CPtrArray vec; // hold data from _prelim function
// confirm unsubscribe
if (unsubscribe_prelim (&vec, bAlwaysAsk))
return;
CWaitCursor cursor;
UnsubscribeGroups (vec);
FreeGroupIDPairs (&vec);
}
// ------------------------------------------------------------------------
void CNewsView::OnNewsgroupUnsubscribe()
{
DoUnsubscribe (FALSE /* bAlwaysAsk */);
}
// ------------------------------------------------------------------------
void CNewsView::OnArticleDeleteSelected()
{
DoUnsubscribe (TRUE /* bAlwaysAsk */);
}
// ------------------------------------------------------------------------
// TRUE indicates the lbx line was deleted
bool CNewsView::demote_newsgroup ( TNewsGroup* pNG )
{
extern TNewsTasker* gpTasker;
CListCtrl & lc = GetListCtrl();
int total = lc.GetItemCount();
for (int i = 0; i < total; ++i)
{
if (pNG->m_GroupID == (int)lc.GetItemData(i))
{
// kill any queued jobs.
gpTasker->UnregisterGroup ( pNG );
// if we are killing the current newsgroup, open some
// other group
if (pNG->m_GroupID == m_curNewsgroupID)
{
m_curNewsgroupID = 0;
}
lc.DeleteItem ( i );
// figure out what to do with the selection
int newsel;
if (i == total - 1)
newsel = i - 1;
else
newsel = i;
if (newsel >= 0)
SetOneSelection (newsel);
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////
//
// 4-24-96 amc Write changes to disk, reset title to Null
// 11-01-96 amc Clear out views when going from Mode2(dead)->Mode1
int CNewsView::finish_unsubscribe (void)
{
int total;
BOOL fEmptySync = TRUE;
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
total = vNewsGroups->GetSize();
if (total > 0)
{
BOOL fOpenGroup = FALSE;
LONG newGroupID;
// Pull in newly selected newsgroup
// iff we killed the current newsgroup
if (0==m_curNewsgroupID)
{
// However... don't pull a newsgroup in
// if it means doing a Mode-1 suck
{
newGroupID = GetSelectedGroupID ();
if (NULL == newGroupID)
return 0;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, newGroupID, &fUseLock, pNG);
if (!fUseLock)
return 0;
if (TNewsGroup::kHeadersOnly == UtilGetStorageOption(pNG) ||
TNewsGroup::kStoreBodies == UtilGetStorageOption(pNG))
fOpenGroup = TRUE;
}
if (fOpenGroup)
{
fEmptySync = FALSE;
OpenNewsgroup(kOpenNormal, kPreferredFilter, newGroupID);
}
}
}
if (fEmptySync)
{
// empty all views
GetDocument()->UpdateAllViews ( NULL, VIEWHINT_EMPTY );
sync_caption (); // "no newsgroup selected"
}
return 0;
}
// ------------------------------------------------------------------------
// gets info on multiselect
int CNewsView::multisel_get (CPtrArray * pVec, int* piSel)
{
CListCtrl & lc = GetListCtrl();
int sel = lc.GetSelectedCount();
if (sel <= 0)
return 1;
int* pIdx = new int[sel];
auto_ptr<int> pDeleterIdx(pIdx);
// get selected items
int n = 0;
POSITION pos = lc.GetFirstSelectedItemPosition ();
while (pos)
pIdx[n++] = lc.GetNextSelectedItem (pos);
// get the names and the group-ids
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
// get the each ng name and release
for (int i = 0; i < sel; ++i)
{
int groupId = lc.GetItemData (pIdx[i]);
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, groupId, &fUseLock, pNG);
if (fUseLock)
pVec->Add ( new TGroupIDPair(groupId, pNG->GetBestname()) );
}
*piSel = sel;
return 0;
}
// ------------------------------------------------------------------------
// unsubscribe_prelim - Returns 0 for success. 1 for stop
// Confirm that the user wants to unsubscribe from multiple newsgroups
// Name and id pairs are returned in the PtrArray. Uses nickname if
// it is set.
int CNewsView::unsubscribe_prelim (CPtrArray *pVec, BOOL bAlwaysAsk)
{
int sel = 0;
if (multisel_get (pVec, &sel))
return 1;
int nProtectedArticles = 0;
TServerCountedPtr cpNewsServer;
for (int i = 0; i < pVec->GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(pVec->GetAt(i));
{
BOOL fUseLock = FALSE;
TNewsGroup* pNG;
TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG);
if (fUseLock)
{
int nProt = 0;
pNG->StatusCountProtected ( nProt );
nProtectedArticles += nProt;
}
}
}
// see if they really want to kill these groups...
if (gpGlobalOptions->WarnOnUnsubscribe() || bAlwaysAsk || (nProtectedArticles > 0))
{
CString msg;
CString strProtected;
if (1 == sel)
{
if (pVec->GetSize () != 1)
return 1;
AfxFormatString1 (msg, IDS_WARNING_UNSUBSCRIBE,
((TGroupIDPair*)pVec->GetAt(0))->ngName);
}
else
{
char szCount[10];
_itoa (sel, szCount, 10);
AfxFormatString1 (msg, IDS_WARN_UNSUBSCRIBE_MANY1, szCount);
}
if (nProtectedArticles > 0)
{
CString strProtected;
strProtected.Format (IDS_WARNING_PROTCOUNT1, nProtectedArticles);
msg += strProtected;
}
BOOL fDisableWarning = FALSE;
if (WarnWithCBX (msg,
&fDisableWarning,
NULL /* pParentWnd */,
FALSE /* iNotifyOnly */,
FALSE /* bDefaultToNo */,
bAlwaysAsk /* bDisableCheckbox */))
{
if (fDisableWarning)
{
gpGlobalOptions->SetWarnOnUnsubscribe(FALSE);
TRegWarn *pRegWarning = gpGlobalOptions->GetRegWarn ();
pRegWarning->Save();
}
return 0; // it's OK to go on
}
else
{
// free intermediate data
FreeGroupIDPairs (pVec);
return 1;
}
}
return 0; // it's OK to go on
}
/* ----------------------------------------------------------------
Case 1: You are in Mode 1, and you are viewing New & Read
messages. Catching up means marking things Read; After catching
up, you do not want to reload the same headers over your
PPP link (see Bug #68 part 2)
11-26-96 amc User can move to next group after catchup on this one
------------------------------------------------------------------- */
void CNewsView::OnNgpopupCatchupallarticles()
{
// holds a collection of (groupID, name) pairs
CPtrArray vec;
// get info on multisel and allow cancellation
if (catchup_prelim (&vec))
return;
int tot = vec.GetSize();
for (int i = 0; i < tot; i++)
{
BOOL fMoveNext = (i == tot-1);
TGroupIDPair* pPair = static_cast<TGroupIDPair*>(vec[i]);
CatchUp_Helper ( pPair->id, fMoveNext );
}
// free intermediate data
FreeGroupIDPairs (&vec);
}
// ------------------------------------------------------------------------
// Called from :
// OnGetheaderGroup
// OnNgpopupCatchupallarticles
void CNewsView::CatchUp_Helper (int iGroupID, BOOL fAllowMoveNext)
{
TServerCountedPtr cpNewsServer;
TNewsGroup * pNG = 0;
BOOL fUseLock;
// reacquire lock
TNewsGroupUseLock useLock(cpNewsServer, iGroupID, &fUseLock, pNG);
if (!fUseLock)
return;
BOOL fViewing = (pNG->m_GroupID == m_curNewsgroupID);
if (TNewsGroup::kNothing == UtilGetStorageOption ( pNG ))
{
// Since this is Mode 1, avoid going out to the server again
// marks everything as Read
pNG->CatchUpArticles();
OnDisplayArtcount(pNG->m_GroupID, 0);
if (fViewing)
{
int iNextGrpId = -1;
int iNextIdx;
// see if we are moving onward
if (fAllowMoveNext &&
gpGlobalOptions->GetRegSwitch()->GetCatchUpLoadNext() &&
validate_next_newsgroup(&iNextGrpId, &iNextIdx))
{
// clear out
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
// goto next ng
AddOneClickGroupInterference();
SetOneSelection (iNextIdx);
OpenNewsgroup (kOpenNormal, kPreferredFilter, iNextGrpId);
}
else
{
TViewFilter * pFilter = TNewsGroup::GetpCurViewFilter ();
if (0 == pFilter)
return;
TStatusUnit::ETriad eTri = pFilter->GetNew ();
switch (eTri)
{
case TStatusUnit::kMaybe:
case TStatusUnit::kNo:
// this will show the result (all articles marked as Read)
GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP);
break;
case TStatusUnit::kYes:
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
break;
}
}
}
else
{
// catchup on a group that we are not viewing. No movement
}
}
else
{
// this is Mode 2 or Mode 3
if (fViewing)
// empty out TreeView, FlatView, ArtView
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
pNG->CatchUpArticles();
// newsview should redraw count of new articles (0)
OnDisplayArtcount(pNG->m_GroupID, 0);
if (fViewing)
{
int iNextGrpId = -1;
int iNextIdx;
// see if we are moving onward
if (fAllowMoveNext &&
gpGlobalOptions->GetRegSwitch()->GetCatchUpLoadNext() &&
validate_next_newsgroup(&iNextGrpId, &iNextIdx))
{
EmptyBrowsePointers ();
// goto next ng
AddOneClickGroupInterference();
SetOneSelection (iNextIdx);
OpenNewsgroup (CNewsView::kOpenNormal, kPreferredFilter, iNextGrpId);
}
else
{
EmptyBrowsePointers ();
// reload & update the display
newsview_reload(pNG);
}
}
}
}
// -----------------------------------------------------------------------
// Called from OnNgpopupCatchupallarticles
void CNewsView::newsview_reload(TNewsGroup* pNG)
{
ASSERT(pNG);
CWaitCursor wait;
if (pNG)
{
SetCurNewsGroupID( pNG->m_GroupID );
// TRUE - empty thread list first, then load
pNG->ReloadArticles(TRUE);
// perform a broadcast directed at the threadlist view
GetDocument()->UpdateAllViews(this, VIEWHINT_SHOWGROUP);
}
}
// --------------------------------------------------------------
int CNewsView::catchup_prelim (CPtrArray* pVec)
{
int sel = 0;
if (multisel_get (pVec, &sel))
return 1;
// see if they really want to catchup on these groups...
if (gpGlobalOptions->WarnOnCatchup())
{
CString msg;
if (1 == sel)
{
if (pVec->GetSize () != 1)
return 1;
AfxFormatString1 (msg, IDS_WARNING_CATCHUP,
((TGroupIDPair*)pVec->GetAt(0))->ngName);
}
else
{
char szCount[10];
_itoa (sel, szCount, 10);
AfxFormatString1 (msg, IDS_WARN_CATCHUP_MANY1, szCount);
}
BOOL fDisableWarning = FALSE;
if (WarnWithCBX (msg, &fDisableWarning))
{
if (fDisableWarning)
{
gpGlobalOptions->SetWarnOnCatchup(FALSE);
TRegWarn *pRegWarning = gpGlobalOptions->GetRegWarn ();
pRegWarning->Save();
}
}
else
{
// free intermediate data
FreeGroupIDPairs (pVec);
return 1;
}
}
return 0; // it's OK to go on
}
// --------------------------------------------------------------
void CNewsView::OnUpdateNewsgroupPostarticle(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsNewsgroupDisplayed());
}
// --------------------------------------------------------------
// OnNewsgroupPostarticle -- post an article to the open newsgroup
void CNewsView::OnNewsgroupPostarticle ()
{
if (!check_server_posting_allowed())
return;
ASSERT (m_curNewsgroupID);
TPostTemplate *pTemplate = gptrApp->GetPostTemplate ();
pTemplate->m_iFlags = TPT_TO_NEWSGROUP | TPT_CANCEL_WARNING_ID | TPT_POST;
pTemplate->m_NewsGroupID = GetCurNewsGroupID();
pTemplate->m_iCancelWarningID = IDS_WARNING_POSTCANCEL;
pTemplate->Launch (GetCurNewsGroupID());
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdatePostSelected(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ------------------------------------------------------------------------
void CNewsView::OnPostSelected()
{
CListCtrl & lc = GetListCtrl();
// check if posting is allowed to this server
if (!check_server_posting_allowed())
return;
// make template
TPostTemplate *pTemplate = gptrApp->GetPostTemplate ();
// get selected group IDs
int iSel = lc.GetSelectedCount ();
if (iSel <= 0)
{
ASSERT (0);
return;
}
int * pIndices = new int [iSel];
auto_ptr<int> pDeleterIndices (pIndices);
// get selected items
int n = 0;
POSITION pos = lc.GetFirstSelectedItemPosition ();
while (pos)
pIndices[n++] = lc.GetNextSelectedItem (pos);
bool fCurGroupInSelection = false;
pTemplate->m_rNewsgroups.RemoveAll ();
for (int i = 0; i < iSel; i++)
{
LONG gid = lc.GetItemData (pIndices [i]);
if (m_curNewsgroupID == gid)
fCurGroupInSelection = true;
pTemplate->m_rNewsgroups.Add (gid);
}
// utilize Per-Group e-mail address override w.r.t. which Group?
if (1 == iSel)
pTemplate->m_NewsGroupID = lc.GetItemData (pIndices[0]);
else
pTemplate->m_NewsGroupID = (fCurGroupInSelection) ? m_curNewsgroupID : 0 ;
// fill in rest of template and launch
pTemplate->m_iFlags = TPT_TO_NEWSGROUPS | TPT_CANCEL_WARNING_ID | TPT_POST;
pTemplate->m_iCancelWarningID = IDS_WARNING_POSTCANCEL;
pTemplate->Launch (pTemplate->m_NewsGroupID);
}
// ------------------------------------------------------------------------
void CNewsView::OnArticleFollowup ()
{
TServerCountedPtr cpNewsServer;
CString followUps;
TArticleText * pArtText = static_cast<TArticleText*>(m_pBrowsePaneText);
// get article on demand if we need it. I would like the TPostDoc to
// get the article, but the check for "followup-to: poster" already
// requires it early.
if (true)
{
int stat;
BOOL fUseLock;
TNewsGroup * pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
BOOL fMarkAsRead = gpGlobalOptions->GetRegSwitch()->GetMarkReadFollowup();
if (0 == pArtText)
{
TError sErrorRet;
CPoint ptPartID(0,0);
TArticleText * pReturnArticleText = 0;
stat = fnFetchBody (sErrorRet,
pNG,
(TArticleHeader *) m_pBrowsePaneHeader,
pReturnArticleText,
ptPartID,
fMarkAsRead, // mark-as-read
TRUE); // Try from newsfeed
if (0 == stat)
{
SetBrowseText ( pReturnArticleText );
pArtText = pReturnArticleText;
}
else
{
CString str; str.LoadString (IDS_ERR_COULD_NOT_RETRIEVE);
NewsMessageBox ( this, str, MB_ICONSTOP | MB_OK );
return;
}
}
else
{ // it's local
TArticleHeader* pArtHdr = (TArticleHeader* ) m_pBrowsePaneHeader;
if (pArtHdr && fMarkAsRead)
pNG->ReadRangeAdd ( pArtHdr );
}
}
BOOL fPostWithCC = FALSE;
// check for "followup-to: poster"
pArtText->GetFollowup ( followUps );
followUps.TrimLeft(); followUps.TrimRight();
// Son-of-1036 indicates exact match
if ("poster" == followUps)
{
TAskFollowup dlg(this);
dlg.DoModal();
switch (dlg.m_eAction)
{
case TAskFollowup::kCancel:
return;
case TAskFollowup::kPostWithCC:
fPostWithCC = TRUE;
break;
case TAskFollowup::kSendEmail:
{
OnArticleReplybymail ();
return;
}
}
}
// Verify that server is "Posting Allowed". This check is down here since
// Followup-To: poster can morph to an e-mail message
if (!check_server_posting_allowed())
return;
ASSERT (m_curNewsgroupID);
TPostTemplate *pTemplate = gptrApp->GetFollowTemplate ();
pTemplate->m_iFlags =
TPT_TO_NEWSGROUP |
TPT_INSERT_ARTICLE |
TPT_READ_ARTICLE_HEADER |
TPT_CANCEL_WARNING_ID |
TPT_FOLLOWUP |
TPT_INIT_SUBJECT |
TPT_USE_FOLLOWUP_INTRO |
TPT_POST;
if (fPostWithCC)
pTemplate->m_iFlags |= TPT_POST_CC_AUTHOR;
pTemplate->m_NewsGroupID = m_curNewsgroupID;
pTemplate->m_iCancelWarningID = IDS_WARNING_FOLLOWUPCANCEL;
pTemplate->m_strSubjPrefix.LoadString (IDS_RE);
// lock the group while the article header and text are being accessed
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
TSyncReadLock sync (pNG);
// $$ MicroPlanet tech-support specific. Turn on CC
if (gpGlobalOptions->GetRegSwitch()->m_fUsePopup &&
("support" == pNG->GetName() ||
"suggest" == pNG->GetName() ||
"regstudio" == pNG->GetName()))
pTemplate->m_iFlags |= TPT_POST_CC_AUTHOR;
pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader;
pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText;
pTemplate->m_strSubject =
((TArticleHeader *) m_pBrowsePaneHeader)->GetSubject ();
pTemplate->Launch (pTemplate->m_NewsGroupID);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateArticleFollowup(CCmdUI* pCmdUI)
{
// we must have a current article
BOOL fEnable = FALSE;
if (m_curNewsgroupID && m_pBrowsePaneHeader)
{
if (m_pBrowsePaneText)
fEnable = TRUE;
else
{
// the body is not here. But we can probably get it.
fEnable = gpTasker->IsConnected();
}
}
pCmdUI->Enable ( fEnable );
}
// ------------------------------------------------------------------------
void fnNewsView_ReplyTo (CString& strTo, CString& strFrom, TArticleText* pText)
{
// use the 'Reply-To' field if present
CString fldReplyTo;
if (pText->GetReplyTo (fldReplyTo) && !fldReplyTo.IsEmpty())
{
// RLW : 16/10/08 : The effect of these #ifdefs and
// DecodeElectronicAddress being commented out meant that
// ReplyTo: was being ignored, and the email was getting
// the email of the pervious email sent!!
// So I have removed #ifdef and ASSERT...
//#if defined(_DEBUG)
//ASSERT(0);
// RLW : 16/10/08 : removed commenting from this func...
// this function will handle the rfc2047 encoding
TArticleHeader::DecodeElectronicAddress (fldReplyTo, strTo);
// RLW : 16/10/08 : removed #endif to implement correct behaviour.
//#endif
}
else
strTo = strFrom;
}
///////////////////////////////////////////////////////////////////////////
// amc 4-2-97 Fix a deadlock problem. If you are replying to something
// you haven't read, the Pump gets it on the fly and then
// blocks on a WriteLock as it tries to mark the article
// Read. Solution - release the ReadLock we acquired in this
// function
void CNewsView::OnArticleReplybymail()
{
TServerCountedPtr cpNewsServer;
TPostTemplate *pTemplate = gptrApp->GetReplyTemplate ();
pTemplate->m_iFlags =
TPT_TO_STRING |
TPT_INSERT_ARTICLE |
TPT_READ_ARTICLE_HEADER |
TPT_CANCEL_WARNING_ID |
TPT_INIT_SUBJECT |
TPT_USE_REPLY_INTRO |
TPT_MAIL;
pTemplate->m_iCancelWarningID = IDS_WARNING_REPLYCANCEL;
pTemplate->m_strSubjPrefix.LoadString (IDS_RE);
pTemplate->m_NewsGroupID = m_curNewsgroupID;
// lock the group while the article header and text are being accessed
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
// protects the header object
pNG->ReadLock ();
pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader;
// copy the From field
CString strFrom = pTemplate->m_pArtHdr->GetFrom ();
pTemplate->m_strSubject = pTemplate->m_pArtHdr->GetSubject ();
pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText;
if (pTemplate->m_pArtText)
{
pNG->UnlockRead ();
}
else
{
TError sErrorRet;
CPoint ptPartID(0,0);
TArticleHeader tmpHdr(*pTemplate->m_pArtHdr);
TArticleText * pReturnArticleText = 0;
// fMarkRead will need a WriteLock !! Give it up.
pNG->UnlockRead ();
BOOL fMarkAsRead = gpGlobalOptions->GetRegSwitch()->GetMarkReadReply();
int stat = fnFetchBody ( sErrorRet,
pNG,
&tmpHdr,
pReturnArticleText,
ptPartID,
fMarkAsRead /* fMarkRead */,
TRUE /* Try newsfeed */ );
if (stat)
{
NewsMessageBox (this, IDS_ERR_COULD_NOT_RETRIEVE, MB_ICONSTOP | MB_OK);
return;
}
SetBrowseText ( pReturnArticleText );
pTemplate->m_pArtText = pReturnArticleText;
}
// setup the 'To:' field. Use the 'Reply-To' field if present
fnNewsView_ReplyTo ( pTemplate->m_strTo, strFrom,
pTemplate->m_pArtText );
// proceed
pTemplate->Launch (pTemplate->m_NewsGroupID);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateArticleReplybymail(CCmdUI* pCmdUI)
{
if (!IsActiveServer())
{
pCmdUI->Enable (FALSE);
return;
}
TServerCountedPtr cpNewsServer;
BOOL fArticleBody = m_pBrowsePaneText ? TRUE : gpTasker->IsConnected();
pCmdUI->Enable (
!cpNewsServer->GetSmtpServer ().IsEmpty () &&
m_curNewsgroupID &&
m_pBrowsePaneHeader &&
fArticleBody
);
}
////////////////////////////////////////////////////////////////
static BOOL gbForwardingSelected; // forwarding all selected articles?
void CNewsView::OnArticleForward ()
{
TServerCountedPtr cpNewsServer;
TPostTemplate *pTemplate = gptrApp->GetForwardTemplate ();
pTemplate->m_iFlags =
TPT_CANCEL_WARNING_ID |
TPT_MAIL;
pTemplate->m_NewsGroupID = m_curNewsgroupID;
pTemplate->m_iCancelWarningID = IDS_WARNING_FORWARDCANCEL;
pTemplate->m_strSubjPrefix.LoadString (IDS_FWD);
pTemplate->m_iFlags |=
gbForwardingSelected ? (TPT_INSERT_SELECTED_ARTICLES | TPT_INIT_SUBJECT) :
(TPT_READ_ARTICLE_HEADER | TPT_INSERT_ARTICLE | TPT_INIT_SUBJECT);
// put this newsgroup's name in the template's "extra text file" field
{
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
pTemplate->m_strExtraTextFile = pNG->GetName ();
}
// when forwarding, don't wrap, don't quote, ignore the line limit, and
// insert the special prefix message
pTemplate->m_iFlags |= TPT_DONT_WRAP | TPT_DONT_QUOTE |
TPT_IGNORE_LINE_LIMIT | TPT_USE_FORWARD_INTRO;
if (!gbForwardingSelected) {
// lock the group while the article header and text are being accessed
BOOL fUseLock;
TNewsGroup *pNG;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (!fUseLock)
return;
TSyncReadLock sync (pNG);
pTemplate->m_pArtHdr = (TArticleHeader *) m_pBrowsePaneHeader;
pTemplate->m_pArtText = (TArticleText *) m_pBrowsePaneText;
pTemplate->m_strSubject =
((TArticleHeader *) m_pBrowsePaneHeader)->GetSubject ();
}
else {
// get the subject from the first selected article
TThreadListView *pView = GetThreadView ();
ASSERT (pView);
TArticleHeader *pHeader = NULL;
pView->GetFirstSelectedHeader ((TPersist822Header *&) pHeader);
ASSERT (pHeader);
pTemplate->m_strSubject = pHeader->GetSubject ();
}
pTemplate->Launch (pTemplate->m_NewsGroupID);
gbForwardingSelected = FALSE;
}
////////////////////////////////////////////////////////////////
void CNewsView::OnForwardSelectedArticles ()
{
gbForwardingSelected = TRUE;
OnArticleForward ();
}
void CNewsView::OnUpdateForwardSelectedArticles (CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
const CString & host = cpNewsServer->GetSmtpServer();
if (!host.IsEmpty() && m_curNewsgroupID &&
m_pBrowsePaneHeader && m_pBrowsePaneText)
pCmdUI->Enable (TRUE);
else
pCmdUI->Enable (FALSE);
}
///////////////////////////////////////////////////
void CNewsView::SetBrowseText(TPersist822Text* pText)
{
delete m_pBrowsePaneText;
m_pBrowsePaneText = pText;
}
TPersist822Text * CNewsView::GetBrowseText(void)
{
//ASSERT(m_pBrowsePaneArticle);
return m_pBrowsePaneText;
}
///////////////////////////////////////////////////
void CNewsView::SetBrowseHeader(TPersist822Header* pHdr)
{
m_pBrowsePaneHeader = pHdr;
}
TPersist822Header * CNewsView::GetBrowseHeader(void)
{
//ASSERT(m_pBrowsePaneArticle);
return m_pBrowsePaneHeader;
}
///////////////////////////////////////////////////
void CNewsView::SetCurNewsGroupID(LONG id)
{
m_curNewsgroupID = id;
}
LONG CNewsView::GetCurNewsGroupID(void)
{
return m_curNewsgroupID;
}
void CNewsView::OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView)
{
// TODO: Add your specialized code here and/or call the base class
if (bActivate)
{
SetFocus ();
// let the mdichild window know that we have the focus
((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->PostMessage ( WMU_CHILD_FOCUS, 0, 0L );
}
// IMHO this vvv is bullshit -al
//BASE_CLASS::OnActivateView(bActivate, pActivateView, pDeactiveView);
}
// This is public, so the threadView can route msgs through us
BOOL CNewsView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
// TODO: Add your specialized code here and/or call the base class
return BASE_CLASS::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
////////////////////////////////////////////////////////////////////
// Note: the Deregister also happens when we destroy & recreate the
// layout configuration
void CNewsView::OnDestroy()
{
// save off status before we shut down
{
if (IsActiveServer())
{
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pOld = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pOld);
if (fUseLock)
{
if (pOld && (pOld->GetDirty()) )
pOld->TextRangeSave();
// close the current newsgroup
if (pOld->IsOpen())
pOld->Close();
}
}
}
SaveColumnSettings();
// m_fPinFilter doesn't need to be written. it is saved immediately on Toggl
BASE_CLASS::OnDestroy();
}
//-------------------------------------------------------------------------
// PropertyPage
void CNewsView::OnNgpopupProperties()
{
int idx = GetSelectedIndex ();
if (idx < 0)
return;
LONG id = (LONG)GetListCtrl().GetItemData(idx);
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG);
if (!fUseLock)
return;
TNewsGroup::EStorageOption eOldStorage = UtilGetStorageOption (pNG);
TNewGroupGeneralOptions pgGeneral;
TPurgePage pgPurge;
TNewsGroupOverrideOptions pgOverride;
TNewsGroupFilterPage pgFilter;
TSigPage pgSignature;
pgGeneral.m_kStorageOption = pgGeneral.m_iOriginalMode = (int) eOldStorage;
pNG->GetServerBounds ( pgGeneral.m_iServerLow, pgGeneral.m_iServerHi );
int iHiRead = 0;
if (pNG->GetHighestReadArtInt (&iHiRead))
pgGeneral.m_iHighestArticleRead = iHiRead;
pgGeneral.m_lowWater = pNG->GetLowwaterMark();
pgGeneral.m_nickname = pNG->GetNickname ();
pgGeneral.m_bSample = pNG->IsSampled ();
pgGeneral.m_fInActive = pNG->IsActiveGroup() ? FALSE : TRUE ;
//pgGeneral.m_fUseGlobalStorageOptions = pNG->UseGlobalStorageOptions ();
pgGeneral.m_fCustomNGFont = FALSE;
pgGeneral.m_strGroupName = pNG->GetName ();
if (gpGlobalOptions->IsCustomNGFont())
{
CopyMemory (&pgGeneral.m_ngFont, gpGlobalOptions->GetNewsgroupFont(), sizeof(LOGFONT));
pgGeneral.m_newsgroupColor = gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor();
pgGeneral.m_fCustomNGFont = TRUE;
}
else
CopyMemory (&pgGeneral.m_ngFont, &gpGlobalOptions->m_defNGFont, sizeof(LOGFONT));
TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors ();
pgGeneral.m_newsgroupBackground = pBackgrounds->GetNewsgroupBackground();
pgGeneral.m_fDefaultBackground = gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG();
pgPurge.m_fOverride = pNG->IsPurgeOverride();
pgPurge.m_fPurgeRead = UtilGetPurgeRead(pNG);
pgPurge.m_iReadLimit = UtilGetPurgeReadLimit(pNG);
pgPurge.m_fPurgeUnread = UtilGetPurgeUnread(pNG);
pgPurge.m_iUnreadLimit = UtilGetPurgeUnreadLimit(pNG);
pgPurge.m_fOnHdr = UtilGetPurgeOnHdrs(pNG);
pgPurge.m_iDaysHdrPurge= UtilGetPurgeOnHdrsEvery(pNG);
pgPurge.m_fShutdown = UtilGetCompactOnExit(pNG);
pgPurge.m_iShutCompact = UtilGetCompactOnExitEvery(pNG);
pgOverride.m_bOverrideCustomHeaders = pNG->GetOverrideCustomHeaders ();
pgOverride.m_bOverrideEmail = pNG->GetOverrideEmail ();
pgOverride.m_bOverrideFullName = pNG->GetOverrideFullName ();
pgOverride.m_bOverrideDecodeDir = pNG->GetOverrideDecodeDir ();
pgOverride.m_fOverrideLimitHeaders = pNG->GetOverrideLimitHeaders ();
pgOverride.m_strDecodeDir = pNG->GetDecodeDir ();
pgOverride.m_strEmail = pNG->GetEmail ();
pgOverride.m_strFullName = pNG->GetFullName ();
CopyCStringList (pgOverride.m_sCustomHeaders, pNG->GetCustomHeaders ());
pgOverride.m_iHeaderLimit = pNG->GetHeadersLimit ();
// newsgroup filter page
pgFilter.m_iFilterID = pNG->GetFilterID();
pgFilter.m_fOverrideFilter = pgFilter.m_iFilterID != 0;
// newsgroup signature page
pgSignature.m_fCustomSig = pNG->GetUseSignature();
pgSignature.m_strShortName = pNG->GetSigShortName();
CPropertySheet newsgroupProperties(pNG->GetName ());
int iRC;
newsgroupProperties.AddPage (&pgGeneral);
newsgroupProperties.AddPage (&pgPurge);
newsgroupProperties.AddPage (&pgOverride);
newsgroupProperties.AddPage (&pgFilter);
newsgroupProperties.AddPage (&pgSignature);
iRC = newsgroupProperties.DoModal ();
if (IDOK == iRC)
{
#if defined(_DEBUG) && defined(VERBOSE)
CString msg; msg.Format("SrHi= %d; SrLo= %d; HiRead=%d",
pgGeneral.m_iServerHi,
pgGeneral.m_iServerLow,
pgGeneral.m_iHighestArticleRead);
MessageBox (msg);
#endif
pNG->SetNickname (pgGeneral.m_nickname);
pNG->Sample (pgGeneral.m_bSample);
sync_caption();
if (pgGeneral.m_iHighestArticleRead != pgGeneral.m_iHighestArticleRead0)
{
// user has chosen to go back!
int iLowWater = pNG->GetLowwaterMark ();
if (pgGeneral.m_iHighestArticleRead < iLowWater)
pNG->SetLowwaterMark (pgGeneral.m_iHighestArticleRead);
pNG->ResetHighestArticleRead (pgGeneral.m_iHighestArticleRead,
pgGeneral.m_iHighestArticleRead0);
// if user changed the GoBack, then we should save this
cpNewsServer->SaveReadRange ();
}
pNG->SetStorageOption (TNewsGroup::EStorageOption(pgGeneral.m_kStorageOption));
pNG->SetUseGlobalStorageOptions (/*pgGeneral.m_fUseGlobalStorageOptions*/FALSE);
gpGlobalOptions->CustomNGFont (pgGeneral.m_fCustomNGFont);
gpGlobalOptions->GetRegSwitch()->SetDefaultNGBG(pgGeneral.m_fDefaultBackground);
pBackgrounds->SetNewsgroupBackground(pgGeneral.m_newsgroupBackground);
gpGlobalOptions->GetRegFonts()->SetNewsgroupFontColor( pgGeneral.m_newsgroupColor );
if (pgGeneral.m_fCustomNGFont)
gpGlobalOptions->SetNewsgroupFont ( &pgGeneral.m_ngFont );
pNG->SetActiveGroup (!pgGeneral.m_fInActive);
pNG->SetPurgeOverride(pgPurge.m_fOverride);
pNG->SetPurgeRead(pgPurge.m_fPurgeRead);
pNG->SetPurgeReadLimit(pgPurge.m_iReadLimit);
pNG->SetPurgeUnread(pgPurge.m_fPurgeUnread);
pNG->SetPurgeUnreadLimit(pgPurge.m_iUnreadLimit);
pNG->SetPurgeOnHdrs(pgPurge.m_fOnHdr);
pNG->SetPurgeOnHdrsEvery(pgPurge.m_iDaysHdrPurge);
pNG->SetCompactOnExit(pgPurge.m_fShutdown);
pNG->SetCompactOnExitEvery(pgPurge.m_iShutCompact);
pNG->SetOverrideCustomHeaders (pgOverride.m_bOverrideCustomHeaders);
pNG->SetOverrideEmail (pgOverride.m_bOverrideEmail);
pNG->SetOverrideFullName (pgOverride.m_bOverrideFullName);
pNG->SetOverrideDecodeDir (pgOverride.m_bOverrideDecodeDir);
pNG->SetOverrideLimitHeaders (pgOverride.m_fOverrideLimitHeaders);
pNG->SetDecodeDir (pgOverride.m_strDecodeDir);
pNG->SetEmail (pgOverride.m_strEmail);
pNG->SetFullName (pgOverride.m_strFullName);
pNG->SetCustomHeaders (pgOverride.m_sCustomHeaders);
pNG->SetHeadersLimit (pgOverride.m_iHeaderLimit);
// destroy stuff if we transition from (Mode 2,3)->(Mode 1)
if ((TNewsGroup::kHeadersOnly == eOldStorage ||
TNewsGroup::kStoreBodies == eOldStorage) &&
TNewsGroup::kNothing == UtilGetStorageOption (pNG))
{
if (pNG->m_GroupID == m_curNewsgroupID)
{
// probably lots of articles have been removed
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_EMPTY);
// empty out thread list
pNG->Empty ();
}
// destroy headers for which there are no bodies
// -- what do we have to lock down?
pNG->StorageTransition (eOldStorage);
}
// associated filter
if (pgFilter.m_fOverrideFilter)
pNG->SetFilterID (pgFilter.m_iFilterID);
else
pNG->SetFilterID (0);
pNG->SetUseSignature (pgSignature.m_fCustomSig);
pNG->SetSigShortName (pgSignature.m_strShortName);
// if user changed the GoBack, then we should save this
// "this is done above" cpNewsServer->SaveReadRange ();
// make it last
cpNewsServer->SaveIndividualGroup ( pNG );
gpStore->SaveGlobalOptions ();
CMDIChildWnd * pMDIChild;
CMDIFrameWnd * pMDIFrame = (CMDIFrameWnd*) AfxGetMainWnd();
// note this is only 1 of the mdi children. could be more.
// we aren't handling them.
pMDIChild = pMDIFrame->MDIGetActive();
// apply the new ng font
pMDIChild->PostMessage ( WMU_NEWSVIEW_NEWFONT );
GetListCtrl().DeleteItem (idx);
// use name or nickname
if (0==AddStringWithData (pNG->GetBestname(), pNG->m_GroupID, &idx))
SetOneSelection (idx);
} // IDOK == DoModal()
}
// -------------------------------------------------------------------------
static void MicroplanetDoesntLikeSpamBlockingAddresses ()
{
TServerCountedPtr pServer;
CString strAddress = pServer->GetEmailAddress ();
strAddress.MakeUpper ();
if (strAddress.Find ("SPAM") >= 0 ||
strAddress.Find ("REMOVE") >= 0 ||
strAddress.Find ("DELETE") >= 0)
MsgResource (IDS_MICROPLANET_DOESNT_LIKE_SPAM);
}
// -------------------------------------------------------------------------
void CNewsView::ComposeMessage ()
{
// if mailing to microplanet, check the from address for spam-blocking
if (giMessageType == MESSAGE_TYPE_SUGGESTION ||
giMessageType == MESSAGE_TYPE_BUG)
MicroplanetDoesntLikeSpamBlockingAddresses ();
TPostTemplate *pTemplate =
giMessageType == MESSAGE_TYPE_BUG ? gptrApp->GetBugTemplate () :
(giMessageType == MESSAGE_TYPE_SUGGESTION ?
gptrApp->GetSuggestionTemplate () :
gptrApp->GetSendToFriendTemplate ());
pTemplate->m_strSubjPrefix = "";
pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_INIT_SUBJECT | TPT_MAIL;
switch (giMessageType) {
case MESSAGE_TYPE_BUG:
pTemplate->m_iFlags |= TPT_TO_STRING | TPT_INSERT_MACHINEINFO;
pTemplate->m_iCancelWarningID = IDS_WARNING_BUGCANCEL;
pTemplate->m_strSubject.LoadString (IDS_BUG_REPORT);
#if defined(KISS) || defined(KISS_TRIAL)
pTemplate->m_strTo.LoadString (IDS_SUPPORT_KISS);
#else
pTemplate->m_strTo.LoadString (IDS_SUPPORT_ADDR);
#endif
break;
case MESSAGE_TYPE_SUGGESTION:
pTemplate->m_iFlags |= TPT_TO_STRING;
pTemplate->m_iCancelWarningID = IDS_WARNING_SUGGESTCANCEL;
pTemplate->m_strSubject.LoadString (IDS_NEWS32_SUGGESTION);
pTemplate->m_strTo.LoadString (IDS_SUGGEST_ADDR);
break;
case MESSAGE_TYPE_SEND_TO_FRIEND:
{
TPath appFilespec;
CString & infoFilename = pTemplate->m_strExtraTextFile;
pTemplate->m_iCancelWarningID = IDS_WARNING_MESSAGECANCEL;
pTemplate->m_strSubject.LoadString (IDS_NEWS32_INFORMATION);
pTemplate->m_iFlags |= TPT_INSERT_FILE;
// look in the App's directory
infoFilename.LoadString (IDS_INFO_FILE);
TFileUtil::UseProgramPath(infoFilename, appFilespec);
pTemplate->m_strExtraTextFile = appFilespec;
break;
}
default:
ASSERT (0);
break;
}
pTemplate->Launch ( 0 /* newsgroupID */);
}
// ------------------------------------------------------------------------
//void CNewsView::OnHelpSendBugReport()
//{
// giMessageType = MESSAGE_TYPE_BUG;
// ComposeMessage ();
//}
// ------------------------------------------------------------------------
//void CNewsView::OnUpdateHelpSendBugReport (CCmdUI* pCmdUI)
//{
// TServerCountedPtr cpNewsServer;
//
// const CString & host = cpNewsServer->GetSmtpServer();
// if (!host.IsEmpty())
// pCmdUI->Enable (TRUE);
// else
// pCmdUI->Enable (FALSE);
//}
// ------------------------------------------------------------------------
//void CNewsView::OnHelpSendSuggestion()
//{
// giMessageType = MESSAGE_TYPE_SUGGESTION;
// ComposeMessage ();
//}
//
//// ------------------------------------------------------------------------
//void CNewsView::OnUpdateHelpSendSuggestion (CCmdUI* pCmdUI)
//{
// OnUpdateHelpSendBugReport(pCmdUI);
//}
// ------------------------------------------------------------------------
void CNewsView::OnSendToFriend()
{
giMessageType = MESSAGE_TYPE_SEND_TO_FRIEND;
ComposeMessage ();
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateSendToFriend (CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
const CString & host = cpNewsServer->GetSmtpServer();
if (!host.IsEmpty())
pCmdUI->Enable (TRUE);
else
pCmdUI->Enable (FALSE);
}
// ------------------------------------------------------------------------
// Keep trying to set the Caption on the mdichild
void CNewsView::OnTimer(UINT nIDEvent)
{
if (idCaptionTimer == nIDEvent)
{
if (sync_caption())
{
KillTimer ( m_hCaptionTimer );
m_hCaptionTimer = 0;
}
}
else if (CNewsView::idSelchangeTimer == nIDEvent)
{
// this is related to 1-click open NG
stop_selchange_timer ();
//TRACE("SelchangeTimer popped\n");
PostMessage (WMU_SELCHANGE_OPEN);
}
BASE_CLASS::OnTimer(nIDEvent);
}
///////////////////////////////////////////////////////////////////////////
// Get the name of the current NG and set the CDocument title. This
// will set the caption on the MDI window.
//
BOOL CNewsView::sync_caption()
{
TNewsGroup* pNG = 0;
LONG id = m_curNewsgroupID;
CString title;
TServerCountedPtr cpNewsServer;
TNewsGroupArray& vNewsGroups = cpNewsServer->GetSubscribedArray();
TNewsGroupArrayReadLock ngMgr(vNewsGroups);
if (0 == vNewsGroups->GetSize() || (0==id))
{
title.Empty ();
}
else
{
BOOL fUseLock;
TNewsGroupUseLock useLock(cpNewsServer, id, &fUseLock, pNG);
if (!fUseLock)
{
title.Empty ();
}
else
{
title = cpNewsServer->GetNewsServerName() + "/" + pNG->GetBestname();
}
}
// Documents have titles too!
GetDocument()->SetTitle ( title );
return TRUE;
}
/////////////////////////////////////////////////////////////////////
// GotoArticle - Jump to a specific group/article pair.
//
// return 0 if loaded, 1 if started download
//
LRESULT CNewsView::GotoArticle (WPARAM wParam, LPARAM lParam)
{
CListCtrl & lc = GetListCtrl ();
TServerCountedPtr cpNewsServer;
// find the newsgroup in the listbox, set selection, and
// call OpenNewsgroup
int iOpenRet = 0;
TGotoArticle *pGoto = (TGotoArticle *) lParam;
BOOL fOpened = FALSE;
int iRet = -1;
int count = lc.GetItemCount ();
for (int i = 0; i < count; i++)
{
if (pGoto->m_groupNumber == (int)lc.GetItemData (i))
{
#if 1
// the search dialog has logic to force a filter change (via
// WMU_FORCE_FILTER_CHANGE
#else
// set the view filter to the least restrictive one... ???? don't need
// to restrict filter if article is compatible with current filter set
gpUIMemory->SetViewFilter (0);
#endif
// ???? might need to optimize for newsgroup is current one somehow
// potentially by passing in the status of the message so
// that it can be compared against the current filter
// if we need to jump to a different NG, or we are about to utilize
// the 'All Articles' filter, then Open the newsgroup
if (m_curNewsgroupID != pGoto->m_groupNumber || pGoto->m_byOpenNG)
{
if (pGoto->m_byDownloadNG)
{
// this is useful for newsurl support. DL a newly subscribed NG.
iRet = iOpenRet = OpenNewsgroup ( kFetchOnZero, kCurrentFilter, pGoto->m_groupNumber);
}
else
iRet = iOpenRet = OpenNewsgroup ( kOpenNormal, kCurrentFilter, pGoto->m_groupNumber);
}
if (iRet >= 0)
{
this->AddOneClickGroupInterference ();
SetOneSelection (i);
}
else
{
SetOneSelection (i);
}
break;
}
}
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, m_curNewsgroupID, &fUseLock, pNG);
if (fUseLock)
{
switch (UtilGetStorageOption ( pNG ))
{
case TNewsGroup::kNothing:
m_GotoArticle = *pGoto;
break;
case TNewsGroup::kHeadersOnly:
case TNewsGroup::kStoreBodies:
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_GOTOARTICLE, pGoto);
break;
default:
ASSERT(0);
break;
}
}
return iOpenRet;
}
/////////////////////////////////////////////////////////////////////
// ProcessMailTo - Send mail to somebody.
/////////////////////////////////////////////////////////////////////
LRESULT CNewsView::ProcessMailTo (WPARAM wParam, LPARAM lParam)
{
TPostTemplate *pTemplate = gptrApp->GetMailToTemplate ();
pTemplate->m_iFlags = TPT_CANCEL_WARNING_ID | TPT_MAIL | TPT_TO_STRING;
pTemplate->m_iCancelWarningID = IDS_WARNING_MESSAGECANCEL;
pTemplate->m_strTo = (LPCTSTR) lParam;
pTemplate->Launch (GetCurNewsGroupID());
return FALSE;
}
// ---------------------------------------------------------------------
// handles WMU_NEWSVIEW_NEWFONT
void CNewsView::ApplyNewFont(void)
{
TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors ();
if (!gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG())
{
CListCtrl &lc = GetListCtrl();
lc.SetBkColor ( pBackgrounds->GetNewsgroupBackground() );
lc.SetTextBkColor ( pBackgrounds->GetNewsgroupBackground() );
}
GetListCtrl().SetTextColor (
gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor() );
LOGFONT lfCurrent;
// check against current font.
CFont* pCurCFont = GetFont();
if (pCurCFont)
pCurCFont->GetObject (sizeof(LOGFONT), &lfCurrent);
else
{
// we should always have an explicit font set.
ASSERT(0);
}
const LOGFONT* plfFontNew;
BOOL fCustom = gpGlobalOptions->IsCustomNGFont();
if (fCustom)
plfFontNew = gpGlobalOptions->GetNewsgroupFont();
else
plfFontNew = &gpGlobalOptions->m_defNGFont;
// Only if the newfont is different, do we apply it.
// 9-15-95 this may not work due to non-match on precision,
// clipping and fine points like that
if (memcmp (plfFontNew, &lfCurrent, sizeof(LOGFONT)))
{
if (m_font.m_hObject)
{
m_font.DeleteObject (); // i pray this does the detach
m_font.m_hObject = NULL;
}
m_font.CreateFontIndirect ( plfFontNew );
SetFont (&m_font, TRUE);
// m_font is cleaned up by CFont destructor.
}
}
LRESULT CNewsView::OnDisplayArtcount (WPARAM wParam, LPARAM lParam)
{
int iGroupID = (int) wParam;
if (iGroupID <= 0)
{
// redraw all
this->Invalidate ();
}
else
{
// redraw to show the Total number of new articles
RedrawByGroupID ( iGroupID );
}
return 0;
}
///////////////////////////////////////////////////////////////////////////
// The MDI window does the 4 way routing. If we really do have the focus
// save the article shown is the view pane.
void CNewsView::OnSaveToFile ()
{
BOOL fMax;
TNews3MDIChildWnd *pMDI = (TNews3MDIChildWnd *)
((CMainFrame*) AfxGetMainWnd ())->MDIGetActive (&fMax);
TMdiLayout *pLayout = pMDI->GetLayoutWnd ();
TArticleFormView *pArtView = pLayout->GetArtFormView();
pArtView->SendMessage (WM_COMMAND, ID_ARTICLE_SAVE_AS);
}
void CNewsView::OnUpdateSaveToFile (CCmdUI* pCmdUI)
{
BOOL fValid = (GetBrowseHeader () && GetBrowseText ());
pCmdUI->Enable (fValid);
}
// -------------------------------------------------------------------------
void CNewsView::OnUpdateThreadChangeToRead (CCmdUI* pCmdUI)
{
pCmdUI->Enable (FALSE);
}
// -------------------------------------------------------------------------
// this should always be disabled when the NewsView pane has focus
void CNewsView::OnThreadChangeToRead ()
{
// ChangeThreadStatusTo (TStatusUnit::kNew, FALSE);
}
void CNewsView::EmptyBrowsePointers ()
{
SetBrowseHeader (NULL);
SetBrowseText (NULL);
}
// -------------------------------------------------------------------------
// a newsgroup's headers are displayed
BOOL CNewsView::IsNewsgroupDisplayed ()
{
return m_curNewsgroupID ? TRUE : FALSE;
}
// -------------------------------------------------------------------------
// True if exactly one
bool CNewsView::IsExactlyOneNewsgroupSelected ()
{
return GetListCtrl().GetSelectedCount() == 1;
}
// -------------------------------------------------------------------------
bool CNewsView::IsOneOrMoreNewsgroupSelected ()
{
return GetListCtrl().GetSelectedCount() > 0;
}
// -------------------------------------------------------------------------
void CNewsView::OnUpdateNewsgroupUnsubscribe (CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// -------------------------------------------------------------------------
// 4-19-96 amc Changed catchup alot. So I can use any selected NG.
void CNewsView::OnUpdateNewsgroupCatchup (CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// -------------------------------------------------------------------------
void CNewsView::OnUpdateNewsgroupProperties (CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsExactlyOneNewsgroupSelected ());
}
void CNewsView::OnUpdateDisable(CCmdUI* pCmdUI)
{
pCmdUI->Enable (FALSE);
}
// -------------------------------------------------------------------------
// this is a real accelerator
void CNewsView::OnCmdTabaround()
{
((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->
PostMessage (WMU_CHILD_TAB, FALSE, 0);
}
// -------------------------------------------------------------------------
// this is a real accelerator
void CNewsView::OnCmdTabBack()
{
((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame()->
PostMessage (WMU_CHILD_TAB, TRUE, 0);
}
///////////////////////////////////////////////////////////////////////////
// Get articles for all subscribed newsgroups
//
void CNewsView::OnGetheadersAllGroups()
{
// get headers, (force the retrieve cycle, fUserAction)
CNewsDoc::DocGetHeadersAllGroups (true, true);
}
void CNewsView::OnUpdateGetheadersAllGroups(CCmdUI* pCmdUI)
{
BOOL fEnable = FALSE;
if (gpTasker)
fEnable = gpTasker->CanRetrieveCycle ();
pCmdUI->Enable ( fEnable );
}
///////////////////////////////////////////////////////////////////////////
// Get article headers for one group. Function does NOT map to a menu-item
//
void CNewsView::GetHeadersOneGroup()
{
if (0 == gpTasker)
return;
BOOL fCatchUp = gpGlobalOptions->GetRegSwitch()->GetCatchUpOnRetrieve();
int iGroupId = GetSelectedGroupID ();
if (LB_ERR != iGroupId)
get_header_worker (iGroupId, fCatchUp, TRUE /* get all */, 0);
}
// ------------------------------------------------------------------------
// also used by ID_VERIFY_HDRS
void CNewsView::OnUpdateGetHeadersMultiGroup(CCmdUI* pCmdUI)
{
pCmdUI->Enable (gpTasker ? IsOneOrMoreNewsgroupSelected () : false);
}
// ------------------------------------------------------------------------
// Request headers for 1 or more groups
void CNewsView::OnGetHeadersMultiGroup ()
{
// call worker function
get_header_multigroup_worker (TRUE /* fGetAllHdrs */, 0);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateGetheaderLimited(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
OnUpdateGetHeadersMultiGroup( pCmdUI);
}
// ------------------------------------------------------------------------
// Get 'X' headers
void CNewsView::OnGetheaderLimited()
{
CPromptLimitHeaders sDlg (AfxGetMainWnd());
if (IDOK == sDlg.DoModal())
{
get_header_multigroup_worker (FALSE, sDlg.m_iCount);
}
}
// ------------------------------------------------------------------------
int CNewsView::get_header_multigroup_worker (BOOL fGetAll, int iHdrsLimit)
{
if (0 == gpTasker)
return 1;
BOOL fCatchUp = gpGlobalOptions->GetRegSwitch()->GetCatchUpOnRetrieve();
CPtrArray vec;
int iSelCount = 0;
// get info on multi selection
if (multisel_get (&vec, &iSelCount))
return 1;
for (int i = 0; i < vec.GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]);
get_header_worker (pPair->id, fCatchUp, fGetAll, iHdrsLimit);
}
FreeGroupIDPairs (&vec);
return 0;
}
// ------------------------------------------------------------------------
//
int CNewsView::get_header_worker (int iGroupId,
BOOL fCatchUp,
BOOL fGetAll,
int iHdrsLimit)
{
if (LB_ERR == iGroupId)
return 1;
BOOL fConnected = gpTasker->IsConnected();
if (!fConnected)
return 1;
TServerCountedPtr cpNewsServer;
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, iGroupId, &fUseLock, pNG);
if (!fUseLock)
return 1;
if (fCatchUp)
{
CatchUp_Helper ( iGroupId, FALSE );
}
// before downloading headers Purge via Date criteria
// Master Plan:
// purge
// get headers
// refresh ui.
// If we are't connected then don't purge either [2-12-97 amc]
if (fConnected && pNG->NeedsPurge())
pNG->PurgeByDate();
gpTasker->PrioritizeNewsgroup ( pNG->GetName(), fGetAll, iHdrsLimit );
return 0;
}
// ------------------------------------------------------------------------
// OnVerifyLocalHeaders -- see if all local headers still exist on the
// server. If any have been expired, remove them from the display (reload)
void CNewsView::OnVerifyLocalHeaders ()
{
try
{
CPtrArray vec;
int iSelCount = 0;
// get info on multi selection
if (multisel_get (&vec, &iSelCount))
return;
TServerCountedPtr cpNewsServer;
for (int i = 0; i < vec.GetSize(); i++)
{
TGroupIDPair * pPair = static_cast<TGroupIDPair*>(vec[i]);
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, pPair->id, &fUseLock, pNG);
if (fUseLock && TNewsGroup::kNothing != UtilGetStorageOption (pNG))
gpTasker->VerifyLocalHeaders (pNG);
}
FreeGroupIDPairs (&vec);
}
catch(...) { /* trap all errors */ }
}
void CNewsView::OnDisplayAllArticleCounts(void)
{
// for listctrl redraw it all
Invalidate ();
}
///////////////////////////////////////////////////////////////////////////
// Created 3-24-96
// Once all the headers have been saved - re-open the newsgroup.
// 1 - this saves the user the effort of opening the NG himself
// 2 - after purging articles (during hdr retrieve) we sorta haveto
// repaint, (some articles showing in the LBX may be gone)
//
LRESULT CNewsView::OnNewsgroupHdrsDone(WPARAM wParam, LPARAM lParam)
{
TServerCountedPtr cpNewsServer;
LONG grpID = (LONG) wParam;
BOOL fUserAction = (BOOL) lParam;
if (grpID == m_curNewsgroupID)
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, grpID, &fUseLock, pNG);
if (fUseLock)
{
if (fUserAction)
OpenNewsgroup (kOpenNormal, kPreferredFilter, grpID);
}
}
return 0;
}
//-------------------------------------------------------------------------
//
LRESULT CNewsView::OnMode1HdrsDone(WPARAM wParam, LPARAM lParam)
{
LONG grpID = (LONG) wParam;
BOOL fOld = (lParam & 0x1) ? TRUE : FALSE;
BOOL fNew = (lParam & 0x2) ? TRUE : FALSE;
TServerCountedPtr cpNewsServer;
if (grpID == m_curNewsgroupID)
{
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, grpID, &fUseLock, pNG);
if (fUseLock)
{
if (TNewsGroup::kNothing == UtilGetStorageOption(pNG))
{
// mode 1 - Don't call OpenNewsgroup this would be an infinite loop
pNG->Mode1_Thread (fOld, fNew);
please_update_views ();
// 'GOTO' article from Search Window
if (m_GotoArticle.m_articleNumber >= 0)
{
EmptyBrowsePointers ();
GetDocument()->UpdateAllViews(this, VIEWHINT_GOTOARTICLE,
&m_GotoArticle);
m_GotoArticle.m_articleNumber = -1;
}
return 0;
}
}
}
return 0;
}
// There are no objects in the newsview you can copy
void CNewsView::OnUpdateEditCopy(CCmdUI* pCmdUI)
{
pCmdUI->Enable( FALSE );
}
// ------------------------------------------------------------------------
// subthread forces UI to show a message box
LRESULT CNewsView::OnErrorFromServer (WPARAM wParam, LPARAM lParam)
{
ASSERT(wParam);
if (wParam)
{
PTYP_ERROR_FROM_SERVER psErr = (PTYP_ERROR_FROM_SERVER)(void*)(wParam);
// Response from Server: %s
CString strReason;
strReason.Format (IDS_UTIL_SERVRESP, psErr->iRet, LPCTSTR(psErr->serverString));
TNNTPErrorDialog sDlg(this);
sDlg.m_strWhen = psErr->actionDesc;
sDlg.m_strReason = strReason;
// show fairly polished dlg box
sDlg.DoModal ();
delete psErr;
}
return TRUE;
}
void CNewsView::protected_open(TNewsGroup* pNG, BOOL fOpen)
{
TEnterCSection enter(&m_dbCritSect);
int iCount = 10;
if (fOpen)
{
TUserDisplay_UIPane sAutoDraw("Open group");
pNG->Open ();
++ iLocalOpen;
}
else
{
TUserDisplay_UIPane sAutoDraw("Close group");
ASSERT(iLocalOpen > 0);
if (iLocalOpen > 0)
{
pNG->Close ();
-- iLocalOpen;
}
}
}
//////////////////////////////////////////////////////////////////////////
// Called from OnLbxSelChange(void)
LRESULT CNewsView::OnSelChangeOpen(WPARAM wParam, LPARAM lParam)
{
//TRACE0("Start from SelChange Open\n");
OpenNewsgroup( kFetchOnZero, kPreferredFilter );
//TRACE0("Returning from SelChange Open\n");
return 0;
}
//-------------------------------------------------------------------------
// return TRUE to continue, FALSE to abort
BOOL CNewsView::check_server_posting_allowed()
{
TServerCountedPtr cpNewsServer;
if (cpNewsServer->GetPostingAllowed())
return TRUE;
CString msg;
AfxFormatString1(msg, IDS_WARN_SERVER_NOPOSTALLOWED,
(LPCTSTR) cpNewsServer->GetNewsServerName());
// are you sure you want to continue?
return (IDYES == NewsMessageBox(this, msg, MB_YESNO | MB_ICONQUESTION));
}
//-------------------------------------------------------------------------
// validate_connection -- Suppose the normal pump is busy downloading a
// binary. As the user switches to a mode-1 NG, the emergency-pump
// should be used, since the n-pump is busy. Start it up and it should
// be running when the ArticleBank needs it. It would be GROSS to
// move the connection code to when the ArticleBank calls
// gpTasker->GetRangeFor()
BOOL CNewsView::validate_connection ()
{
TServerCountedPtr cpNewsServer;
if (FALSE == gpTasker->IsConnected())
return TRUE;
else
{
// ok we are connected
if (FALSE == gpTasker->NormalPumpBusy())
return TRUE;
int iTry;
BOOL fConnected;
BOOL fContinueConnect = FALSE;
fConnected = gpTasker->SecondIsConnected ( &fContinueConnect );
if (fConnected)
return TRUE;
else
{
// since the norm-pump is running, we should have permission to
// start the e-pump
if (!fContinueConnect)
return FALSE;
iTry = gpTasker->SecondConnect ( cpNewsServer->GetNewsServerAddress() );
if (0 != iTry)
return FALSE;
return TRUE;
}
}
}
// ------------------------------------------------------------------------
// used for CatchUp and Move to Next newsgroup. Returns grpid.
BOOL CNewsView::validate_next_newsgroup (int * pGrpId, int * pIdx)
{
TServerCountedPtr cpNewsServer;
CListCtrl & lc = GetListCtrl ();
int iNext = -1;
int tot = lc.GetItemCount();
for (int i = 0; i < tot; ++i)
{
// hunt for a newsgroup we can open
if (0 == iNext)
{
int iGrpID = (int) lc.GetItemData(i);
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, iGrpID, &fUseLock, pNG);
if (fUseLock)
{
if (TNewsGroup::kNothing == UtilGetStorageOption (pNG))
{
// if we are not connected keep going
if (gpTasker->IsConnected())
{
*pGrpId = iGrpID;
*pIdx = i;
return TRUE;
}
}
else
{
*pGrpId = iGrpID;
*pIdx = i;
return TRUE;
}
}
}
// find our current guy
if (m_curNewsgroupID == (int) lc.GetItemData(i))
iNext = 0;
}
return FALSE;
}
// ------------------------------------------------------------------------
// A real public func
void CNewsView::OpenNewsgroupEx(CNewsView::EOpenMode eMode)
{
// open the selected one!
OpenNewsgroup ( eMode, kPreferredFilter );
}
// ------------------------------------------------------------------------
int CNewsView::NumSelected ()
{
return GetListCtrl().GetSelectedCount();
}
// ------------------------------------------------------------------------
// GetSelectedIDs -- takes a pointer to an integer array, and returns the
// group IDs for the selected groups
void CNewsView::GetSelectedIDs (int *piIDs, int iSize)
{
// first, fill dest array with zeros
int i = 0;
for (i = 0; i < iSize; i++)
piIDs [i] = 0;
int iNumSelected = NumSelected ();
if (iNumSelected <= 0)
return;
CListCtrl & lc = GetListCtrl();
int * piIndices = new int [iNumSelected];
auto_ptr <int> pIndicesDeleter(piIndices);
int n = 0;
POSITION pos = lc.GetFirstSelectedItemPosition ();
while (pos)
piIndices[n++] = lc.GetNextSelectedItem (pos);
for (i = 0; i < iNumSelected && i < iSize; i++)
piIDs [i] = lc.GetItemData (piIndices [i]);
}
// ------------------------------------------------------------------------
// OnUpdateKeepSampled -- enabled if any selected group is sampled
void CNewsView::OnUpdateKeepSampled(CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
BOOL bEnable = FALSE;
CPtrArray sPairs; // holds a collection of (groupID, name) pairs
int iNum = 0;
if (multisel_get (&sPairs, &iNum)) {
pCmdUI->Enable (FALSE);
return;
}
iNum = sPairs.GetSize();
for (int i = 0; i < iNum; i++) {
// get pNG
TGroupIDPair *pPair = static_cast <TGroupIDPair*> (sPairs [i]);
TNewsGroup *pNG;
BOOL fUseLock;
TNewsGroupUseLock useLock (cpNewsServer, pPair->id, &fUseLock, pNG);
if (!fUseLock)
break;
// check it
if (pNG->IsSampled ()) {
bEnable = TRUE;
break;
}
}
FreeGroupIDPairs (&sPairs);
pCmdUI->Enable (bEnable);
}
// ------------------------------------------------------------------------
void CNewsView::OnKeepSampled()
{
TServerCountedPtr cpNewsServer;
CPtrArray sPairs; // holds a collection of (groupID, name) pairs
int iNum = 0;
if (multisel_get (&sPairs, &iNum))
return;
iNum = sPairs.GetSize();
for (int i = 0; i < iNum; i++) {
// get pNG
TGroupIDPair *pPair = static_cast <TGroupIDPair*> (sPairs [i]);
TNewsGroup *pNG;
BOOL fUseLock;
TNewsGroupUseLock useLock (cpNewsServer, pPair->id, &fUseLock, pNG);
if (!fUseLock)
break;
// keep the group
pNG->Sample (FALSE);
}
FreeGroupIDPairs (&sPairs);
// redraw all
Invalidate ();
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateKeepAllSampled(CCmdUI* pCmdUI)
{
TServerCountedPtr cpNewsServer;
BOOL bEnable = FALSE;
TNewsGroupArray &vNewsGroups = cpNewsServer->GetSubscribedArray ();
int iNum = vNewsGroups->GetSize ();
for (int i = 0; i < iNum; i++) {
TNewsGroup *pNG = vNewsGroups [i];
if (pNG->IsSampled ())
bEnable = TRUE;
}
pCmdUI->Enable (bEnable);
}
// ------------------------------------------------------------------------
void CNewsView::OnKeepAllSampled()
{
TServerCountedPtr cpNewsServer;
TNewsGroupArray &vNewsGroups = cpNewsServer->GetSubscribedArray ();
int iNum = vNewsGroups->GetSize ();
for (int i = 0; i < iNum; i++) {
TNewsGroup *pNG = vNewsGroups [i];
pNG->Sample (FALSE);
}
// redraw all
Invalidate ();
}
// ------------------------------------------------------------------------
void CNewsView::OnEditSelectAll()
{
GetListCtrl().SetItemState (-1, LVIS_SELECTED, LVIS_SELECTED);
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateEditSelectAll(CCmdUI* pCmdUI)
{
pCmdUI->Enable (GetListCtrl().GetItemCount () > 0);
}
// ------------------------------------------------------------------------
void CNewsView::EmptyListbox ()
{
GetListCtrl().DeleteAllItems ();
}
// ------------------------------------------------------------------------
void CNewsView::OnUpdateDeleteSelected(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ---------------------------------------------------
void CNewsView::OnHelpResyncStati()
{
//TRACE0("Resyncing...\n");
TServerCountedPtr cpNewsServer;
LONG nGID = GetCurNewsGroupID();
BOOL fUseLock;
TNewsGroup* pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, nGID, &fUseLock, pNG);
if (!fUseLock)
return;
{
TAutoClose sCloser(pNG);
CWaitCursor cursor;
pNG->ValidateStati ();
}
// redraw all
Invalidate ();
}
// Pindown view filter
void CNewsView::OnNewsgroupPinfilter()
{
m_fPinFilter = !m_fPinFilter;
// save immediately
gpGlobalOptions->GetRegUI()->SetPinFilter( m_fPinFilter );
gpGlobalOptions->GetRegUI()->Save ();
((CMainFrame*)AfxGetMainWnd())->UpdatePinFilter ( m_fPinFilter );
}
void CNewsView::OnUpdateNewsgroupPinfilter(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck ( m_fPinFilter );
}
// -------------------------------------------------------------------------
// Returns 0 for success. On success return the group-id we found.
//
int CNewsView::GetNextGroup (EJmpQuery eQuery, int * pGroupID)
{
CListCtrl & lc = GetListCtrl ();
// depends on the 'sort' order, so we have to ask the UI. ick!
int curGID = GetCurNewsGroupID();
bool fFound = false;
int nextI = 0;
for (int i = 0; i < lc.GetItemCount(); i++)
{
if (lc.GetItemData (i) == curGID)
{
nextI = i + 1;
break;
}
}
if (nextI >= lc.GetItemCount() || 0==nextI)
return 1;
TServerCountedPtr cpNewsServer; // smart pointer
for (; nextI < lc.GetItemCount(); nextI++)
{
int gid = lc.GetItemData (nextI);
BOOL fUseLock;
TNewsGroup * pNG = 0;
TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG);
if (pNG)
{
if (pNG->QueryExistArticle (eQuery))
{
*pGroupID = gid;
return 0;
}
}
}
return 1; // no matching group found
}
BOOL CNewsView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
cs.style &= ~(LVS_ICON | LVS_SMALLICON | LVS_LIST);
cs.style |= LVS_REPORT | LVS_NOSORTHEADER | LVS_SORTASCENDING
| LVS_SHOWSELALWAYS;
return BASE_CLASS::PreCreateWindow(cs);
}
// ------------------------------------------------------------------------
int CNewsView::AddStringWithData (const CString & groupName,
LONG lGroupID,
int * pIdxAt /* =NULL */)
{
CListCtrl & lc = GetListCtrl();
int idx;
LVITEM lvi; ZeroMemory (&lvi, sizeof(lvi));
lvi.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE;
lvi.iItem = lc.GetItemCount();
lvi.iSubItem = 0;
lvi.iImage = I_IMAGECALLBACK;
lvi.pszText = LPTSTR(LPCTSTR(groupName));
// lvi.state |= INDEXTOOVERLAYMASK(1);
// lvi.stateMask = LVIS_OVERLAYMASK;
lvi.lParam = lGroupID;
if (-1 == (idx = lc.InsertItem ( &lvi)))
return 1; //fail
// local count, server count
lc.SetItemText (idx, 1, LPSTR_TEXTCALLBACK);
lc.SetItemText (idx, 2, LPSTR_TEXTCALLBACK);
if (pIdxAt)
*pIdxAt = idx;
return 0; // success
}
// ------------------------------------------------------------------------
int CNewsView::SetOneSelection (int idx)
{
CListCtrl & lc = GetListCtrl();
// note: in case the SELCHANGE notification is hooked, do not
// - turn off selection on all
// - turn on selection on the index we want. (It may cause a
// one-click group to re-open)
for (int i = 0; i < lc.GetItemCount(); i++)
{
if (i == idx)
{
// select this guy
lc.SetItemState (idx, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
}
else
{
// deselect all
lc.SetItemState (i, 0, LVIS_SELECTED | LVIS_FOCUSED);
}
}
// this useful thing is provided by MFC
lc.EnsureVisible (idx, TRUE /* fPartialOK */);
// success
return 0;
}
// ---------------------------------------------------------------------
// called from OnCreate
void CNewsView::SetupFont ()
{
TBackgroundColors *pBackgrounds = gpGlobalOptions->GetBackgroundColors ();
COLORREF ngCR = pBackgrounds->GetNewsgroupBackground();
if (!gpGlobalOptions->GetRegSwitch()->IsDefaultNGBG())
{
CListCtrl &lc = GetListCtrl();
lc.SetBkColor ( pBackgrounds->GetNewsgroupBackground() );
lc.SetTextBkColor ( pBackgrounds->GetNewsgroupBackground() );
}
ngCR = gpGlobalOptions->GetRegFonts()->GetNewsgroupFontColor();
GetListCtrl().SetTextColor (ngCR);
if (0 == gpGlobalOptions->m_defNGFont.lfFaceName[0])
{
// show this info in the config dialog box
gpVariableFont->GetObject ( sizeof (LOGFONT), &gpGlobalOptions->m_defNGFont );
}
if (m_font.m_hObject)
{
m_font.DeleteObject (); // i pray this does the detach
m_font.m_hObject = NULL;
}
if (gpGlobalOptions->IsCustomNGFont())
m_font.CreateFontIndirect ( gpGlobalOptions->GetNewsgroupFont() );
else
{
// default to microplanet defined small font
LOGFONT info;
gpVariableFont->GetObject ( sizeof (info), &info );
m_font.CreateFontIndirect ( &info );
}
SetFont ( &m_font );
}
// --------------------------------------------------------------------------
void CNewsView::OnGetDisplayInfo(NMHDR* pNMHDR, LRESULT* pResult)
{
LV_DISPINFO * pDispInfo = (LV_DISPINFO*)pNMHDR;
if (!IsActiveServer())
{
*pResult = 0;
return;
}
LVITEM & lvi = pDispInfo->item;
TServerCountedPtr cpNewsServer;
TNewsGroup * pNG = 0;
BOOL fUseLock;
LONG gid = LONG(GetListCtrl().GetItemData (lvi.iItem));
TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG);
if (fUseLock)
{
if (lvi.mask & LVIF_IMAGE)
{
switch (pNG->GetStorageOption())
{
case TNewsGroup::kNothing:
lvi.iImage = 0;
break;
case TNewsGroup::kHeadersOnly:
lvi.iImage = 1;
break;
case TNewsGroup::kStoreBodies:
lvi.iImage = 2;
break;
}
if (pNG->IsSampled ())
lvi.iImage += 3;
}
if (lvi.mask & LVIF_STATE)
{
if (!pNG->IsActiveGroup())
lvi.state |= INDEXTOOVERLAYMASK(1);
}
if (lvi.mask & LVIF_TEXT)
{
int iLocalNew, iServerNew, nTotal;
pNG->FormatNewArticles ( iLocalNew, iServerNew , nTotal);
if (1 == lvi.iSubItem)
wsprintf (lvi.pszText, "%d", iLocalNew);
else if (2 == lvi.iSubItem)
wsprintf (lvi.pszText, "%d", iServerNew);
// data eventuall is displayed in status bar pane
if (GetCurNewsGroupID() == gid)
gpUserDisplay->SetCountTotal ( nTotal );
}
}
*pResult = 0;
}
///////////////////////////////////////////////////////////////////////////
// Depends on user preference - single click/selchange opens a newsgroup
//
void CNewsView::OnClick (NMHDR* pNMHDR, LRESULT* pResult)
{
//TRACE0("On Click\n");
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup() &&
(1 == GetListCtrl().GetSelectedCount()))
{
// turn off delayed activation. Actually this is futile, since
// NM_ITEMCHANGE will start the timer again
stop_selchange_timer();
AddOneClickGroupInterference();
PostMessage (WMU_SELCHANGE_OPEN);
}
*pResult = 0;
}
///////////////////////////////////////////////////////////////////////////
void CNewsView::AddOneClickGroupInterference ()
{
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup())
{
m_iOneClickInterference ++;
}
}
///////////////////////////////////////////////////////////////////////////
// Substitute for LBN_SELCHANGE,
//
void CNewsView::OnItemChanged (NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 1;
LPNMLISTVIEW pnmlv = (LPNMLISTVIEW) pNMHDR;
BOOL fNewSelect = (pnmlv->uNewState & LVIS_SELECTED);
BOOL fOldSelect = (pnmlv->uOldState & LVIS_SELECTED);
if ( fNewSelect && !fOldSelect )
{
//TRACE0("OnItemChanged\n");
if (gpGlobalOptions->GetRegUI()->GetOneClickGroup() &&
(1 == GetListCtrl().GetSelectedCount()))
{
if (m_iOneClickInterference > 0)
{
*pResult = 0;
// do not start timer!
--m_iOneClickInterference;
}
else
{
// this will pop unless:
// a: another selchange comes
// b: this turns out to be a right click
//
start_selchange_timer ();
// OnTimer will call
// PostMessage (WMU_SELCHANGE_OPEN);
// 5-25-96 Rather than calling OpenNewsgroup() directly,
// post a message to myself. That way the processing
// can finish before we start the big fat OpenNewsgroup function
*pResult = 0;
}
}
}
}
///////////////////////////////////////////////////////////////////////////
void CNewsView::OnReturn(NMHDR* pNMHDR, LRESULT* pResult)
{
// We got an VK_RETURN, so open the newsgroup
OpenNewsgroup ( kFetchOnZero, kPreferredFilter );
*pResult = 0;
}
// ------------------------------------------------------------------------
void CNewsView::OnRclick(NMHDR* pNMHDR, LRESULT* pResult)
{
// seems to set selection on Right click
// this is so we can right click on a newsgroup, an put selection on it
// with out actually opening the newsgroup via 1-click
stop_selchange_timer ();
//TRACE("Rclik stopped selchange action\n");
*pResult = 0;
}
///////////////////////////////////////////////////////////////////////////
// Depends on user preference - double click opens a newsgroup
//
void CNewsView::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult)
{
if (FALSE == gpGlobalOptions->GetRegUI()->GetOneClickGroup())
OpenNewsgroup( kFetchOnZero, kPreferredFilter );
*pResult = 0;
}
// ------------------------------------------------------------------------
void CNewsView::RedrawByGroupID (int iGroupID)
{
CListCtrl & lc = GetListCtrl();
RECT rct;
int n = lc.GetItemCount();
for (--n; n >= 0; --n)
{
if (iGroupID == (int) lc.GetItemData (n))
{
lc.GetItemRect (n, &rct, LVIR_BOUNDS);
// we only need to redraw the counters
InvalidateRect (&rct);
break;
}
}
}
// ------------------------------------------------------------------------
void CNewsView::SaveColumnSettings()
{
SaveColumnSettingsTo (m_fTrackZoom ? "NGPaneZ" : "NGPane");
}
// ------------------------------------------------------------------------
void CNewsView::SaveColumnSettingsTo (const CString & strLabel)
{
TRegUI* pRegUI = gpGlobalOptions->GetRegUI();
int riWidths[3];
riWidths[0] = GetListCtrl().GetColumnWidth (0);
riWidths[1] = GetListCtrl().GetColumnWidth (1);
riWidths[2] = GetListCtrl().GetColumnWidth (2);
pRegUI->SaveUtilHeaders(strLabel, riWidths, ELEM(riWidths));
}
// ------------------------------------------------------------------------
// tnews3md.cpp does the real work. Each active view must have a
// handler for this
//
void CNewsView::OnUpdateArticleMore (CCmdUI* pCmdUI)
{
CWnd* pMdiChild = ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame();
BOOL fOK = ((TNews3MDIChildWnd*) pMdiChild)->CanArticleMore();
pCmdUI->Enable (fOK);
}
// ------------------------------------------------------------------------
BOOL CNewsView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
// let the mdi-child decide which pane will handle this
CWnd* pMdiChild = ((CFrameWnd*) AfxGetMainWnd())->GetActiveFrame();
if (!pMdiChild)
return FALSE;
if (((TNews3MDIChildWnd*) pMdiChild)->handleMouseWheel(nFlags, zDelta, pt))
return TRUE;
else
return handleMouseWheel (nFlags, zDelta, pt);
}
// ------------------------------------------------------------------------
// called from MDI child
BOOL CNewsView::handleMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
return BASE_CLASS::OnMouseWheel (nFlags, zDelta, pt);
}
// ------------------------------------------------------------------------
// zoom mode has its own set of column widths
void CNewsView::handle_zoom (bool fZoom, CObject* pHint)
{
int riWidths[3];
bool fApply = false;
TRegUI* pRegUI = gpGlobalOptions->GetRegUI();
if (fZoom)
{
if (pHint == this)
{
// The roles are the same, but the widths can be different
// save off normal
SaveColumnSettings ();
if (0 != pRegUI->LoadUtilHeaders("NGPaneZ", riWidths, ELEM(riWidths)))
return;
fApply = true;
m_fTrackZoom = true; // passive variable, as a convenienence
}
}
else
{
TUnZoomHintInfo * pUnZoom = static_cast<TUnZoomHintInfo *>(pHint);
if (pUnZoom->m_pTravelView == this)
{
m_fTrackZoom = false;
// save zoomed
SaveColumnSettingsTo ("NGPaneZ");
// load Normal
if (0 != pRegUI->LoadUtilHeaders("NGPane", riWidths, ELEM(riWidths)))
return;
fApply = true;
}
}
if (fApply)
{
GetListCtrl().SetColumnWidth (0, riWidths[0]);
GetListCtrl().SetColumnWidth (1, riWidths[1]);
GetListCtrl().SetColumnWidth (2, riWidths[2]);
}
}
// pCmdUI for ID_GETTAGGED_FOR_GROUPS
void CNewsView::OnUpdateGettaggedForgroups(CCmdUI* pCmdUI)
{
pCmdUI->Enable (IsOneOrMoreNewsgroupSelected ());
}
// ----------------------------------------------------------
// Retrieve Tagged articles only for the selected groups
void CNewsView::OnGettaggedForgroups()
{
// holds a collection of (groupID, name) pairs
CPtrArray vecPairs;
int sel = 0;
// get info on multisel
if (multisel_get (&vecPairs, &sel))
return;
int tot = vecPairs.GetSize();
// build up CDWordArray that only contains GroupIDs
CDWordArray vecIDs;
for (int i = 0; i < tot; i++)
{
TGroupIDPair* pPair = static_cast<TGroupIDPair*>(vecPairs[i]);
vecIDs.Add (pPair->id);
}
FreeGroupIDPairs (&vecPairs);
TServerCountedPtr cpServer;
cpServer->GetPersistentTags().RetrieveTagged (false, vecIDs);
}
// -------------------------------------------------------------------------
BOOL CNewsView::PreTranslateMessage(MSG* pMsg)
{
if (::IsWindow (m_sToolTips.m_hWnd) && pMsg->hwnd == m_hWnd)
{
switch (pMsg->message)
{
case WM_LBUTTONDOWN:
case WM_MOUSEMOVE:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
m_sToolTips.RelayEvent (pMsg);
break;
}
}
return BASE_CLASS::PreTranslateMessage(pMsg);
}
// -------------------------------------------------------------------------
void CNewsView::OnMouseMove(UINT nFlags, CPoint point)
{
if (!(nFlags & MK_LBUTTON) || 0 == GetListCtrl().GetSelectedCount ())
{
HandleToolTips (point);
BASE_CLASS::OnMouseMove (nFlags, point);
return;
}
BASE_CLASS::OnMouseMove(nFlags, point);
}
// -------------------------------------------------------------------------
BOOL CNewsView::OnNeedText (UINT, NMHDR *pNMHdr, LRESULT *)
{
// make sure the cursor is in the client area, because the mainframe also
// wants these messages to provide tooltips for the toolbar
CPoint sCursorPoint;
VERIFY (::GetCursorPos (&sCursorPoint));
ScreenToClient (&sCursorPoint);
CRect sClientRect;
GetClientRect (&sClientRect);
if (sClientRect.PtInRect (sCursorPoint))
{
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *) pNMHdr;
pTTT->lpszText = (LPTSTR)(LPCTSTR) m_strToolTip;
return TRUE;
}
return FALSE;
}
// -------------------------------------------------------------------------
void CNewsView::HandleToolTips (CPoint &point)
{
static bool fDisplayed = false;
static int iDisplayedIndex;
if (!::IsWindow (m_sToolTips.m_hWnd))
return;
// get index of item under mouse
int iIndex = GetListCtrl().HitTest ( point );
if (fDisplayed)
{
if (iIndex != iDisplayedIndex)
{
m_sToolTips.Activate (FALSE);
m_strToolTip.Empty();
fDisplayed = false;
}
}
if (!fDisplayed && iIndex >= 0)
{
try
{
TServerCountedPtr cpNewsServer;
TNewsGroup * pNG = 0;
BOOL fUseLock;
LONG gid = LONG(GetListCtrl().GetItemData (iIndex));
TNewsGroupUseLock useLock(cpNewsServer, gid, &fUseLock, pNG);
if (fUseLock)
{
int nNewHdrs, nServer, nTotalHdrs;
pNG->FormatNewArticles ( nNewHdrs, nServer, nTotalHdrs );
m_strToolTip.Format ("%s\nLocal Unread: %d\nLocal Total: %d\nServer: %d",
GetListCtrl().GetItemText (iIndex, 0),
nNewHdrs, nTotalHdrs, nServer );
}
else
m_strToolTip = GetListCtrl().GetItemText (iIndex, 0);
}
catch(...)
{
m_strToolTip.Empty();
}
m_sToolTips.Activate (TRUE);
iDisplayedIndex = iIndex;
fDisplayed = true;
}
}
// -------------------------------------------------------------------------
void CNewsView::start_selchange_timer ()
{
stop_selchange_timer ();
m_hSelchangeTimer = SetTimer (CNewsView::idSelchangeTimer, 333, NULL);
}
// -------------------------------------------------------------------------
void CNewsView::stop_selchange_timer ()
{
// kill any timer currently running
if (m_hSelchangeTimer)
KillTimer (m_hSelchangeTimer);
m_hSelchangeTimer = 0;
}
// -------------------------------------------------------------------------
int CNewsView::GetPreferredFilter (TNewsGroup * pNG)
{
int iWhatFilter = pNG->GetFilterID();
if (0 == iWhatFilter)
{
TAllViewFilter * pAllFilters = gpStore->GetAllViewFilters();
iWhatFilter = pAllFilters->GetGlobalDefFilterID();
}
return iWhatFilter;
}
| 28.222278 | 152 | 0.61866 | taviso |
f98a0cdf5f2a3eee6a87ac19dbb2e18e2198ddcd | 1,283 | cpp | C++ | Tree/BalancedTree/BalancedTree.cpp | PrachieNaik/DSA | 083522bb3c8a0694adec1f2856d4d4cd0fb51722 | [
"MIT"
] | null | null | null | Tree/BalancedTree/BalancedTree.cpp | PrachieNaik/DSA | 083522bb3c8a0694adec1f2856d4d4cd0fb51722 | [
"MIT"
] | null | null | null | Tree/BalancedTree/BalancedTree.cpp | PrachieNaik/DSA | 083522bb3c8a0694adec1f2856d4d4cd0fb51722 | [
"MIT"
] | null | null | null | /*
Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is
not more than one for all nodes of tree.
Constraints:
1<= N <= 10^4
Approach: To check if a tree is height-balanced, get the height of left and right subtrees. Return true if difference between heights is not more than 1 and left
and right subtrees are balanced, otherwise return false. Calculate the height in the same recursion rather than calling a height() function separately.
Time complexity – O(n)
*/
bool isBalancedUtil(Node *root, int *height) {
int leftHeight = 0, rightHeight = 0;
bool leftBalanced = 0, rightBalanced = 0;
if(root == NULL)
{
*height = 0;
return 1;
}
leftBalanced = isBalancedUtil(root->left, &leftHeight);
rightBalanced = isBalancedUtil(root->right, &rightHeight);
*height = max(leftHeight,rightHeight) + 1;
if( abs(leftHeight - rightHeight) >= 2 || !leftBalanced || !rightBalanced)
return 0;
return 1;
}
// This function should return tree if passed tree
// is balanced, else false.
bool isBalanced(Node *root)
{
int height = 0;
return isBalancedUtil(root,&height);
}
| 27.891304 | 163 | 0.681216 | PrachieNaik |
f98b56f403871a3056dd8284deee2b49b92ca23d | 4,718 | cpp | C++ | src/model_loading/model.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | src/model_loading/model.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | src/model_loading/model.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | //
// model.cpp
//
// Created by Clsrfish on 08/10/2020
//
#include "./model.h"
#include "../gl/gl_utils.h"
model_loading::Model::Model(const std::string &modelPath)
{
loadModel(modelPath);
}
void model_loading::Model::Draw(const Shader &shader)
{
for (unsigned int i = 0; i < Meshes.size(); i++)
{
Meshes[i].Draw(shader);
}
}
void model_loading::Model::loadModel(const std::string &modelPath)
{
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(modelPath.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs);
if (scene == nullptr || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || scene->mRootNode == nullptr)
{
LOG_E("ASSMIP::%s", importer.GetErrorString());
return;
}
directory = modelPath.substr(0, modelPath.find_last_of('/'));
processNode(scene->mRootNode, scene);
}
void model_loading::Model::processNode(aiNode *node, const aiScene *scene)
{
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
Meshes.push_back(processMesh(mesh, scene));
}
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
processNode(node->mChildren[i], scene);
}
}
model_loading::Mesh model_loading::Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex;
glm::vec3 pos;
pos.x = mesh->mVertices[i].x;
pos.y = mesh->mVertices[i].y;
pos.z = mesh->mVertices[i].z;
vertex.Position = pos;
glm::vec3 normal;
normal.x = mesh->mNormals[i].x;
normal.y = mesh->mNormals[i].y;
normal.z = mesh->mNormals[i].z;
vertex.Normal = normal;
if (mesh->mTextureCoords[0])
{
glm::vec2 texCoord;
texCoord.x = mesh->mTextureCoords[0][i].x;
texCoord.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = texCoord;
}
else
{
vertex.TexCoords = glm::vec2(0.0f, 0.0f);
}
vertices.push_back(vertex);
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j]);
}
}
if (mesh->mMaterialIndex >= 0)
{
// process all materials
aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
// 1. diffuse maps
std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "u_TextureDiffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. specular maps
std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "u_TextureSpecular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
// 3. normal maps
std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_NORMALS, "u_TextureNormal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
// 4. height maps
std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "u_TextureHeight");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
}
return model_loading::Mesh(vertices, indices, textures);
}
std::vector<model_loading::Texture> model_loading::Model::loadMaterialTextures(aiMaterial *material, aiTextureType texType, const std::string &typeName)
{
std::vector<model_loading::Texture> textures;
for (unsigned int i = 0; i < material->GetTextureCount(texType); ++i)
{
aiString str;
material->GetTexture(texType, i, &str);
auto file = std::string(str.C_Str());
bool useCache = false;
for (unsigned int j = 0; j < loadedTextures.size(); j++)
{
if (file.compare(loadedTextures[j].path) == 0)
{
LOG_I("Texture loaded preciously: %s", file.c_str());
textures.push_back(loadedTextures[j]);
useCache = true;
break;
}
}
if (!useCache)
{
model_loading::Texture texture;
texture.id = TextureFromFile(file, directory);
texture.type = typeName;
texture.path = file;
textures.push_back(texture);
loadedTextures.push_back(texture);
}
}
return textures;
}
| 31.453333 | 152 | 0.602798 | clsrfish |
f98fc6fe889504295cefaf5aa7436bc071f81e98 | 7,042 | hpp | C++ | src/Utilities/NMatrix/NLine.hpp | fcaillaud/SARAH | ca79c7d9449cf07eec9d5cc13293ec0c128defc1 | [
"MIT"
] | null | null | null | src/Utilities/NMatrix/NLine.hpp | fcaillaud/SARAH | ca79c7d9449cf07eec9d5cc13293ec0c128defc1 | [
"MIT"
] | null | null | null | src/Utilities/NMatrix/NLine.hpp | fcaillaud/SARAH | ca79c7d9449cf07eec9d5cc13293ec0c128defc1 | [
"MIT"
] | null | null | null | /**
* \file NLine.hpp
* \author fcaillaud
* \version 1.0
* \date 2 Avril 2014
* \brief Fichier décrivant la classe NLine.
* \details Classe utilisée pour représenter une ligne ou colonne de matrice (plus ou moins un vecteur).
* \todo Réfléchir à une meilleure approche pour toute la classe.
*/
#ifndef NMATRIX_NLINE
#define NMATRIX_NLINE
#include <vector>
#include <stdlib.h>
/**
* \namespace alg
* \brief Nom de domaine tertiaire, partie utilitaire.
* \todo Migrer vers le namespace gu.
*/
namespace alg
{
/**
* \enum LineState
* \brief Type de vecteur, soit ligne, soit colonne.
*/
enum LineState
{
LS_ROW, /*!< Vecteur de type ligne. */
LS_COLUMN /*!< Vecteur de type colonne. */
};
/**
* \class NLine
* \brief Classe représentant un vecteur de matrice (soit ligne, soit colonne).
* \details Classe template avec le type Mtype qui sera le type des valeurs contenues dans le vecteur.
*/
template<class MType = double>
class NLine
{
public:
/**
* Constructeur par défaut.
* \details Construit un vecteur de taille 0.
*/
NLine():
mSize(),
mLine(),
mHasToBeAllDeleted(false)
{
//EMPTY
}
/**
* Constructeur paramétré.
* \param pSize La taille du vecteur voulu.
* \details Construit un vecteur de taille pSize.
*/
NLine(unsigned int pSize):
mSize(pSize),
mLine(new MType *[pSize]),
mHasToBeAllDeleted(true)
{
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = new MType();
}
/**
* Constructeur par copie.
* \param pLine Le vecteur à copier.
*/
NLine(const NLine & pLine):
mSize(pLine.mSize),
mLine(new MType *[pLine.mSize]),
mHasToBeAllDeleted(false)
{
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = pLine.mLine[i];
}
/**
* Constructeur par copie.
* \param pMatrixData La matrice cotenant le vecteur à copier.
* \param pInd L'indice de la ligne ou de la colonne dans la matrice.
* \param pSize Les dimensions de la matrice à copier.
* \param pLineState Le type de vecteur à copier (ligne ou colonne).
* \todo Enlever pSize, pas besoin, utiliser les dimensions de la matrice à copier.
*/
NLine(MType * pMatrixData, int pInd, std::pair<unsigned int, unsigned int> pSize, LineState pLineState):
mSize(),
mLine(),
mHasToBeAllDeleted(false)
{
if(pLineState == LS_ROW){
mSize = pSize.first;
mLine = new MType *[mSize];
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = pMatrixData + (pInd * pSize.first + i);
}else{
mSize = pSize.second;
mLine = new MType *[mSize];
for(unsigned int i = 0; i < mSize; ++i)
mLine[i] = pMatrixData + (i * pSize.first + pInd);
}
}
/**
* Destructeur
* \details Si mHasToBeAllDeleted est à false, il n'efface pas les pointeurs
* sur les valeurs stockées.
*/
~NLine()
{
if(mHasToBeAllDeleted)
for(unsigned int i = 0; i < mSize; ++i)
delete mLine[i];
delete [] mLine;
}
/**
* Récupération de la valeur à l'indice souhaité.
* \param pInd L'indice de la valeur à récupérer dans le vecteur.
* \return La valeur à l'indice pInd dans le vecteur.
*/
const MType GetAt(int pInd)
{
return *mLine[pInd];
}
/**
* Change la valeur à l'indice souhaité.
* \param pInd L'indice de la valeur à changer dans le vecteur.
* \param pData La nouvelle valeur.
*/
void SetAt(int pInd, MType pData)
{
*mLine[pInd] = pData;
}
/**
* Récupération de la valeur à l'indice souhaité.
* \param pInd L'indice de la valeur à récupérer dans le vecteur.
* \return La valeur à l'indice pInd dans le vecteur.
*/
MType operator[] (int pInd)
{
return *mLine[pInd];
}
/**
* Addition de deux vecteurs.
* \param pLine L'autre vecteur à additionner.
* \return Le vecteur résultant de l'addition.
* \details Additionne valeur par valeur.
*/
NLine operator+ (NLine pLine)
{
if(mSize != pLine.mSize){
std::cerr << "ERROR : In NLine +, the addition between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl;
exit(-1);
}
NLine<MType> vLine(mSize);
for(unsigned int i = 0; i < mSize; ++i)
*(vLine.mLine[i]) = *mLine[i] + pLine[i];
return vLine;
}
/**
* Soustraction de deux vecteurs.
* \param pLine Le vecteur que l'on soustrait.
* \return Le vecteur résultant de la soustraction.
* \details Soustrait valeur par valeur.
*/
NLine operator- (NLine pLine)
{
if(mSize != pLine.mSize){
std::cerr << "ERROR : In NLine -, the substraction between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl;
exit(-1);
}
NLine<MType> vLine(mSize);
for(unsigned int i = 0; i < mSize; ++i)
*(vLine.mLine[i]) = *mLine[i] - pLine[i];
return vLine;
}
/**
* Multiplication de deux vecteurs.
* \param pLine L'autre vecteur à multiplier.
* \return Le vecteur résultant de la multiplication.
* \details Multiplie valeur par valeur.
*/
double operator* (NLine pLine)
{
unsigned int vSize = pLine.mSize;
double vRes = 0.0;
if(mSize != vSize){
std::cerr << "ERROR : In NLine *, the substraction between two lines with different size (" << mSize << ", " << pLine.mSize << ") can't be done." << std::endl;
exit(-1);
}
for(unsigned int i = 0; i < vSize; ++i)
vRes += (*mLine[i]) * (*(pLine.mLine[i]));
return vRes;
}
/**
* Récupère la taille du vecteur.
* \return La taille du vecteur.
* \todo Changer le nom de la fonction pour GetSize(), plus cohérent.
*/
unsigned int Size()
{
return mSize;
}
/**
* Récupère le pointeur sur les éléments du vecteur.
* \return Le pointeur sur les éléments du vecteur.
*/
MType ** SData()
{
return mLine;
}
/**
* Ajout d'un pointeur sur valeur dans le vecteur.
* \param pData Le pointeur sur valeur à ajouter.
* \details Le vecteur s'agrandit et sa taille s'incrémente.
*/
void Add(MType * pData)
{
mSize++;
mLine = (MType *) realloc(mLine, mSize * sizeof(MType *));
mLine[mSize - 1] = pData;
}
/**
* Affichage du vecteur.
* \details Affiche sur la sortie standard les valeurs du vecteur.
* \todo Utiliser Msg (dans les autres fonction également) ET
* différencier l'affichage en colonne et en ligne.
*/
void Print()
{
for(unsigned int i = 0; i < mSize; ++i)
std::cout << *mLine[i] << " ";
}
private:
/**
* \brief Taille du vecteur.
*/
unsigned int mSize;
/**
* \brief Tableau des pointeurs sur les valeurs.
*/
MType ** mLine;
/**
* \brief État de suppression des pointeurs sur les valeurs.
*/
bool mHasToBeAllDeleted;
};
}
#endif
| 24.883392 | 164 | 0.598268 | fcaillaud |
f9950c4c127eed8eb765a4f79dff18707a5a927e | 1,141 | cpp | C++ | libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/charconv/src/charconv/fcppt_string_to_utf8_file.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/charconv/fcppt_string_to_utf8.hpp>
#include <sge/charconv/fcppt_string_to_utf8_file.hpp>
#include <sge/charconv/utf8_string.hpp>
#include <fcppt/string.hpp>
#include <fcppt/cast/size.hpp>
#include <fcppt/cast/to_char_ptr.hpp>
#include <fcppt/cast/to_signed.hpp>
#include <fcppt/config/external_begin.hpp>
#include <filesystem>
#include <fstream>
#include <ios>
#include <fcppt/config/external_end.hpp>
bool sge::charconv::fcppt_string_to_utf8_file(
fcppt::string const &_string, std::filesystem::path const &_path)
{
std::ofstream file(_path);
if (!file.is_open())
{
return false;
}
sge::charconv::utf8_string const result(sge::charconv::fcppt_string_to_utf8(_string));
return !file.write(
fcppt::cast::to_char_ptr<char const *>(result.c_str()),
fcppt::cast::size<std::streamsize>(fcppt::cast::to_signed(result.size())))
.fail();
}
| 31.694444 | 92 | 0.69851 | cpreh |
f9a02a599df97e56a3b57d258939f6fc32e01d64 | 610 | cpp | C++ | source/343.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/343.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/343.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 343.cpp
// LeetCode
//
// Created by Narikbi on 23.02.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
using namespace std;
int integerBreak(int n) {
vector <int> dp(n+1, 0);
dp[1] = 0;
for (int i = 2; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = max(dp[i], max(j, dp[j]) * max(i-j, dp[i-j]));
}
}
return dp[n];
}
| 16.052632 | 66 | 0.539344 | narikbi |
f9a62c668e2250f899b7b3e209bda4e68f8183bc | 2,605 | cpp | C++ | droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneArchitectureRvizInterfaceROSModule/src/source/swarmAgentInterface.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | #include "swarmAgentInterface.h"
#include "RvizInteractiveMarkerDisplay.h"
SwarmAgentInterface::SwarmAgentInterface(int idDrone_in)
{
idDrone = idDrone_in;
return;
}
SwarmAgentInterface::~SwarmAgentInterface()
{
return;
}
void SwarmAgentInterface::open(ros::NodeHandle &nIn)
{
n = nIn;
localizer_pose_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_POSE_SUBSCRIPTION, 1, &SwarmAgentInterface::localizerPoseCallback, this);
mission_planner_mission_point_reference_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_TRAJECTORY_ABS_REF_CMD_SUBSCRIPTION, 1, &SwarmAgentInterface::missionPointCallback, this);
trajectory_planner_trajectory_reference_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_TRAJECTORY_ABS_REF_CMD_SUBSCRIPTION, 1, &SwarmAgentInterface::trajectoryAbsRefCmdCallback, this);
obstacle_processor_obstacle_list_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_OBSTACLE_LIST_SUBSCRIPTION, 1, &SwarmAgentInterface::obstacleListCallback, this);
// this_drone_society_pose_subscriber = n.subscribe(std::string("/drone")+std::to_string(idDrone)+"/"+DRONE_ARCHITECTURE_RVIZ_INTERFACE_SOCIETY_POSE_SUBSCRIPTION, 1, &SwarmAgentInterface::societyPoseSubCallback, this);
return;
}
void SwarmAgentInterface::localizerPoseCallback(const droneMsgsROS::dronePose &pose_euler)
{
Drone.PoseCallback(pose_euler, idDrone);
}
void SwarmAgentInterface::missionPointCallback(const droneMsgsROS::dronePositionTrajectoryRefCommand &point)
{
if (idDrone == Drone.ActiveDroneId())
{
Drone.MissionPointPubCallback(point, idDrone);
}
}
void SwarmAgentInterface::trajectoryAbsRefCmdCallback(const droneMsgsROS::dronePositionTrajectoryRefCommand &trajectory)
{
if (idDrone == Drone.ActiveDroneId())
{
Drone.TrajectoryPubCallback(trajectory, idDrone);
}
}
void SwarmAgentInterface::obstacleListCallback(const droneMsgsROS::obstaclesTwoDim &obstacles)
{
//ROS_INFO("Drone ID %i", Drone.ActiveDroneId());
if (idDrone == Drone.ActiveDroneId())
{
Drone.ObstaclesPubCallback(obstacles, idDrone);
}
}
void SwarmAgentInterface::societyPoseSubCallback(const droneMsgsROS::societyPose::ConstPtr &msg)
{
//std::cout << "SwarmAgentInterface::societyPoseSubCallback drone:" << idDrone << std::endl;
}
| 30.290698 | 250 | 0.761996 | MorS25 |
f9a85337ac0427c6189842eb22ef8534aa49fb95 | 6,279 | cpp | C++ | MakeBuild/MakeBuild/CMakeFile.cpp | mooming/make_builder | e5aa68d4c922b3343cb032c0201126b9ed85ae37 | [
"MIT"
] | 1 | 2018-09-29T01:36:18.000Z | 2018-09-29T01:36:18.000Z | MakeBuild/MakeBuild/CMakeFile.cpp | mooming/make_builder | e5aa68d4c922b3343cb032c0201126b9ed85ae37 | [
"MIT"
] | null | null | null | MakeBuild/MakeBuild/CMakeFile.cpp | mooming/make_builder | e5aa68d4c922b3343cb032c0201126b9ed85ae37 | [
"MIT"
] | null | null | null | //
// CMakeFile.cpp
// mbuild
//
// Created by mooming on 2016. 8. 15..
//
//
#include "CMakeFile.h"
#include "StringUtil.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
using namespace Builder;
namespace
{
void AddFrameworks(ostream& os, string projName, const vector<string>& frameworks)
{
os << "if (APPLE)" << endl;
os << "include_directories ( /System/Library/Frameworks )" << endl;
os << "endif (APPLE)" << endl << endl;
if (!frameworks.empty())
{
for (const auto& element : frameworks)
{
if (Util::EqualsIgnoreCase(element, "opengl"))
{
os << "find_package (OpenGL)" << endl << endl;
os << "if (OPENGL_FOUND)" << endl;
os << "include_directories (${OPENGL_INCLUDE_DIR})" << endl;
os << "target_link_libraries (" << projName << " ${OPENGL_gl_LIBRARY})" << endl;
os << "endif (OPENGL_FOUND)" << endl << endl;
os << "if (OPENGL_GLU_FOUND)" << endl;
os << "target_link_libraries (" << projName << " ${OPENGL_glu_LIBRARY})" << endl;
os << "endif (OPENGL_GLU_FOUND)" << endl << endl;
}
else
{
string libName = element;
libName.append("_LIBRARY");
os << "find_library(" << libName << " " << element << ")" << endl << endl;
os << "if (" << libName << ")" << endl;
os << "target_link_libraries (" << projName << " ${" << libName << "})" << endl;
os << "endif (" << libName << ")" << endl << endl;
}
}
}
}
}
namespace CMake
{
CMakeFile::CMakeFile(const Build& build, const ProjectDir& targetDir)
: build(build), dir(targetDir)
{
}
void CMakeFile::Make()
{
const BuildType buildType = dir.GetBuildType();
const char* basePath = "${CMAKE_SOURCE_DIR}";
using namespace Util;
string filePath(dir.path);
string projName(PathToName(dir.path));
filePath.append("/CMakeLists.txt");
cout << "Creating: " << filePath.c_str() << "(" << BuildTypeStr(buildType) << ")" << endl;
ofstream ofs (filePath.c_str(), ofstream::out);
ofs << "cmake_minimum_required (VERSION 2.6)" << endl;
ofs << "project (" << projName << ")" << endl;
ofs << endl;
ofs << "if(CMAKE_COMPILER_IS_GNUCXX)" << endl;
ofs << " set(CMAKE_CXX_FLAGS \"${ CMAKE_CXX_FLAGS } -Wall -Werror\")" << endl;
ofs << "endif(CMAKE_COMPILER_IS_GNUCXX)" << endl;
auto& definesList = dir.DefinitionsList();
if (!definesList.empty())
{
ofs << "add_definitions (";
for (auto& def : definesList)
{
ofs << def << " ";
}
ofs << ")" << endl;
}
ofs << endl;
ofs << "include_directories (";
ofs << " " << basePath << endl;
ofs << " " << basePath << "/include" << endl;
for (const auto& element : build.includeDirs)
{
ofs << " " << TranslatePath(element) << endl;
}
ofs << " )" << endl;
ofs << endl;
if (buildType != HEADER_ONLY)
{
ofs << "link_directories (" << basePath << "/lib)" << endl;
ofs << endl;
}
ofs << endl;
for (const auto& subDir : dir.ProjDirList())
{
if (!subDir.SrcFileList().empty())
{
ofs << "add_subdirectory (" << PathToName(subDir.path.c_str()) << ")" << endl;
}
}
ofs << endl;
switch(buildType)
{
case EXECUTABLE:
ofs << "add_executable (" << projName.c_str() << endl;
for (const auto& element : dir.SrcFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl << endl;
AddFrameworks(ofs, projName, dir.FrameworkList());
ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/bin)" << endl;
break;
case STATIC_LIBRARY:
ofs << "add_library (" << projName.c_str() << " STATIC " << endl;
for (const auto& element : dir.SrcFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl << endl;
AddFrameworks(ofs, projName, dir.FrameworkList());
ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/lib)" << endl;
break;
case SHARED_LIBRARY:
ofs << "add_library (" << projName.c_str() << " SHARED " << endl;
for (const auto& element : dir.SrcFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl << endl;
AddFrameworks(ofs, projName, dir.FrameworkList());
ofs << "install (TARGETS " << projName << " DESTINATION " << basePath << "/bin)" << endl;
break;
case HEADER_ONLY:
ofs << "add_library (" << projName.c_str() << " INTERFACE)" << endl;
ofs << "target_sources (" << projName.c_str() << " INTERFACE " << endl;
for (const auto& element : dir.HeaderFileList())
{
ofs << " " << PathToName(element.path.c_str()) << endl;
}
ofs << ")" << endl;
break;
default:
break;
};
ofs << endl << endl;
auto& dependencyList = dir.DependencyList();
auto& libList = dir.LibraryList();
if (!dependencyList.empty() || !libList.empty())
{
ofs << "target_link_libraries (" << projName;
for (const auto& dependency : dependencyList)
{
if (dependency.empty())
continue;
ofs << " " << dependency;
}
for (const auto& library : libList)
{
if (library.empty())
continue;
ofs << " " << library;
}
ofs << ")" << endl << endl;
for (const auto& dependency : dependencyList)
{
if (dependency.empty())
continue;
ofs << "add_dependencies (" << projName.c_str() << " " << dependency << ")" << endl;
}
ofs << endl;
}
ofs << endl;
ofs.close();
}
string CMakeFile::TranslatePath(string path)
{
using namespace Util;
path = TrimPath(path);
if (StartsWithIgnoreCase(path, build.baseDir.path))
{
string newPath = string("${CMAKE_SOURCE_DIR}");
newPath.append(path.substr(build.baseDir.path.length()));
return newPath;
}
return path;
}
}
| 23.965649 | 93 | 0.563306 | mooming |
e2fffc29f48d61bbb1fd0392d17ef7142a1b37af | 3,606 | hh | C++ | include/maxscale/response_distribution.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | include/maxscale/response_distribution.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | include/maxscale/response_distribution.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2021 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-12-13
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxscale/ccdefs.hh>
#include <maxbase/stopwatch.hh>
#include <map>
using namespace std::chrono_literals;
namespace maxscale
{
/**
* Distribution of queries into buckets of response time, similar to
* the Query Response Time Plugin in mariadb.
* https://mariadb.com/kb/en/query-response-time-plugin/
*
* From Query Response Time Plugin documentation:
* The user can define time intervals that divide the range 0 to positive infinity into smaller
* intervals and then collect the number of commands whose execution times fall into each of
* those intervals.
* Each interval is described as:
* (range_base ^ n; range_base ^ (n+1)]
*
* SELECT * FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME;
* +----------------+-------+----------------+
* | TIME | COUNT | TOTAL |
* +----------------+-------+----------------+
* | 0.000001 | 0 | 0.000000 |
* | 0.000010 | 17 | 0.000094 |
* | 0.000100 | 4301 0.236555 |
* | 0.001000 | 1499 | 0.824450 |
* | 0.010000 | 14851 | 81.680502 |
* | 0.100000 | 8066 | 443.635693 |
* | 1.000000 | 0 | 0.000000 |
* | 10.000000 | 0 | 0.000000 |
* | 100.000000 | 1 | 55.937094 |
* | 1000.000000 | 0 | 0.000000 |
* | 10000.000000 | 0 | 0.000000 |
* | 100000.000000 | 0 | 0.000000 |
* | 1000000.000000 | 0 | 0.000000 |
* | TOO LONG | 0 | TOO LONG |
* +----------------+-------+----------------+
*
* This class tallies the response times added to it maintaining
* a vector of the results.
*
* The limits are rounded to microseconds (a bit differently than the plugin).
* The first limit is >= 1us, depends on the given range_base.
* The last limit < 10'000'000 (1M for range_base=10, 11.6 days). In the server
* the last limit is followed by a "TOO LONG" entry. There is no too-long entry
* in class ResponseDistribution (not needed, can't convert to consistent json).
*/
class ResponseDistribution
{
public:
/**
* @brief ResponseDistribution
* @param range_base - minimum 2
*/
ResponseDistribution(int range_base = 10);
struct Element
{
// These are all "atomic" sizes (64 bits).
mxb::Duration limit; // upper limit for a bucket
int64_t count;
mxb::Duration total;
};
int range_base() const;
void add(mxb::Duration dur);
const std::vector<Element>& get() const;
// Get an initial copy for summing up using operator+=
ResponseDistribution with_stats_reset() const;
ResponseDistribution& operator+(const ResponseDistribution& rhs);
ResponseDistribution& operator+=(const ResponseDistribution& rhs);
private:
int m_range_base;
// initialized in the constructor after which
// the underlying array (size) remains unchanged
std::vector<Element> m_elements;
};
inline void ResponseDistribution::add(mxb::Duration dur)
{
for (auto& element : m_elements)
{
if (dur <= element.limit)
{
++element.count;
element.total += dur;
break;
}
}
}
}
| 31.356522 | 95 | 0.602329 | sdrik |
390abeb5824edd87d529070e13d838c0c2467c31 | 17,059 | cpp | C++ | engine/src/ph/util/GltfLoader.cpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/src/ph/util/GltfLoader.cpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/src/ph/util/GltfLoader.cpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "ph/util/GltfLoader.hpp"
#include <sfz/Logging.hpp>
#include <sfz/strings/StackString.hpp>
#define TINYGLTF_NOEXCEPTION
#define JSON_NOEXCEPTION
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include <sfz/PushWarnings.hpp>
#include "tiny_gltf.h"
#include <sfz/PopWarnings.hpp>
#include <sfz/Assert.hpp>
#include <ph/Context.hpp>
namespace ph {
using sfz::str320;
using sfz::vec2;
using sfz::vec3;
using sfz::vec3_u8;
using sfz::vec4;
using sfz::vec4_u8;
// Statics
// ------------------------------------------------------------------------------------------------
static bool dummyLoadImageDataFunction(
tinygltf::Image*, const int, std::string*, std::string*, int, int, const unsigned char*, int, void*)
{
return true;
}
static str320 calculateBasePath(const char* path) noexcept
{
str320 str("%s", path);
// Go through path until the path separator is found
bool success = false;
for (uint32_t i = str.size() - 1; i > 0; i--) {
const char c = str.str[i - 1];
if (c == '\\' || c == '/') {
str.str[i] = '\0';
success = true;
break;
}
}
// If no path separator is found, assume we have no base path
if (!success) str.printf("");
return str;
}
enum class ComponentType : uint32_t {
INT8 = 5120,
UINT8 = 5121,
INT16 = 5122,
UINT16 = 5123,
UINT32 = 5125,
FLOAT32 = 5126,
};
static uint32_t numBytes(ComponentType type)
{
switch (type) {
case ComponentType::INT8: return 1;
case ComponentType::UINT8: return 1;
case ComponentType::INT16: return 2;
case ComponentType::UINT16: return 2;
case ComponentType::UINT32: return 4;
case ComponentType::FLOAT32: return 4;
}
return 0;
}
enum class ComponentDimensions : uint32_t {
SCALAR = TINYGLTF_TYPE_SCALAR,
VEC2 = TINYGLTF_TYPE_VEC2,
VEC3 = TINYGLTF_TYPE_VEC3,
VEC4 = TINYGLTF_TYPE_VEC4,
MAT2 = TINYGLTF_TYPE_MAT2,
MAT3 = TINYGLTF_TYPE_MAT3,
MAT4 = TINYGLTF_TYPE_MAT4,
};
static uint32_t numDimensions(ComponentDimensions dims)
{
switch (dims) {
case ComponentDimensions::SCALAR: return 1;
case ComponentDimensions::VEC2: return 2;
case ComponentDimensions::VEC3: return 3;
case ComponentDimensions::VEC4: return 4;
case ComponentDimensions::MAT2: return 4;
case ComponentDimensions::MAT3: return 9;
case ComponentDimensions::MAT4: return 16;
}
return 0;
}
struct DataAccess final {
const uint8_t* rawPtr = nullptr;
uint32_t numElements = 0;
ComponentType compType = ComponentType::UINT8;
ComponentDimensions compDims = ComponentDimensions::SCALAR;
template<typename T>
const T& at(uint32_t index) const noexcept
{
return reinterpret_cast<const T*>(rawPtr)[index];
}
};
static DataAccess accessData(
const tinygltf::Model& model, int accessorIdx) noexcept
{
// Access Accessor
if (accessorIdx < 0) return DataAccess();
if (accessorIdx >= int32_t(model.accessors.size())) return DataAccess();
const tinygltf::Accessor& accessor = model.accessors[accessorIdx];
// Access BufferView
if (accessor.bufferView < 0) return DataAccess();
if (accessor.bufferView >= int32_t(model.bufferViews.size())) return DataAccess();
const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView];
// Access Buffer
if (bufferView.buffer < 0) return DataAccess();
if (bufferView.buffer >= int32_t(model.buffers.size())) return DataAccess();
const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer];
// Fill DataAccess struct
DataAccess tmp;
tmp.rawPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset];
tmp.numElements = uint32_t(accessor.count);
tmp.compType = ComponentType(accessor.componentType);
tmp.compDims = ComponentDimensions(accessor.type);
// For now we require that that there is no padding between elements in buffer
sfz_assert_hard(
bufferView.byteStride == 0 ||
bufferView.byteStride == size_t(numDimensions(tmp.compDims) * numBytes(tmp.compType)));
return tmp;
}
static DataAccess accessData(
const tinygltf::Model& model, const tinygltf::Primitive& primitive, const char* type) noexcept
{
const auto& itr = primitive.attributes.find(type);
if (itr == primitive.attributes.end()) return DataAccess();
return accessData(model, itr->second);
}
static uint8_t toU8(float val) noexcept
{
return uint8_t(std::roundf(val * 255.0f));
}
static vec4_u8 toSfz(const tinygltf::ColorValue& val) noexcept
{
vec4_u8 tmp;
tmp.x = toU8(float(val[0]));
tmp.y = toU8(float(val[1]));
tmp.z = toU8(float(val[2]));
tmp.w = toU8(float(val[3]));
return tmp;
}
static bool extractAssets(
const char* basePath,
const tinygltf::Model& model,
Mesh& meshOut,
DynArray<ImageAndPath>& texturesOut,
bool (*checkIfTextureIsLoaded)(StringID id, void* userPtr),
void* userPtr,
sfz::Allocator* allocator) noexcept
{
StringCollection& resStrings = getResourceStrings();
// Load textures
texturesOut.init(uint32_t(model.textures.size()), allocator, sfz_dbg(""));
for (uint32_t i = 0; i < model.textures.size(); i++) {
const tinygltf::Texture& tex = model.textures[i];
if (tex.source < 0 || int(model.images.size()) <= tex.source) {
SFZ_ERROR("tinygltf", "Bad texture source: %i", tex.source);
return false;
}
const tinygltf::Image& img = model.images[tex.source];
// Create global path (path relative to game executable)
const str320 globalPath("%s%s", basePath, img.uri.c_str());
StringID globalPathId = resStrings.getStringID(globalPath.str);
// Check if texture is already loaded, skip it if it is
if (checkIfTextureIsLoaded != nullptr) {
if (checkIfTextureIsLoaded(globalPathId, userPtr)) continue;
}
// Load and store image
ImageAndPath pack;
pack.globalPathId = globalPathId;
pack.image = loadImage("", globalPath);
if (pack.image.rawData.data() == nullptr) {
SFZ_ERROR("tinygltf", "Could not load texture: \"%s\"", globalPath.str);
return false;
}
texturesOut.add(std::move(pack));
// TODO: We need to store these two values somewhere. Likely in material (because it does
// not make perfect sense that everything should access the texture the same way)
//const tinygltf::Sampler& sampler = model.samplers[tex.sampler];
//int wrapS = sampler.wrapS; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default "REPEAT"
//int wrapT = sampler.wrapT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default "REPEAT"
}
// Lambda for getting the StringID from a material
auto getStringID = [&](int texIndex) -> StringID {
const tinygltf::Texture& tex = model.textures[texIndex];
const tinygltf::Image& img = model.images[tex.source];
str320 globalPath("%s%s", basePath, img.uri.c_str());
StringID globalPathId = resStrings.getStringID(globalPath.str);
return globalPathId;
};
// Load materials
meshOut.materials.init(uint32_t(model.materials.size()), allocator, sfz_dbg(""));
for (uint32_t i = 0; i < model.materials.size(); i++) {
const tinygltf::Material& material = model.materials[i];
Material phMat;
// Lambda for checking if parameter exists
auto hasParamValues = [&](const char* key) {
return material.values.find(key) != material.values.end();
};
auto hasParamAdditionalValues = [&](const char* key) {
return material.additionalValues.find(key) != material.additionalValues.end();
};
// Albedo value
if (hasParamValues("baseColorFactor")) {
const tinygltf::Parameter& param = material.values.find("baseColorFactor")->second;
tinygltf::ColorValue color = param.ColorFactor();
phMat.albedo = toSfz(color);
}
// Albedo texture
if (hasParamValues("baseColorTexture")) {
const tinygltf::Parameter& param = material.values.find("baseColorTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.albedoTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Roughness Value
if (hasParamValues("roughnessFactor")) {
const tinygltf::Parameter& param = material.values.find("roughnessFactor")->second;
phMat.roughness = toU8(float(param.Factor()));
}
// Metallic Value
if (hasParamValues("metallicFactor")) {
const tinygltf::Parameter& param = material.values.find("metallicFactor")->second;
phMat.metallic = toU8(float(param.Factor()));
}
// Emissive value
if (hasParamAdditionalValues("emissiveFactor")) {
const tinygltf::Parameter& param = material.additionalValues.find("emissiveFactor")->second;
phMat.emissive.x = float(param.ColorFactor()[0]);
phMat.emissive.y = float(param.ColorFactor()[1]);
phMat.emissive.z = float(param.ColorFactor()[2]);
}
// Roughness and Metallic texture
if (hasParamValues("metallicRoughnessTexture")) {
const tinygltf::Parameter& param = material.values.find("metallicRoughnessTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.metallicRoughnessTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Normal texture
if (hasParamAdditionalValues("normalTexture")) {
const tinygltf::Parameter& param = material.additionalValues.find("normalTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.normalTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Occlusion texture
if (hasParamAdditionalValues("occlusionTexture")) {
const tinygltf::Parameter& param = material.additionalValues.find("occlusionTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.occlusionTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Emissive texture
if (hasParamAdditionalValues("emissiveTexture")) {
const tinygltf::Parameter& param = material.additionalValues.find("emissiveTexture")->second;
int texIndex = param.TextureIndex();
if (texIndex < 0 || int(model.textures.size()) <= texIndex) {
SFZ_ERROR("tinygltf", "Bad texture index for material %u", i);
continue;
}
phMat.emissiveTex = getStringID(texIndex);
// TODO: Store which texcoords to use
}
// Remove default emissive factor if no emissive is specified
if (phMat.emissiveTex == StringID::invalid() && !hasParamAdditionalValues("emissiveFactor")) {
phMat.emissive = vec3(0.0f);
}
// Add material to assets
meshOut.materials.add(phMat);
}
// Add single default material if no materials
if (meshOut.materials.size() == 0) {
ph::Material defaultMaterial;
defaultMaterial.emissive = vec3(1.0, 0.0, 0.0);
meshOut.materials.add(defaultMaterial);
}
// Add meshes
uint32_t numVertexGuess = uint32_t(model.meshes.size()) * 256;
meshOut.vertices.init(numVertexGuess, allocator, sfz_dbg(""));
meshOut.indices.init(numVertexGuess * 2, allocator, sfz_dbg(""));
meshOut.components.init(uint32_t(model.meshes.size()), allocator, sfz_dbg(""));
for (uint32_t i = 0; i < uint32_t(model.meshes.size()); i++) {
const tinygltf::Mesh& mesh = model.meshes[i];
MeshComponent phMeshComp;
// TODO: For now, stupidly assume each mesh only have one primitive
const tinygltf::Primitive& primitive = mesh.primitives[0];
// Mode can be:
// TINYGLTF_MODE_POINTS (0)
// TINYGLTF_MODE_LINE (1)
// TINYGLTF_MODE_LINE_LOOP (2)
// TINYGLTF_MODE_TRIANGLES (4)
// TINYGLTF_MODE_TRIANGLE_STRIP (5)
// TINYGLTF_MODE_TRIANGLE_FAN (6)
sfz_assert_hard(primitive.mode == TINYGLTF_MODE_TRIANGLES);
sfz_assert_hard(
primitive.indices >= 0 && primitive.indices < int(model.accessors.size()));
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
//
// Allowed attributes:
// POSITION, NORMAL, TANGENT, TEXCOORD_0, TEXCOORD_1, COLOR_0, JOINTS_0, WEIGHTS_0
//
// Stupidly assume positions, normals, and texcoord_0 exists
DataAccess posAccess = accessData(model, primitive, "POSITION");
sfz_assert_hard(posAccess.rawPtr != nullptr);
sfz_assert_hard(posAccess.compType == ComponentType::FLOAT32);
sfz_assert_hard(posAccess.compDims == ComponentDimensions::VEC3);
DataAccess normalAccess = accessData(model, primitive, "NORMAL");
sfz_assert_hard(normalAccess.rawPtr != nullptr);
sfz_assert_hard(normalAccess.compType == ComponentType::FLOAT32);
sfz_assert_hard(normalAccess.compDims == ComponentDimensions::VEC3);
DataAccess texcoord0Access = accessData(model, primitive, "TEXCOORD_0");
sfz_assert_hard(texcoord0Access.rawPtr != nullptr)
sfz_assert_hard(texcoord0Access.compType == ComponentType::FLOAT32);
sfz_assert_hard(texcoord0Access.compDims == ComponentDimensions::VEC2);
// Assume texcoord_1 does NOT exist
DataAccess texcoord1Access = accessData(model, primitive, "TEXCOORD_1");
sfz_assert_hard(texcoord1Access.rawPtr == nullptr);
// Create vertices from positions and normals
// TODO: Texcoords
sfz_assert_hard(posAccess.numElements == normalAccess.numElements);
uint32_t compVertexOffset = meshOut.vertices.size();
for (uint32_t j = 0; j < posAccess.numElements; j++) {
Vertex vertex;
vertex.pos = posAccess.at<vec3>(j);
vertex.normal = normalAccess.at<vec3>(j);
vertex.texcoord = texcoord0Access.at<vec2>(j);
meshOut.vertices.add(vertex);
}
// Create indices
DataAccess idxAccess = accessData(model, primitive.indices);
sfz_assert_hard(idxAccess.rawPtr != nullptr);
sfz_assert_hard(idxAccess.compDims == ComponentDimensions::SCALAR);
phMeshComp.firstIndex = meshOut.indices.size();
phMeshComp.numIndices = idxAccess.numElements;
if (idxAccess.compType == ComponentType::UINT32) {
for (uint32_t j = 0; j < idxAccess.numElements; j++) {
meshOut.indices.add(compVertexOffset + idxAccess.at<uint32_t>(j));
}
}
else if (idxAccess.compType == ComponentType::UINT16) {
for (uint32_t j = 0; j < idxAccess.numElements; j++) {
meshOut.indices.add(compVertexOffset + uint32_t(idxAccess.at<uint16_t>(j)));
}
}
else {
sfz_assert_hard(false);
}
// Material
uint32_t materialIdx = primitive.material < 0 ? 0 : primitive.material;
sfz_assert_hard(materialIdx < meshOut.materials.size());
phMeshComp.materialIdx = materialIdx;
// Add component to mesh
meshOut.components.add(phMeshComp);
}
return true;
}
// Function for loading from gltf
// ------------------------------------------------------------------------------------------------
bool loadAssetsFromGltf(
const char* gltfPath,
Mesh& meshOut,
DynArray<ImageAndPath>& texturesOut,
sfz::Allocator* allocator,
bool (*checkIfTextureIsLoaded)(StringID id, void* userPtr),
void* userPtr) noexcept
{
str320 basePath = calculateBasePath(gltfPath);
// Initializing loader with dummy image loader function
tinygltf::TinyGLTF loader;
loader.SetImageLoader(dummyLoadImageDataFunction, nullptr);
// Read model from file
tinygltf::Model model;
std::string error;
std::string warnings;
bool result = loader.LoadASCIIFromFile(&model, &error, &warnings, gltfPath);
// Check error string
if (!warnings.empty()) {
SFZ_WARNING("tinygltf", "Warnings loading \"%s\": %s", gltfPath, warnings.c_str());
}
if (!error.empty()) {
SFZ_ERROR("tinygltf", "Error loading \"%s\": %s", gltfPath, error.c_str());
return false;
}
// Check return code
if (!result) {
SFZ_ERROR("tinygltf", "Error loading \"%s\"", gltfPath);
return false;
}
// Log that model was succesfully loaded
SFZ_INFO_NOISY("tinygltf", "Model \"%s\" loaded succesfully", gltfPath);
// Extract assets from results
bool extractSuccess = extractAssets(
basePath.str, model, meshOut, texturesOut, checkIfTextureIsLoaded, userPtr, allocator);
if (!extractSuccess) {
SFZ_ERROR("tinygltf", "Failed to create ph::Mesh from gltf: \"%s\"", gltfPath);
return false;
}
return true;
}
} // namespace ph
| 33.318359 | 101 | 0.712762 | PetorSFZ |
390ff228cd4db2d07d9236a1271bdac3a64c1706 | 4,848 | cpp | C++ | src/loaders/PE.cpp | LucasDblt/QBDL | fc873087740f10ac56c023cad8b1c8ca42aa8d28 | [
"Apache-2.0"
] | 52 | 2021-05-21T20:17:13.000Z | 2022-03-26T11:08:44.000Z | src/loaders/PE.cpp | LucasDblt/QBDL | fc873087740f10ac56c023cad8b1c8ca42aa8d28 | [
"Apache-2.0"
] | 2 | 2021-06-06T09:32:09.000Z | 2021-09-03T10:25:19.000Z | src/loaders/PE.cpp | LucasDblt/QBDL | fc873087740f10ac56c023cad8b1c8ca42aa8d28 | [
"Apache-2.0"
] | 7 | 2021-05-22T02:17:20.000Z | 2022-01-25T16:21:07.000Z | #include "logging.hpp"
#include <LIEF/PE.hpp>
#include <QBDL/Engine.hpp>
#include <QBDL/arch.hpp>
#include <QBDL/loaders/PE.hpp>
#include <QBDL/utils.hpp>
using namespace LIEF::PE;
namespace QBDL::Loaders {
std::unique_ptr<PE> PE::from_file(const char *path, TargetSystem &engines,
BIND binding) {
Logger::info("Loading {}", path);
if (!is_pe(path)) {
Logger::err("{} is not an PE file", path);
return {};
}
std::unique_ptr<Binary> bin = Parser::parse(path);
if (bin == nullptr) {
Logger::err("Can't parse {}", path);
return {};
}
return from_binary(std::move(bin), engines, binding);
}
std::unique_ptr<PE> PE::from_binary(std::unique_ptr<Binary> bin,
TargetSystem &engines, BIND binding) {
if (!engines.supports(*bin)) {
return {};
}
std::unique_ptr<PE> loader(new PE{std::move(bin), engines});
loader->load(binding);
return loader;
}
PE::PE(std::unique_ptr<Binary> bin, TargetSystem &engines)
: Loader::Loader(engines), bin_{std::move(bin)} {}
uint64_t PE::get_address(const std::string &sym) const {
const Binary &binary = get_binary();
const LIEF::Symbol *symbol = nullptr;
if (binary.has_symbol(sym)) {
symbol = &binary.get_symbol(sym);
}
if (symbol == nullptr) {
return 0;
}
return base_address_ + get_rva(binary, symbol->value());
}
uint64_t PE::get_address(uint64_t offset) const {
return base_address_ + offset;
}
uint64_t PE::entrypoint() const {
const Binary &binary = get_binary();
return base_address_ +
(binary.entrypoint() - binary.optional_header().imagebase());
}
void PE::load(BIND binding) {
Binary &binary = get_binary();
const uint64_t imagebase = binary.optional_header().imagebase();
uint64_t virtual_size = binary.virtual_size();
virtual_size = page_align(virtual_size);
mem_size_ = virtual_size;
Logger::debug("Virtual size: 0x{:x}", virtual_size);
const uint64_t base_address_hint =
engine_->base_address_hint(imagebase, virtual_size);
const uint64_t base_address =
engine_->mem().mmap(base_address_hint, virtual_size);
if (base_address == 0 || base_address == -1ull) {
Logger::err("mmap() failed! Abort.");
return;
}
base_address_ = base_address;
// Map sections
// =======================================================
for (const Section §ion : binary.sections()) {
QBDL_DEBUG("Mapping: {:<10}: (0x{:06x} - 0x{:06x})", section.name(),
section.virtual_address(),
section.virtual_address() + section.virtual_size());
const uint64_t rva = section.virtual_address();
const std::vector<uint8_t> &content = section.content();
if (!content.empty()) {
engine_->mem().write(base_address_ + rva, content.data(), content.size());
}
}
// Perform relocations
// =======================================================
if (binary.has_relocations()) {
const Arch binarch = arch();
const uint64_t fixup = base_address_ - imagebase;
for (const Relocation &relocation : binary.relocations()) {
const uint64_t rva = relocation.virtual_address();
for (const RelocationEntry &entry : relocation.entries()) {
switch (entry.type()) {
case RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_DIR64: {
const uint64_t relocation_addr =
base_address_ + rva + entry.position();
const uint64_t value =
engine_->mem().read_ptr(binarch, relocation_addr);
engine_->mem().write_ptr(binarch, relocation_addr, value + fixup);
break;
}
default: {
QBDL_ERROR("PE relocation {} is not supported!",
to_string(entry.type()));
break;
}
}
}
}
}
// Perform symbol resolution
// =======================================================
// TODO(romain): Find a mechanism to support import by ordinal
if (binary.has_imports()) {
const Arch binarch = arch();
for (const Import &imp : binary.imports()) {
for (const ImportEntry &entry : imp.entries()) {
const uint64_t iat_addr = entry.iat_address();
QBDL_DEBUG("Resolving: {}:{} (0x{:x})", imp.name(), entry.name(),
iat_addr);
LIEF::Symbol sym{entry.name()};
const uintptr_t sym_addr = engine_->symlink(*this, sym);
// Write the value in the IAT:
engine_->mem().write_ptr(binarch, base_address_ + iat_addr, sym_addr);
}
}
}
}
Arch PE::arch() const { return Arch::from_bin(get_binary()); }
uint64_t PE::get_rva(const Binary &bin, uint64_t addr) const {
const uint64_t imagebase = bin.optional_header().imagebase();
if (addr >= imagebase) {
return addr - imagebase;
}
return addr;
}
PE::~PE() = default;
} // namespace QBDL::Loaders
| 31.277419 | 80 | 0.607673 | LucasDblt |
391258a61b2f516878fedbf96255bda38df9868f | 3,927 | cpp | C++ | qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** Copyright (C) 2011 www.hanxuantech.com. The Gix parts.
** Written by Easion <easion@hanxuantech.com>
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdesktopwidget.h"
#include <stdio.h>
#include <gi/gi.h>
QDesktopWidget::QDesktopWidget()
: QWidget(0, Qt::Desktop)
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::QDesktopWidget\n");
}
QDesktopWidget::~QDesktopWidget()
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::~QDesktopWidget\n");
}
void
QDesktopWidget::resizeEvent(QResizeEvent*)
{
fprintf(stderr, "Unimplemented: QDesktopWidget::resizeEvent\n");
}
const QRect QDesktopWidget::availableGeometry(int screen) const
{
int workarea[4];
int rv;
QRect workArea;
rv = gi_wm_get_workarea(workarea);
if (!rv)
{
workArea = QRect(workarea[0], workarea[1], workarea[2], workarea[3]);
}
else{
workArea = screenGeometry(0);
}
return workArea;//QRect(0,0,info.scr_width,info.scr_height);
}
const QRect QDesktopWidget::screenGeometry(int screen) const
{
gi_screen_info_t info;
gi_get_screen_info(&info);
return QRect(0,0,info.scr_width,info.scr_height);
}
int QDesktopWidget::screenNumber(const QWidget *widget) const
{
Q_UNUSED(widget);
//fprintf(stderr, "Reimplemented: QDesktopWidget::screenNumber(widget) \n");
return 0;
}
int QDesktopWidget::screenNumber(const QPoint &point) const
{
Q_UNUSED(point);
//fprintf(stderr, "Reimplemented: QDesktopWidget::screenNumber\n");
return 0;
}
bool QDesktopWidget::isVirtualDesktop() const
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::isVirtualDesktop\n");
return true;
}
int QDesktopWidget::primaryScreen() const
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::primaryScreen\n");
return 0;
}
int QDesktopWidget::numScreens() const
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::numScreens\n");
return 1;
}
QWidget *QDesktopWidget::screen(int /* screen */)
{
//fprintf(stderr, "Unimplemented: QDesktopWidget::screen\n");
// It seems that a Qt::WType_Desktop cannot be moved?
return this;
}
| 29.30597 | 77 | 0.718615 | easion |
3912b1cc54d2b24986c1b54851f0b0eb1ce44980 | 637 | cpp | C++ | Problems/codility/CyclicRotation/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/codility/CyclicRotation/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/codility/CyclicRotation/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
vector<int> solution(vector<int> &A, int K) {
const int size = A.size();
if(size != 0 && K % size != 0) {
vector<int> result(size);
for (int i = 0; i < size; i++) {
result[(i + K) % size] = A[i];
}
return result;
}
return A;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
#endif
int n,k;
cin >> n >> k;
vector<int> b(n);
for (int i = 0; i < n; i++)
cin >> b[i];
vector<int> a = solution(b, k);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
} | 18.735294 | 45 | 0.467818 | grand87 |
3915750d1eb18c97faa2696719710f45cb2ef94d | 916 | cpp | C++ | Codeforces/731A - Night at the Museum.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/731A - Night at the Museum.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/731A - Night at the Museum.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cctype>
#include <cmath>
#include <string>
using namespace std;
int get_minimum_distance(char src, char dest) {
int distance;
src = tolower(src);
dest = tolower(dest);
// if the distance between the pointed charecter and the destination charecter is greater than 13, then we want make our movement to the opposite side
if (abs(src - dest) > 13)
distance = 26 - abs(src - dest);
// else the distance is the differce between the source and the dest
else
distance = abs(src-dest);
return distance;
}
int main() {
string input;
cin >> input;
int minimum_rotations = get_minimum_distance('a', input.at(0));
char pointer = input.at(0);
for (int i = 0, j = 1; i < input.length() - 1; i++, j++)
minimum_rotations += get_minimum_distance(input.at(i), input.at(j));
cout << minimum_rotations << endl;
} | 26.171429 | 154 | 0.644105 | naimulcsx |
39186a85e96ca0f5d099d05e8241ea93483e058a | 5,307 | cpp | C++ | src/gui/pen.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | 1 | 2020-12-28T01:41:35.000Z | 2020-12-28T01:41:35.000Z | src/gui/pen.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | src/gui/pen.cpp | strandfield/yasl | d109eb3166184febfe48d1a2d1c96683c4a813f7 | [
"MIT"
] | null | null | null | // Copyright (C) 2018 Vincent Chambrin
// This file is part of the Yasl project
// For conditions of distribution and use, see copyright notice in LICENSE
#include "yasl/gui/pen.h"
#include "yasl/common/binding/class.h"
#include "yasl/common/binding/default_arguments.h"
#include "yasl/common/binding/namespace.h"
#include "yasl/common/genericvarianthandler.h"
#include "yasl/core/datastream.h"
#include "yasl/core/enums.h"
#include "yasl/gui/brush.h"
#include "yasl/gui/color.h"
#include "yasl/gui/pen.h"
#include <script/classbuilder.h>
static void register_pen_class(script::Namespace ns)
{
using namespace script;
Class pen = ns.newClass("Pen").setId(script::Type::QPen).get();
// QPen();
bind::default_constructor<QPen>(pen).create();
// QPen(Qt::PenStyle);
bind::constructor<QPen, Qt::PenStyle>(pen).create();
// QPen(const QColor &);
bind::constructor<QPen, const QColor &>(pen).create();
// QPen(const QBrush &, qreal, Qt::PenStyle = Qt::SolidLine, Qt::PenCapStyle = Qt::SquareCap, Qt::PenJoinStyle = Qt::BevelJoin);
bind::constructor<QPen, const QBrush &, qreal, Qt::PenStyle, Qt::PenCapStyle, Qt::PenJoinStyle>(pen)
.apply(bind::default_arguments(Qt::BevelJoin, Qt::SquareCap, Qt::SolidLine)).create();
// QPen(const QPen &);
bind::constructor<QPen, const QPen &>(pen).create();
// ~QPen();
bind::destructor<QPen>(pen).create();
// QPen & operator=(const QPen &);
bind::memop_assign<QPen, const QPen &>(pen);
// QPen(QPen &&);
bind::constructor<QPen, QPen &&>(pen).create();
// QPen & operator=(QPen &&);
bind::memop_assign<QPen, QPen &&>(pen);
// void swap(QPen &);
bind::void_member_function<QPen, QPen &, &QPen::swap>(pen, "swap").create();
// Qt::PenStyle style() const;
bind::member_function<QPen, Qt::PenStyle, &QPen::style>(pen, "style").create();
// void setStyle(Qt::PenStyle);
bind::void_member_function<QPen, Qt::PenStyle, &QPen::setStyle>(pen, "setStyle").create();
// QVector<qreal> dashPattern() const;
/// TODO: QVector<qreal> dashPattern() const;
// void setDashPattern(const QVector<qreal> &);
/// TODO: void setDashPattern(const QVector<qreal> &);
// qreal dashOffset() const;
bind::member_function<QPen, qreal, &QPen::dashOffset>(pen, "dashOffset").create();
// void setDashOffset(qreal);
bind::void_member_function<QPen, qreal, &QPen::setDashOffset>(pen, "setDashOffset").create();
// qreal miterLimit() const;
bind::member_function<QPen, qreal, &QPen::miterLimit>(pen, "miterLimit").create();
// void setMiterLimit(qreal);
bind::void_member_function<QPen, qreal, &QPen::setMiterLimit>(pen, "setMiterLimit").create();
// qreal widthF() const;
bind::member_function<QPen, qreal, &QPen::widthF>(pen, "widthF").create();
// void setWidthF(qreal);
bind::void_member_function<QPen, qreal, &QPen::setWidthF>(pen, "setWidthF").create();
// int width() const;
bind::member_function<QPen, int, &QPen::width>(pen, "width").create();
// void setWidth(int);
bind::void_member_function<QPen, int, &QPen::setWidth>(pen, "setWidth").create();
// QColor color() const;
bind::member_function<QPen, QColor, &QPen::color>(pen, "color").create();
// void setColor(const QColor &);
bind::void_member_function<QPen, const QColor &, &QPen::setColor>(pen, "setColor").create();
// QBrush brush() const;
bind::member_function<QPen, QBrush, &QPen::brush>(pen, "brush").create();
// void setBrush(const QBrush &);
bind::void_member_function<QPen, const QBrush &, &QPen::setBrush>(pen, "setBrush").create();
// bool isSolid() const;
bind::member_function<QPen, bool, &QPen::isSolid>(pen, "isSolid").create();
// Qt::PenCapStyle capStyle() const;
bind::member_function<QPen, Qt::PenCapStyle, &QPen::capStyle>(pen, "capStyle").create();
// void setCapStyle(Qt::PenCapStyle);
bind::void_member_function<QPen, Qt::PenCapStyle, &QPen::setCapStyle>(pen, "setCapStyle").create();
// Qt::PenJoinStyle joinStyle() const;
bind::member_function<QPen, Qt::PenJoinStyle, &QPen::joinStyle>(pen, "joinStyle").create();
// void setJoinStyle(Qt::PenJoinStyle);
bind::void_member_function<QPen, Qt::PenJoinStyle, &QPen::setJoinStyle>(pen, "setJoinStyle").create();
// bool isCosmetic() const;
bind::member_function<QPen, bool, &QPen::isCosmetic>(pen, "isCosmetic").create();
// void setCosmetic(bool);
bind::void_member_function<QPen, bool, &QPen::setCosmetic>(pen, "setCosmetic").create();
// bool operator==(const QPen &) const;
bind::memop_eq<QPen, const QPen &>(pen);
// bool operator!=(const QPen &) const;
bind::memop_neq<QPen, const QPen &>(pen);
// bool isDetached();
bind::member_function<QPen, bool, &QPen::isDetached>(pen, "isDetached").create();
// QPen::DataPtr & data_ptr();
/// TODO: QPen::DataPtr & data_ptr();
yasl::registerVariantHandler<yasl::GenericVariantHandler<QPen, QMetaType::QPen>>();
}
void register_pen_file(script::Namespace gui)
{
using namespace script;
Namespace ns = gui;
register_pen_class(ns);
// QDataStream & operator<<(QDataStream &, const QPen &);
bind::op_put_to<QDataStream &, const QPen &>(ns);
// QDataStream & operator>>(QDataStream &, QPen &);
bind::op_read_from<QDataStream &, QPen &>(ns);
// QDebug operator<<(QDebug, const QPen &);
/// TODO: QDebug operator<<(QDebug, const QPen &);
}
| 43.5 | 130 | 0.689278 | strandfield |
392427e59bed278479a35b3e6ff5951f21cb75ed | 2,802 | cpp | C++ | unit_tests/test_playable_moves.cpp | julienlopez/Aronda | 8fb6625bc037736dc2926f97f46a59441d7dc221 | [
"MIT"
] | null | null | null | unit_tests/test_playable_moves.cpp | julienlopez/Aronda | 8fb6625bc037736dc2926f97f46a59441d7dc221 | [
"MIT"
] | 4 | 2018-02-21T15:38:56.000Z | 2019-04-03T07:57:22.000Z | unit_tests/test_playable_moves.cpp | julienlopez/Aronda | 8fb6625bc037736dc2926f97f46a59441d7dc221 | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include "game.hpp"
#include <numeric_range.hpp>
#include <boost/optional/optional_io.hpp>
using Aronda::Board;
using Aronda::Game;
using Aronda::InvalidMove;
using Aronda::Square;
using Aronda::SquareState;
template <class T> bool contains(const std::vector<T>& container, const T& value)
{
return std::find(begin(container), end(container), value) != end(container);
}
TEST_CASE("Testing playable moves throughout the game", "[board]")
{
SECTION("Only the outside squares are playable on an empty board")
{
Board g;
const std::vector<std::size_t> playable_moves = {17, 18, 19, 20, 21, 22, 23, 24};
for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares))
{
const auto res = g.placeStone({Square{square}, Aronda::black, 1});
if(contains(playable_moves, square))
{
CHECK(res.has_value());
}
else
{
REQUIRE_FALSE(res.has_value());
CHECK(res.error() == InvalidMove::SquareUnreachable);
}
}
}
SECTION("Only the outside squares are playable for white's first move")
{
Board b;
const auto res = b.placeStone({Square{24}, Aronda::black, 1});
REQUIRE(res.has_value());
b = res.value();
const std::vector<std::size_t> playable_moves = {17, 18, 19, 20, 21, 22, 23, 24};
for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares))
{
const auto res = b.placeStone({Square{square}, Aronda::white, 1});
if(contains(playable_moves, square))
{
CHECK(res.has_value());
}
else
{
REQUIRE_FALSE(res.has_value());
CHECK(res.error() == InvalidMove::SquareUnreachable);
}
}
}
SECTION("Playing one stone on an outside square unlocks all underlying squares")
{
Game g;
auto res = g.placeStone({Square{24}, Aronda::black, 1});
REQUIRE(res.has_value());
res = g.placeStone({Square{24}, Aronda::white, 1});
REQUIRE(res.has_value());
const std::vector<std::size_t> playable_moves = {9, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares))
{
const auto res = g.currentState().placeStone({Square{square}, Aronda::white, 1});
if(contains(playable_moves, square))
{
CHECK(res.has_value());
}
else
{
REQUIRE_FALSE(res.has_value());
CHECK(res.error() == InvalidMove::SquareUnreachable);
}
}
}
}
| 32.206897 | 100 | 0.557459 | julienlopez |
3927538b461a290b31713b17dcd1b427bbf1a297 | 736 | cpp | C++ | tests/test18.cpp | varnie/giraffe | 0448536cdca5dad66110aa64fdf24688b2a0050a | [
"MIT"
] | null | null | null | tests/test18.cpp | varnie/giraffe | 0448536cdca5dad66110aa64fdf24688b2a0050a | [
"MIT"
] | 1 | 2020-06-16T14:25:17.000Z | 2020-06-16T14:25:17.000Z | tests/test18.cpp | varnie/giraffe | 0448536cdca5dad66110aa64fdf24688b2a0050a | [
"MIT"
] | null | null | null | //
// Created by varnie on 2/23/16.
//
#include <gtest/gtest.h>
#include "../include/Giraffe.h"
TEST(StorageTest, CheckRetrievingAllEntities) {
struct Foo {
Foo() { }
};
using StorageT = Giraffe::Storage<>;
using EntityT = Giraffe::Entity<StorageT>;
StorageT storage;
for (int i = 0; i < 5; ++i) {
EntityT e = storage.addEntity();
}
std::size_t count1 = 0, count2 = 0;
for (const auto &entity: storage.range()) {
++count1;
}
EXPECT_EQ(count1, 5);
storage.process([&](const EntityT &entity) {
++count2;
});
EXPECT_EQ(count2, 5);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 17.52381 | 48 | 0.576087 | varnie |
392770182075de0f956a67a461d133ca273fc07b | 1,231 | cpp | C++ | Notes_Week3/composition.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | Notes_Week3/composition.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | Notes_Week3/composition.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
void setLength(double len) {
length = len;
}
void setWidth(double wid) {
width = wid;
}
double getLength() {
return length;
}
double getWidth() {
return width;
}
double calcArea() {
return length * width;
}
};
class Carpet {
private:
double pricePerSqYd;
Rectangle size; // Instance of the Rentangle class
public:
void setPricePerYd(double p) {
pricePerSqYd = p;
}
void setDimensions(double len, double wid) {
size.setLength(len/3);
size.setWidth(wid/3);
}
double getTotalPrice() {
return (size.calcArea() * pricePerSqYd);
}
};
int main() {
Carpet purchase;
double pricePerSqYd;
double length;
double width;
cout << "Room length in feat: ";
cin >> length;
cout << "Room width in feet: ";
cin >> width;
cout << "Carpet price per sq. yard: ";
cin >> pricePerSqYd;
purchase.setDimensions(length, width);
purchase.setPricePerYd(pricePerSqYd);
cout << "\n The total price of my new carpet is $" << purchase.getTotalPrice() << endl;
return 0;
}
| 17.84058 | 89 | 0.607636 | WeiChienHsu |
392b50d729fc87eed2c45f0554e10b2f27e19709 | 1,949 | cpp | C++ | texture-packer/src/main/Functions/main.cpp | ii887522/texture-packer | 0dc2b6656329f427881c36ddafc0196447c74926 | [
"MIT"
] | null | null | null | texture-packer/src/main/Functions/main.cpp | ii887522/texture-packer | 0dc2b6656329f427881c36ddafc0196447c74926 | [
"MIT"
] | null | null | null | texture-packer/src/main/Functions/main.cpp | ii887522/texture-packer | 0dc2b6656329f427881c36ddafc0196447c74926 | [
"MIT"
] | null | null | null | // Copyright ii887522
#ifndef TEST
#define ALLOCATOR_IMPLEMENTATIONS
#include <nitro/nitro.h>
#include <SDL.h>
#include <viewify/viewify.h>
#include <iostream>
#include <stdexcept>
#include <filesystem>
#include "../ViewGroupFactory/TexturePackerViewGroupFactory.h"
#include "../Any/CommandLine.h"
#include <SDL_image.h>
using ii887522::viewify::App;
using ii887522::viewify::Subsystems;
using ii887522::viewify::Size;
using ii887522::viewify::Color;
using ii887522::viewify::eventLoop;
using std::cerr;
using std::invalid_argument;
using std::filesystem::directory_iterator;
namespace ii887522::texturePacker {
static int main(int argc, char** argv) try {
const CommandLine commandLine{ argc, argv };
commandLine.validate();
const Subsystems subsystems;
TexturePackerViewGroupFactory texturePackerViewGroupFactory{ commandLine.getInputDirPath(), commandLine.getOutputDirPath(), commandLine.getAtlasSize() };
// See also ../ViewGroupFactory/TexturePackerViewGroupFactory.h for more details
eventLoop(App{ "Texture Packer", commandLine.getAtlasSize(), Color{ 0u, 0u, 0u, 0u }, &texturePackerViewGroupFactory, SDL_WINDOW_MINIMIZED });
return EXIT_SUCCESS;
} catch (const invalid_argument&) {
cerr << "Command Line: texture-packer <input-directory-path> <output-directory-path> <atlas-width> <atlas-height>\n";
cerr << "Param <input-directory-path>: it must exists, has at least 1 png file and ends with either '/' or '\\'\n";
cerr << "Param <output-directory-path>: it must ends with either '/' or '\\'\n";
cerr << "Param <atlas-width>: it must be equal to 2^n where n is a non-negative integer, and big enough to fill sprites\n";
cerr << "Param <atlas-height>: it must be equal to 2^n where n is a non-negative integer, and big enough to fill sprites\n";
return EXIT_FAILURE;
}
} // namespace ii887522::texturePacker
int main(int argc, char** argv) {
return ii887522::texturePacker::main(argc, argv);
}
#endif
| 37.480769 | 155 | 0.746537 | ii887522 |
3930edb38c8069acc6af05d921b0fc3c51491186 | 982 | cpp | C++ | LoveLiveWallpaper/src/Interactable.cpp | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | 2 | 2020-05-09T00:13:06.000Z | 2020-05-25T05:49:40.000Z | LoveLiveWallpaper/src/Interactable.cpp | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | null | null | null | LoveLiveWallpaper/src/Interactable.cpp | Juvwxyz/LoveLiveWallpaper | a0eeac941b5ccd53af538192cb92b7df049839c4 | [
"MIT"
] | 1 | 2020-05-25T05:49:44.000Z | 2020-05-25T05:49:44.000Z | #include "Interactable.h"
#include "Component.h"
#include "Mouse.h"
#include "MouseEventArg.h"
#include "Transform.h"
namespace LLWP
{
Interactable::Interactable()
{
Mouse::OnHitTest += (*this, &Interactable::OnHitTest);
}
bool Interactable::OnHitTest(Interactable*& hitted, const MouseEventArg& arg)
{
Component* thisComponent = dynamic_cast<Component*>(this);
if (thisComponent->transform().HitTest(arg.position().x, arg.position().y))
{
if (hitted == nullptr)
{
hitted = this;
return true;
}
else if (dynamic_cast<Component*>(hitted)->transform().position().z() <= thisComponent->transform().position().z())
{
hitted = this;
return true;
}
}
return false;
}
Interactable::~Interactable()
{
Mouse::OnHitTest -= (*this, &Interactable::OnHitTest);
}
}
| 26.540541 | 127 | 0.550916 | Juvwxyz |
3932962e99e15a87428393817850c8fb38c73874 | 1,441 | hpp | C++ | include/argot/concepts/reference.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 49 | 2018-05-09T23:17:45.000Z | 2021-07-21T10:05:19.000Z | include/argot/concepts/reference.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | null | null | null | include/argot/concepts/reference.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 2 | 2019-08-04T03:51:36.000Z | 2020-12-28T06:53:29.000Z | /*==============================================================================
Copyright (c) 2017, 2018, 2019 Matt Calabrese
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ARGOT_CONCEPTS_REFERENCE_HPP_
#define ARGOT_CONCEPTS_REFERENCE_HPP_
//[description
/*`
Reference is an [argot_gen_concept] that is satisfied by reference types.
*/
//]
#include <argot/concepts/detail/concepts_preprocessing_helpers.hpp>
#include <argot/gen/explicit_concept.hpp>
#include <argot/gen/make_concept_map.hpp>
namespace argot {
#define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \
s/reference.h
#ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
#include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER
#else
#include <argot/concepts/detail/preprocess_header_begin.hpp>
ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ )
template< class T >
ARGOT_EXPLICIT_CONCEPT( Reference )
(
);
#include <argot/concepts/detail/preprocess_header_end.hpp>
#endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
template< class T >
struct make_concept_map< Reference< T& > > {};
template< class T >
struct make_concept_map< Reference< T&& > > {};
} // namespace argot
#endif // ARGOT_CONCEPTS_REFERENCE_HPP_
| 27.711538 | 80 | 0.700902 | mattcalabrese |
39410f0a0e8766d77f03a940a2f9f9f063b966d9 | 4,968 | cpp | C++ | test/path_append_test.cpp | abdes/asap_filesystem | 44b8ab19900db6ce58a8802817a5b42d6ab6a4b3 | [
"BSD-3-Clause"
] | 3 | 2019-05-20T14:21:11.000Z | 2019-05-21T19:09:13.000Z | test/path_append_test.cpp | abdes/asap_filesystem | 44b8ab19900db6ce58a8802817a5b42d6ab6a4b3 | [
"BSD-3-Clause"
] | null | null | null | test/path_append_test.cpp | abdes/asap_filesystem | 44b8ab19900db6ce58a8802817a5b42d6ab6a4b3 | [
"BSD-3-Clause"
] | null | null | null | // Copyright The Authors 2018.
// Distributed under the 3-Clause BSD License.
// (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/BSD-3-Clause)
#if defined(__clang__)
#pragma clang diagnostic push
// Catch2 uses a lot of macro names that will make clang go crazy
#if (__clang_major__ >= 13) && !defined(__APPLE__)
#pragma clang diagnostic ignored "-Wreserved-identifier"
#endif
// Big mess created because of the way spdlog is organizing its source code
// based on header only builds vs library builds. The issue is that spdlog
// places the template definitions in a separate file and explicitly
// instantiates them, so we have no problem at link, but we do have a problem
// with clang (rightfully) complaining that the template definitions are not
// available when the template needs to be instantiated here.
#pragma clang diagnostic ignored "-Wundefined-func-template"
#endif // __clang__
#include <catch2/catch.hpp>
#include "fs_testsuite.h"
using testing::ComparePaths;
using testing::TEST_PATHS;
// path::operator/=(const path&)
namespace {
auto Append(fs::path l, const fs::path &r) -> fs::path {
l /= r;
return l;
}
} // namespace
// -----------------------------------------------------------------------------
// Append
// -----------------------------------------------------------------------------
TEST_CASE("Path / append / path", "[common][filesystem][path][append]") {
ComparePaths(Append("/foo/bar", "/foo/"), "/foo/");
ComparePaths(Append("baz", "baz"), "baz/baz");
ComparePaths(Append("baz/", "baz"), "baz/baz");
ComparePaths(Append("baz", "/foo/bar"), "/foo/bar");
ComparePaths(Append("baz/", "/foo/bar"), "/foo/bar");
REQUIRE(Append("", "").empty());
REQUIRE(!Append("", "rel").is_absolute());
ComparePaths(Append("dir/", "/file"), "/file");
ComparePaths(Append("dir/", "file"), "dir/file");
// path("foo") / ""; // yields "foo/"
ComparePaths(Append("foo", ""), "foo/");
// path("foo") / "/bar"; // yields "/bar"
ComparePaths(Append("foo", "/bar"), "/bar");
// path("foo") / ""; // yields "foo/"
ComparePaths(Append("foo", ""), "foo/");
// path("foo") / "/bar"; // yields "/bar"
ComparePaths(Append("foo", "/bar"), "/bar");
#if defined(ASAP_WINDOWS)
ComparePaths(Append("//host", "foo"), "//host/foo");
ComparePaths(Append("//host/", "foo"), "//host/foo");
ComparePaths(Append("//host/bar", "foo"), "//host/bar/foo");
ComparePaths(Append("//host", "/foo"), "//host/foo");
ComparePaths(Append("//host", "//other/foo"), "//other/foo");
ComparePaths(Append("//host/bar", "//other/foo"), "//other/foo");
ComparePaths(Append("c:/foo", "/bar"), "c:/bar");
// path("c:") / ""; // yields "c:"
ComparePaths(Append("c:", ""), "c:");
// path("c:foo") / "/bar"; // yields "c:/bar"
ComparePaths(Append("c:foo", "/bar"), "c:/bar");
// path("c:foo") / "c:bar"; // yields "c:foo/bar"
ComparePaths(Append("c:foo", "c:bar"), "c:foo/bar");
// path("foo") / "c:/bar"; // yields "c:/bar"
ComparePaths(Append("foo", "c:/bar"), "c:/bar");
// path("foo") / "c:"; // yields "c:"
ComparePaths(Append("foo", "c:"), "c:");
#endif // ASAP_WINDOWS
}
// path::operator/=(const Source& source)
// path::Append(const Source& source)
// Equivalent to: return operator/=(path(source));
// path::Append(InputIterator first, InputIterator last)
// Equivalent to: return operator/=(path(first, last));
template <typename Char> void test(const fs::path &p, const Char *s) {
fs::path expected = p;
expected /= fs::path(s);
fs::path oper = p;
oper /= s;
fs::path func = p;
func.append(s);
std::vector<char> input_range(s, s + std::char_traits<Char>::length(s));
fs::path range = p;
range.append(input_range.begin(), input_range.end());
ComparePaths(oper, expected);
ComparePaths(func, expected);
ComparePaths(range, expected);
}
TEST_CASE("Path / append / source", "[common][filesystem][fs::path][append]") {
test("/foo/bar", "/foo/");
test("baz", "baz");
test("baz/", "baz");
test("baz", "/foo/bar");
test("baz/", "/foo/bar");
test("", "");
test("", "rel");
test("dir/", "/file");
test("dir/", "file");
// C++17 [fs.fs::path.append] p4
test("//host", "foo");
test("//host/", "foo");
test("foo", "");
test("foo", "/bar");
test("foo", "c:/bar");
test("foo", "c:");
test("c:", "");
test("c:foo", "/bar");
test("foo", "c:\\bar");
}
TEST_CASE("Path / append / source / TEST_PATHS", "[common][filesystem][fs::path][append]") {
for (const fs::path p : TEST_PATHS()) {
for (const fs::path q : TEST_PATHS()) {
test(p, q.c_str());
}
}
}
// TODO(abdessattar): figure later wstring vs string correct impl
/*
TEST_CASE("Path / append / source / wstring",
"[common][filesystem][path][append]") {
test( "foo", L"/bar" );
test( L"foo", "/bar" );
test( L"foo", L"/bar" );
}
*/
#if defined(__clang__)
#pragma clang diagnostic pop
#endif // __clang__
| 29.748503 | 92 | 0.589171 | abdes |
39503020253aa1fc8bd888aea2ab04ff9816e6bc | 49 | hpp | C++ | src/agl/opengl/function/vertex_attribute/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/vertex_attribute/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/vertex_attribute/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | #pragma once
#include "get_vertex_location.hpp"
| 12.25 | 34 | 0.795918 | the-last-willy |
39514b46fc36f061eaefc57aff06033acea5d384 | 1,023 | cpp | C++ | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez | 52f01b57eea81445f5ef13325969a8a1bd868c50 | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez | 52f01b57eea81445f5ef13325969a8a1bd868c50 | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez | 52f01b57eea81445f5ef13325969a8a1bd868c50 | [
"MIT"
] | null | null | null | #include "tic_tac_toe_manager.h"
void TicTacToeManager::save_game(std::unique_ptr<TicTacToe> & b)
{
update_winner_count(b->get_winner());
games.push_back(std::move(b));
}
ostream& operator << (ostream& out, const TicTacToeManager& manager)
{
for(auto& x : manager.games)
{
out << *x;
}
out << "X won: " << manager.x_win << "\n";
out << "O won: " << manager.o_win << "\n";
out << "Ties: " << manager.tie << "\n";
return out;
}
void TicTacToeManager :: get_winner_total(int& o, int& x, int& t)
{
cout << endl
<< "X Wins =" << x << endl
<< "O Wins =" << o << endl
<< "Ties =" << t << endl
<< endl;
}
void TicTacToeManager :: update_winner_count(string winner)
{
if(winner== "X")
x_win++;
else if(winner =="O")
o_win++;
else
tie++;
}
TicTacToeManager::TicTacToeManager(TicTacToeData& d)
{
games = d.get_games();
for(auto& g : games)
{
update_winner_count(g->get_winner());
}
}
| 21.3125 | 68 | 0.545455 | acc-cosc-1337-fall-2020 |
395242967db1c79c99f873570497994265193717 | 671 | hpp | C++ | src/input.hpp | MaemiKozue/hexceed | 11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a | [
"MIT"
] | null | null | null | src/input.hpp | MaemiKozue/hexceed | 11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a | [
"MIT"
] | null | null | null | src/input.hpp | MaemiKozue/hexceed | 11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a | [
"MIT"
] | null | null | null | #ifndef INPUT_H
#define INPUT_H
#include <iostream>
typedef enum InputType {
MOUSE, KEYBOARD
} InputType;
typedef enum KEY {
KEY_ENTER
} KEY;
typedef enum MOUSE_BUTTON {
MB_MIDDLE, MB_LEFT, MB_RIGHT
} MOUSE_BUTTON;
class Input
{
private:
InputType type;
int x, y; // mouse position
MOUSE_BUTTON mb; // mouse button
KEY key; // key press
public:
Input(MOUSE_BUTTON mb, int x, int y);
Input(KEY key);
~Input();
InputType getType() const;
int getX() const;
int getY() const;
MOUSE_BUTTON getButton() const;
KEY getKey() const;
};
std::ostream& operator<<(std::ostream& out, Input in);
#endif // INPUT_H
| 15.97619 | 54 | 0.654247 | MaemiKozue |
395693c05065645deeca76b1e0fbb8443b352707 | 2,080 | hpp | C++ | ext/src/java/awt/BasicStroke.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/awt/BasicStroke.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/awt/BasicStroke.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <fwd-POI.hpp>
#include <java/awt/fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <java/awt/Stroke.hpp>
struct default_init_tag;
class java::awt::BasicStroke
: public virtual ::java::lang::Object
, public virtual Stroke
{
public:
typedef ::java::lang::Object super;
static constexpr int32_t CAP_BUTT { int32_t(0) };
static constexpr int32_t CAP_ROUND { int32_t(1) };
static constexpr int32_t CAP_SQUARE { int32_t(2) };
static constexpr int32_t JOIN_BEVEL { int32_t(2) };
static constexpr int32_t JOIN_MITER { int32_t(0) };
static constexpr int32_t JOIN_ROUND { int32_t(1) };
public: /* package */
int32_t cap { };
::floatArray* dash { };
float dash_phase { };
int32_t join { };
float miterlimit { };
float width { };
protected:
void ctor();
void ctor(float width);
void ctor(float width, int32_t cap, int32_t join);
void ctor(float width, int32_t cap, int32_t join, float miterlimit);
void ctor(float width, int32_t cap, int32_t join, float miterlimit, ::floatArray* dash, float dash_phase);
public:
Shape* createStrokedShape(Shape* s) override;
bool equals(::java::lang::Object* obj) override;
virtual ::floatArray* getDashArray_();
virtual float getDashPhase();
virtual int32_t getEndCap();
virtual int32_t getLineJoin();
virtual float getLineWidth();
virtual float getMiterLimit();
int32_t hashCode() override;
// Generated
BasicStroke();
BasicStroke(float width);
BasicStroke(float width, int32_t cap, int32_t join);
BasicStroke(float width, int32_t cap, int32_t join, float miterlimit);
BasicStroke(float width, int32_t cap, int32_t join, float miterlimit, ::floatArray* dash, float dash_phase);
protected:
BasicStroke(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 30.144928 | 112 | 0.694231 | pebble2015 |
39599126185e37194126c4ae8f0c418c2f957a66 | 487 | hpp | C++ | EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | #pragma once
#ifndef _ENTITYSYSTEMGENERATOR_COMPONENTMAPSSOURCEGENERATOR_HPP_
#define _ENTITYSYSTEMGENERATOR_COMPONENTMAPSSOURCEGENERATOR_HPP_
#include "CodeGenerator.hpp"
#include "ComponentDefinitions.hpp"
namespace Fnd
{
namespace EntitySystemCodeGeneration
{
class ComponentMapsSourceGenerator:
public CodeGenerator
{
public:
bool Generate( const ComponentDefinitions& component_definitions,
const std::string& output_file );
};
}
}
#endif | 18.037037 | 68 | 0.780287 | jordanlittlefair |
395b252c334d240cbe37b6be91d0904cb2f834af | 349 | cpp | C++ | cpp/cpp_primer/chapter10/ex_10_42.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | 2 | 2019-12-21T00:53:47.000Z | 2020-01-01T10:36:30.000Z | cpp/cpp_primer/chapter10/ex_10_42.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | cpp/cpp_primer/chapter10/ex_10_42.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | //
// Created by kaiser on 18-12-17.
//
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
void elim_dups(std::list<std::string>& words) {
words.sort();
words.unique();
}
int main() {
std::list<std::string> vs{"a", "a", "c", "c", "b"};
elim_dups(vs);
for (const auto& s : vs) {
std::cout << s << '\n';
}
}
| 15.863636 | 53 | 0.56447 | KaiserLancelot |
395f6301e153f9d9d7d2dd3428f88d665133c104 | 850 | cpp | C++ | PTA-B/right/1013-right.cpp | chiangyung/PTA | c8e6bcbc9e552dad5ab71679d861a235b8ad0730 | [
"MIT"
] | 2 | 2018-08-23T06:58:56.000Z | 2018-09-04T02:07:44.000Z | PTA-B/right/1013-right.cpp | chiangyung/PTA | c8e6bcbc9e552dad5ab71679d861a235b8ad0730 | [
"MIT"
] | null | null | null | PTA-B/right/1013-right.cpp | chiangyung/PTA | c8e6bcbc9e552dad5ab71679d861a235b8ad0730 | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
const int INTMAX = pow(2, 30);
bool is_prime(const int n)
{
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
int m, n;
int count1 = 0, count2 = 0;
cin >> m >> n;
for (int i = 2; i < INTMAX; i++) {
if (is_prime(i)) {
count1++;
if (count1 >= m && count1 <= n) {
cout << i;
count2++;
if (count1 == n) {
cout << endl;
break;
}
if (count2 % 10 == 0) {
cout << endl;
} else {
cout << " ";
}
}
}
}
return 0;
}
| 18.888889 | 45 | 0.342353 | chiangyung |
395f7c953cc08a36d29401fb4b839e28b84b46d3 | 531 | cpp | C++ | test/Model/Header.cpp | jxx-project/JXXRS | 0d788e3aba5231ec1782699c9d397b9d81fdb1fd | [
"BSL-1.0"
] | null | null | null | test/Model/Header.cpp | jxx-project/JXXRS | 0d788e3aba5231ec1782699c9d397b9d81fdb1fd | [
"BSL-1.0"
] | null | null | null | test/Model/Header.cpp | jxx-project/JXXRS | 0d788e3aba5231ec1782699c9d397b9d81fdb1fd | [
"BSL-1.0"
] | null | null | null | //
// Copyright (C) 2018 Dr. Michael Steffens
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Model/Header.h"
namespace Model {
Header::Header()
{
}
Header::Header(const std::string& name, const std::string& value) : name(name), value(value)
{
}
Header::Header(const JXXON::Json& json) : name(json.get<decltype(name)>("name")), value(json.get<decltype(value)>("value"))
{
}
JXXON::Json Header::toJson() const
{
JXXON::Json json;
json.set("name", name);
json.set("value", value);
return json;
}
} // namespace Model
| 16.090909 | 123 | 0.661017 | jxx-project |
396289f2ff22620325ab55248496538c6b002707 | 3,553 | cpp | C++ | src/caffe/test/test_training_utils.cpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 933 | 2016-08-29T14:29:20.000Z | 2022-03-20T09:03:49.000Z | src/caffe/test/test_training_utils.cpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 286 | 2016-08-30T01:33:01.000Z | 2021-08-22T08:34:19.000Z | src/caffe/test/test_training_utils.cpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 611 | 2016-08-30T07:22:04.000Z | 2021-12-18T11:53:08.000Z | /*
All modification made by Intel Corporation: © 2016 Intel Corporation
All contributions by the University of California:
Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
All rights reserved.
All other contributions:
Copyright (c) 2014, 2015, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
#include <utility>
#include "boost/algorithm/string.hpp"
#include "boost/lexical_cast.hpp"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "caffe/solver.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/upgrade_proto.hpp"
#include "caffe/training_utils.hpp"
namespace caffe {
class TrainingUtilsTest : public ::testing::Test {
protected:
TrainingUtilsTest()
: topology_file_name_(
CMAKE_SOURCE_DIR "caffe/test/test_data/test_topology.prototxt") {
}
string topology_file_name_;
};
TEST_F(TrainingUtilsTest, GetStagesFromFlags) {
string stages_flag = "stage1,stage2, stage3";
EXPECT_EQ(get_stages_from_flags(stages_flag).size(), 3);
}
TEST_F(TrainingUtilsTest, SetSolverParamsFromFlags) {
caffe::SolverParameter solver_param;
string solver;
string engine = "new engine";
string stages = "stage1,stage2";
int level = 1;
use_flags(&solver_param, solver, engine, level, stages);
EXPECT_EQ(solver_param.engine(), engine);
EXPECT_EQ(solver_param.train_state().stage_size(), 2);
EXPECT_EQ(solver_param.train_state().level(), 1);
}
TEST_F(TrainingUtilsTest, MultiphaseTrainNegativeCpuMode) {
caffe::MultiPhaseSolverParameter multi_solver_param;
caffe::SolverBatchSizePair* solver_param_pair =
multi_solver_param.add_params_pair();
solver_param_pair->mutable_solver_params()->set_solver_mode(
caffe::SolverParameter_SolverMode_GPU);
solver_param_pair->mutable_solver_params()->set_net(
this->topology_file_name_);
EXPECT_EQ(multiphase_train(&multi_solver_param, "", "", 0, ""), -1);
}
} // namespace caffe
| 35.178218 | 92 | 0.777934 | ayzk |
39644976619fc7b047dc5bfb77f4732ad44a2038 | 621 | cxx | C++ | test_code/test_fdstream_simple.cxx | m-renaud/posix-lib | 0296999e252e2b40a80bcc01ea6a1742e8ef1c49 | [
"BSD-2-Clause"
] | 1 | 2020-11-11T12:50:30.000Z | 2020-11-11T12:50:30.000Z | test_code/test_fdstream_simple.cxx | m-renaud/posix-lib | 0296999e252e2b40a80bcc01ea6a1742e8ef1c49 | [
"BSD-2-Clause"
] | null | null | null | test_code/test_fdstream_simple.cxx | m-renaud/posix-lib | 0296999e252e2b40a80bcc01ea6a1742e8ef1c49 | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include "../fdstream.hxx"
#include "../pipe.hxx"
int main()
{
try
{
mrr::posix::pipe successful_auth;
mrr::posix::fd_ostream write_end(successful_auth.write_end());
mrr::posix::fd_istream read_end(successful_auth.read_end());
int received[2];
write_end << 5 << std::endl;
write_end << 8 << std::endl;
read_end >> received[0];
read_end >> received[1];
std::cout << received[0] << std::endl
<< received[1] << std::endl;
successful_auth.close();
}
catch(std::system_error const& except)
{
mrr::posix::output_system_error_msg();
exit(1);
}
return 0;
}
| 17.25 | 64 | 0.639291 | m-renaud |
396aeaba14dfb506f287778ba27e13dd0c0d77f0 | 1,473 | hpp | C++ | include/sprout/predef/compiler/sgi_mipspro.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/predef/compiler/sgi_mipspro.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/predef/compiler/sgi_mipspro.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the sprout Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.sprout.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
#define SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
#include <sprout/config.hpp>
#include <sprout/predef/make.hpp>
#define SPROUT_COMP_SGI 0
#if defined(__sgi) || defined(sgi)
# if !defined(SPROUT_COMP_SGI_DETECTION) && defined(_SGI_COMPILER_VERSION)
# define SPROUT_COMP_SGI_DETECTION SPROUT_PREDEF_MAKE_10_VRP(_SGI_COMPILER_VERSION)
# endif
# if !defined(SPROUT_COMP_SGI_DETECTION) && defined(_COMPILER_VERSION)
# define SPROUT_COMP_SGI_DETECTION SPROUT_PREDEF_MAKE_10_VRP(_COMPILER_VERSION)
# endif
# if !defined(SPROUT_COMP_SGI_DETECTION)
# define SPROUT_COMP_SGI_DETECTION 1
# endif
#endif
#ifdef SPROUT_COMP_SGI_DETECTION
# if defined(SPROUT_PREDEF_DETAIL_COMP_DETECTED)
# define SPROUT_COMP_SGI_EMULATED SPROUT_COMP_SGI_DETECTION
# else
# undef SPROUT_COMP_SGI
# define SPROUT_COMP_SGI SPROUT_COMP_SGI_DETECTION
# endif
# define SPROUT_COMP_SGI_AVAILABLE
# include <sprout/predef/detail/comp_detected.hpp>
#endif
#define SPROUT_COMP_SGI_NAME "SGI MIPSpro"
#endif //#ifndef SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
| 35.071429 | 84 | 0.739308 | thinkoid |
396b1304f779670ccebfe8e01a457de7da6c4d38 | 1,764 | hpp | C++ | tasks/FrameFilter.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 1 | 2022-01-31T01:59:52.000Z | 2022-01-31T01:59:52.000Z | tasks/FrameFilter.hpp | PhischDotOrg/stm32-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 5 | 2020-04-13T21:55:12.000Z | 2020-06-27T17:44:44.000Z | tasks/FrameFilter.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | null | null | null | /*-
* $Copyright$
-*/
#ifndef _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe
#define _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe
#include <tasks/Task.hpp>
#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */
#include "FreeRTOS/FreeRTOS.h"
#include "FreeRTOS/queue.h"
#if defined(__cplusplus)
} /* extern "C" */
#endif /* defined(__cplusplus) */
namespace tasks {
template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT>
class FrameFilterT : public Task {
private:
UartT & m_uart;
OutputBufferT (&m_frames)[N];
FilterChainT & m_filter;
PinT * m_activeIndicationPin;
unsigned m_current;
QueueHandle_t * m_rxQueue;
QueueHandle_t * m_txQueue;
virtual void run(void);
public:
FrameFilterT(const char * const p_name, const unsigned p_priority,
UartT &p_uart, OutputBufferT (&p_frames)[N], FilterChainT &p_filter);
virtual ~FrameFilterT();
void setTxQueue(QueueHandle_t* p_txQueue) {
m_txQueue = p_txQueue;
}
QueueHandle_t* getTxQueue() const {
return m_txQueue;
}
void setRxQueue(QueueHandle_t* p_rxQueue) {
m_rxQueue = p_rxQueue;
}
QueueHandle_t* getRxQueue() const {
return m_rxQueue;
}
void setActiveIndicationPin(PinT* p_activeIndicationPin) {
m_activeIndicationPin = p_activeIndicationPin;
}
PinT* getActiveIndicationPin() const {
return m_activeIndicationPin;
}
typedef OutputBufferT Buffer_t;
};
}; /* namespace tasks */
#include "FrameFilter.cpp"
#endif /* _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe */ | 25.2 | 119 | 0.679705 | PhischDotOrg |
396c73354d9d9ef8cf18366a2a474450ef4f9501 | 1,774 | cc | C++ | map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 1,936 | 2017-11-27T23:11:37.000Z | 2022-03-30T14:24:14.000Z | map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 353 | 2017-11-29T18:40:39.000Z | 2022-03-30T15:53:46.000Z | map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 661 | 2017-11-28T07:20:08.000Z | 2022-03-28T08:06:29.000Z | #include <Eigen/Core>
#include <gtest/gtest.h>
#include <maplab-common/test/testing-entrypoint.h>
#include "vi-map/test/vi-map-generator.h"
namespace vi_map {
class VIMapTest : public ::testing::Test {
protected:
VIMapTest() : map_(), generator_(map_, 42) {}
virtual void SetUp() {
pose::Transformation T_G_V;
pose::Transformation T_G_M;
missions_[0] = generator_.createMission(T_G_M);
missions_[1] = generator_.createMission(T_G_M);
vertices_[0] = generator_.createVertex(missions_[0], T_G_V);
vertices_[1] = generator_.createVertex(missions_[0], T_G_V);
vertices_[2] = generator_.createVertex(missions_[0], T_G_V);
vertices_[3] = generator_.createVertex(missions_[1], T_G_V);
vertices_[4] = generator_.createVertex(missions_[1], T_G_V);
vertices_[5] = generator_.createVertex(missions_[1], T_G_V);
generator_.generateMap();
}
vi_map::MissionId missions_[2];
pose_graph::VertexId vertices_[6];
VIMap map_;
VIMapGenerator generator_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
TEST_F(VIMapTest, TestGetAllVertexIdsInMission) {
pose_graph::VertexIdList vertex_ids;
map_.getAllVertexIdsInMission(missions_[0], &vertex_ids);
for (const pose_graph::VertexId& vertex_id : vertex_ids) {
EXPECT_EQ(map_.getVertex(vertex_id).getMissionId(), missions_[0]);
}
}
TEST_F(VIMapTest, TestGetAllVertexIdsInMissionAlongGraph) {
pose_graph::VertexIdList vertex_ids;
map_.getAllVertexIdsInMissionAlongGraph(missions_[0], &vertex_ids);
EXPECT_FALSE(vertex_ids.empty());
for (size_t i = 0; i < vertex_ids.size(); ++i) {
EXPECT_EQ(map_.getVertex(vertex_ids[i]).getMissionId(), missions_[0]);
EXPECT_EQ(vertex_ids[i], vertices_[i]);
}
}
} // namespace vi_map
MAPLAB_UNITTEST_ENTRYPOINT
| 27.71875 | 74 | 0.73168 | AdronTech |
397170c480ab89b57d5c1d86eefd61c9657a072d | 10,484 | cc | C++ | src/io/scene_loader.cc | hyungman/SpRay | 96380740dd88e6fbc21c0fdbf232cff357b1235d | [
"Apache-2.0"
] | 7 | 2018-10-22T17:13:36.000Z | 2020-04-17T08:28:55.000Z | src/io/scene_loader.cc | hyungman/SpRay | 96380740dd88e6fbc21c0fdbf232cff357b1235d | [
"Apache-2.0"
] | null | null | null | src/io/scene_loader.cc | hyungman/SpRay | 96380740dd88e6fbc21c0fdbf232cff357b1235d | [
"Apache-2.0"
] | 1 | 2018-11-01T14:53:22.000Z | 2018-11-01T14:53:22.000Z | // ========================================================================== //
// Copyright (c) 2017-2018 The University of Texas at Austin. //
// 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. //
// A copy of the License is included with this software in the file LICENSE. //
// If your copy does not contain the License, you may obtain a copy of the //
// License at: //
// //
// https://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT //
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// //
// ========================================================================== //
#include "io/scene_loader.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glog/logging.h"
#include "render/aabb.h"
#include "render/light.h"
#include "render/reflection.h"
#include "render/spray.h"
// #define SPRAY_PRINT_LINES
// #define SPRAY_PRINT_TOKENS
namespace spray {
SceneLoader::DomainTokenType SceneLoader::getTokenType(const std::string& tag) {
DomainTokenType type;
if (tag[0] == '#') {
type = DomainTokenType::kComment;
} else if (tag == "domain") {
type = DomainTokenType::kDomain;
} else if (tag == "file") {
type = DomainTokenType::kFile;
} else if (tag == "mtl") {
type = DomainTokenType::kMaterial;
} else if (tag == "bound") {
type = DomainTokenType::kBound;
} else if (tag == "scale") {
type = DomainTokenType::kScale;
} else if (tag == "rotate") {
type = DomainTokenType::kRotate;
} else if (tag == "translate") {
type = DomainTokenType::kTranslate;
} else if (tag == "face") {
type = DomainTokenType::kFace;
} else if (tag == "vertex") {
type = DomainTokenType::kVertex;
} else if (tag == "light") {
type = DomainTokenType::kLight;
} else {
LOG(FATAL) << "unknown tag name " << tag;
}
return type;
}
void SceneLoader::parseDomain(const std::vector<std::string>& tokens) {
nextDomain();
Domain& d = currentDomain();
d.id = domain_id_;
d.transform = glm::mat4(1.f);
}
void SceneLoader::parseFile(const std::string& ply_path,
const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 2);
d.filename = ply_path.empty() ? tokens[1] : ply_path + "/" + tokens[1];
}
void SceneLoader::parseMaterial(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
if (tokens[1] == "diffuse") {
// mtl diffuse albedo<r g b>
CHECK_EQ(tokens.size(), 5);
glm::vec3 albedo;
albedo[0] = atof(tokens[2].c_str());
albedo[1] = atof(tokens[3].c_str());
albedo[2] = atof(tokens[4].c_str());
d.bsdf = new DiffuseBsdf(albedo);
} else if (tokens[1] == "mirror") {
// mtl mirror reflectance<r g b>
CHECK_EQ(tokens.size(), 5);
glm::vec3 reflectance;
reflectance[0] = atof(tokens[2].c_str());
reflectance[1] = atof(tokens[3].c_str());
reflectance[2] = atof(tokens[4].c_str());
d.bsdf = new MirrorBsdf(reflectance);
} else if (tokens[1] == "glass") {
// mtl mirror etaA etaB
CHECK_EQ(tokens.size(), 4);
float eta_a = atof(tokens[2].c_str());
float eta_b = atof(tokens[3].c_str());
d.bsdf = new GlassBsdf(eta_a, eta_b);
} else if (tokens[1] == "transmission") {
// mtl transmission etaA etaB
CHECK_EQ(tokens.size(), 4);
float eta_a = atof(tokens[2].c_str());
float eta_b = atof(tokens[3].c_str());
d.bsdf = new TransmissionBsdf(eta_a, eta_b);
} else {
LOG(FATAL) << "unknown material type " << tokens[1];
}
}
void SceneLoader::parseBound(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 7);
glm::vec3 min(atof(tokens[1].c_str()), atof(tokens[2].c_str()),
atof(tokens[3].c_str()));
glm::vec3 max(atof(tokens[4].c_str()), atof(tokens[5].c_str()),
atof(tokens[6].c_str()));
d.object_aabb.bounds[0] = min;
d.object_aabb.bounds[1] = max;
}
void SceneLoader::parseScale(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 4);
d.transform = glm::scale(
d.transform, glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()),
atof(tokens[3].c_str())));
}
void SceneLoader::parseRotate(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 3);
glm::vec3 axis;
if (tokens[1] == "x") {
axis = glm::vec3(1.f, 0.f, 0.f);
} else if (tokens[1] == "y") {
axis = glm::vec3(0.f, 1.f, 0.f);
} else if (tokens[1] == "z") {
axis = glm::vec3(0.f, 0.f, 1.f);
} else {
LOG(FATAL) << "invalid axis name " << tokens[1];
}
d.transform = glm::rotate(d.transform,
(float)glm::radians(atof(tokens[2].c_str())), axis);
}
void SceneLoader::parseTranslate(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 4);
d.transform = glm::translate(
d.transform, glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()),
atof(tokens[3].c_str())));
}
void SceneLoader::parseFace(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 2);
d.num_faces = std::stoul(tokens[1]);
}
void SceneLoader::parseVertex(const std::vector<std::string>& tokens) {
Domain& d = currentDomain();
CHECK_EQ(tokens.size(), 2);
d.num_vertices = std::stoul(tokens[1]);
}
void SceneLoader::parseLight(const std::vector<std::string>& tokens) {
if (tokens[1] == "point") {
CHECK_EQ(tokens.size(), 8);
glm::vec3 position, radiance;
position[0] = atof(tokens[2].c_str());
position[1] = atof(tokens[3].c_str());
position[2] = atof(tokens[4].c_str());
radiance[0] = atof(tokens[5].c_str());
radiance[1] = atof(tokens[6].c_str());
radiance[2] = atof(tokens[7].c_str());
addLight(new PointLight(position, radiance));
} else if (tokens[1] == "diffuse") {
CHECK_EQ(tokens.size(), 5);
glm::vec3 position, radiance;
radiance[0] = atof(tokens[2].c_str());
radiance[1] = atof(tokens[3].c_str());
radiance[2] = atof(tokens[4].c_str());
addLight(new DiffuseHemisphereLight(radiance));
} else {
LOG(FATAL) << "unknown light source " << tokens[1];
}
}
void SceneLoader::parseLineTokens(const std::string& ply_path,
const std::vector<std::string>& tokens) {
DomainTokenType type = getTokenType(tokens[0]);
switch (type) {
case DomainTokenType::kDomain:
parseDomain(tokens);
break;
case DomainTokenType::kFile:
parseFile(ply_path, tokens);
break;
case DomainTokenType::kMaterial:
parseMaterial(tokens);
break;
case DomainTokenType::kBound:
parseBound(tokens);
break;
case DomainTokenType::kScale:
parseScale(tokens);
break;
case DomainTokenType::kRotate:
parseRotate(tokens);
break;
case DomainTokenType::kTranslate:
parseTranslate(tokens);
break;
case DomainTokenType::kFace:
parseFace(tokens);
break;
case DomainTokenType::kVertex:
parseVertex(tokens);
break;
case DomainTokenType::kLight:
parseLight(tokens);
break;
default:
break;
}
}
void SceneLoader::countAndAllocate(std::ifstream& infile) {
int ndomains = 0;
int nlights = 0;
std::string line;
while (infile.good()) {
getline(infile, line);
char* token = std::strtok(&line[0], " ");
if (token != NULL) {
if (strcmp(token, "domain") == 0) {
++ndomains;
} else if (strcmp(token, "light") == 0) {
++nlights;
}
}
}
CHECK_GT(ndomains, 0);
domains_->resize(ndomains);
if (nlights)
lights_->resize(nlights);
else
std::cout << "[WARNING] no lights detected\n";
std::cout << "[INFO] number of domains: " << ndomains << "\n";
std::cout << "[INFO] number of lights: " << nlights << "\n";
}
// # domain 0
// domain
// file CornellBox-Original.obj
// mtl 1
// bound -1 -1 -1 1 1 1
// scale 1 1 1
// rotate 0 0 0
// translate 0 0 0
//
// # domain 1
// # tbd
void SceneLoader::load(const std::string& filename, const std::string& ply_path,
std::vector<Domain>* domains_out,
std::vector<Light*>* lights_out) {
reset(domains_out, lights_out);
std::ifstream infile(filename);
CHECK(infile.is_open()) << "unable to open input file " << filename;
countAndAllocate(infile);
infile.clear();
infile.seekg(infile.beg);
char delim[] = " ";
std::vector<std::string> tokens;
while (infile.good()) {
std::string line;
getline(infile, line);
#ifdef SPRAY_PRINT_LINES
std::cout << line << "\n";
#endif
char* token = std::strtok(&line[0], delim);
tokens.clear();
while (token != NULL) {
#ifdef SPRAY_PRINT_TOKENS
std::cout << token << " token len:" << std::string(token).size() << "\n";
#endif
tokens.push_back(token);
token = std::strtok(NULL, delim);
}
if (tokens.size()) parseLineTokens(ply_path, tokens);
}
infile.close();
// apply transformation matrix
for (auto& d : (*domains_out)) {
glm::vec4 min = d.transform * glm::vec4(d.object_aabb.bounds[0], 1.0f);
glm::vec4 max = d.transform * glm::vec4(d.object_aabb.bounds[1], 1.0f);
d.world_aabb.bounds[0] = glm::vec3(min);
d.world_aabb.bounds[1] = glm::vec3(max);
}
}
} // namespace spray
| 29.041551 | 80 | 0.572778 | hyungman |
3974218429c4050238314f3d62724d1d653797df | 10,436 | hpp | C++ | OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp | OpenAutoit/OpenAutoit | f58c98c6e2a706ba7f06dcbc08a54a5a6440063e | [
"MIT"
] | null | null | null | OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp | OpenAutoit/OpenAutoit | f58c98c6e2a706ba7f06dcbc08a54a5a6440063e | [
"MIT"
] | 6 | 2022-02-01T04:07:12.000Z | 2022-03-01T04:43:49.000Z | OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp | OpenAutoit/OpenAutoit | f58c98c6e2a706ba7f06dcbc08a54a5a6440063e | [
"MIT"
] | null | null | null | #pragma once
namespace OpenAutoIt
{
enum class TokenKind
{
NotAToken,
EndOfFile, // '\0'
NewLine, // '\n'
Comment, // ; Comment
VariableIdentifier, // $var
FunctionIdentifier, // my_func
/* Literals */
IntegerLiteral, // 123
FloatLiteral, // 0.123
StringLiteral, // "String"
/* Punctioation */
Comma, // ,
LParen, // (
RParen, // )
Dot, // .
LSquare, // [
RSquare, // ]
/* Macros */
// https://www.autoitscript.com/autoit3/docs/macros.htm
MK_AppDataCommonDir, // @AppDataCommonDir
MK_AppDataDir, // @AppDataDir
MK_AutoItExe, // @AutoItExe
MK_AutoItPID, // @AutoItPID
MK_AutoItVersion, // @AutoItVersion
MK_AutoItX64, // @AutoItX64
MK_COM_EventObj, // @COM_EventObj
MK_CommonFilesDir, // @CommonFilesDir
MK_Compiled, // @Compiled
MK_ComputerName, // @ComputerName
MK_ComSpec, // @ComSpec
MK_CPUArch, // @CPUArch
MK_CR, // @CR
MK_CRLF, // @CRLF
MK_DesktopCommonDir, // @DesktopCommonDir
MK_DesktopDepth, // @DesktopDepth
MK_DesktopDir, // @DesktopDir
MK_DesktopHeight, // @DesktopHeight
MK_DesktopRefresh, // @DesktopRefresh
MK_DesktopWidth, // @DesktopWidth
MK_DocumentsCommonDir, // @DocumentsCommonDir
MK_error, // @error
MK_exitCode, // @exitCode
MK_exitMethod, // @exitMethod
MK_extended, // @extended
MK_FavoritesCommonDir, // @FavoritesCommonDir
MK_FavoritesDir, // @FavoritesDir
MK_GUI_CtrlHandle, // @GUI_CtrlHandle
MK_GUI_CtrlId, // @GUI_CtrlId
MK_GUI_DragFile, // @GUI_DragFile
MK_GUI_DragId, // @GUI_DragId
MK_GUI_DropId, // @GUI_DropId
MK_GUI_WinHandle, // @GUI_WinHandle
MK_HomeDrive, // @HomeDrive
MK_HomePath, // @HomePath
MK_HomeShare, // @HomeShare
MK_HotKeyPressed, // @HotKeyPressed
MK_HOUR, // @HOUR
MK_IPAddress1, // @IPAddress1
MK_IPAddress2, // @IPAddress2
MK_IPAddress3, // @IPAddress3
MK_IPAddress4, // @IPAddress4
MK_KBLayout, // @KBLayout
MK_LF, // @LF
MK_LocalAppDataDir, // @LocalAppDataDir
MK_LogonDNSDomain, // @LogonDNSDomain
MK_LogonDomain, // @LogonDomain
MK_LogonServer, // @LogonServer
MK_MDAY, // @MDAY
MK_MIN, // @MIN
MK_MON, // @MON
MK_MSEC, // @MSEC
MK_MUILang, // @MUILang
MK_MyDocumentsDir, // @MyDocumentsDir
MK_NumParams, // @NumParams
MK_OSArch, // @OSArch
MK_OSBuild, // @OSBuild
MK_OSLang, // @OSLang
MK_OSServicePack, // @OSServicePack
MK_OSType, // @OSType
MK_OSVersion, // @OSVersion
MK_ProgramFilesDir, // @ProgramFilesDir
MK_ProgramsCommonDir, // @ProgramsCommonDir
MK_ProgramsDir, // @ProgramsDir
MK_ScriptDir, // @ScriptDir
MK_ScriptFullPath, // @ScriptFullPath
MK_ScriptLineNumber, // @ScriptLineNumber
MK_ScriptName, // @ScriptName
MK_SEC, // @SEC
MK_StartMenuCommonDir, // @StartMenuCommonDir
MK_StartMenuDir, // @StartMenuDir
MK_StartupCommonDir, // @StartupCommonDir
MK_StartupDir, // @StartupDir
MK_SW_DISABLE, // @SW_DISABLE
MK_SW_ENABLE, // @SW_ENABLE
MK_SW_HIDE, // @SW_HIDE
MK_SW_LOCK, // @SW_LOCK
MK_SW_MAXIMIZE, // @SW_MAXIMIZE
MK_SW_MINIMIZE, // @SW_MINIMIZE
MK_SW_RESTORE, // @SW_RESTORE
MK_SW_SHOW, // @SW_SHOW
MK_SW_SHOWDEFAULT, // @SW_SHOWDEFAULT
MK_SW_SHOWMAXIMIZED, // @SW_SHOWMAXIMIZED
MK_SW_SHOWMINIMIZED, // @SW_SHOWMINIMIZED
MK_SW_SHOWMINNOACTIVE, // @SW_SHOWMINNOACTIVE
MK_SW_SHOWNA, // @SW_SHOWNA
MK_SW_SHOWNOACTIVATE, // @SW_SHOWNOACTIVATE
MK_SW_SHOWNORMAL, // @SW_SHOWNORMAL
MK_SW_UNLOCK, // @SW_UNLOCK
MK_SystemDir, // @SystemDir
MK_TAB, // @TAB
MK_TempDir, // @TempDir
MK_TRAY_ID, // @TRAY_ID
MK_TrayIconFlashing, // @TrayIconFlashing
MK_TrayIconVisible, // @TrayIconVisible
MK_UserName, // @UserName
MK_UserProfileDir, // @UserProfileDir
MK_WDAY, // @WDAY
MK_WindowsDir, // @WindowsDir
MK_WorkingDir, // @WorkingDir
MK_YDAY, // @YDAY
MK_YEAR, // @YEAR
/* Preprocessor identifiers */
// https://www.autoitscript.com/autoit3/docs/intro/lang_directives.htm
// https://www.autoitscript.com/autoit3/docs/keywords/comments-start.htm
// TODO: Do we really need both variants as seperate tokens?
PP_CommentsStart, // #Comments-Start
PP_CommentsEnd, // #Comments-End
PP_CS, // #cs
PP_CE, // #ce
// https://www.autoitscript.com/autoit3/docs/keywords/include.htm
PP_Include, // #include
// https://www.autoitscript.com/autoit3/docs/keywords/include-once.htm
PP_IncludeOnce, // #include-once
// https://www.autoitscript.com/autoit3/docs/keywords/NoTrayIcon.htm
PP_NoTrayIcon, // #NoTrayIcon
// https://www.autoitscript.com/autoit3/docs/keywords/OnAutoItStartRegister.htm
PP_OnAutoItStartRegister, // #OnAutoitStartRegister
// https://www.autoitscript.com/autoit3/docs/keywords/pragma.htm
PP_Pragma, // #pragma
// https://www.autoitscript.com/autoit3/docs/keywords/RequireAdmin.htm
PP_RequireAdmin, // # RequireAdmin
/* Keywords */
// https://www.autoitscript.com/autoit3/docs/keywords.htm
// https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm
// https://www.autoitscript.com/autoit3/docs/keywords/Booleans.htm
KW_False, // False
KW_True, // True
// https://www.autoitscript.com/autoit3/docs/keywords/ContinueCase.htm
KW_ContinueCase, // ContinueCase
// https://www.autoitscript.com/autoit3/docs/keywords/ContinueLoop.htm
KW_ContinueLoop, // ContinueLoop
// https://www.autoitscript.com/autoit3/docs/keywords/Default.htm
KW_Default, // Default
// https://www.autoitscript.com/autoit3/docs/keywords/Dim.htm
KW_Dim, // Dim
KW_Local, // Local
KW_Global, // Global
KW_Const, // Const
// https://www.autoitscript.com/autoit3/docs/keywords/Do.htm
KW_Do, // Do
KW_Until, // Until
// https://www.autoitscript.com/autoit3/docs/keywords/Enum.htm
KW_Enum, // Enum
// https://www.autoitscript.com/autoit3/docs/keywords/Exit.htm
KW_Exit, // Exit
// https://www.autoitscript.com/autoit3/docs/keywords/ExitLoop.htm
KW_ExitLoop, // ExitLoop
// https://www.autoitscript.com/autoit3/docs/keywords/For.htm
KW_For, // For
KW_To, // To
KW_Step, // Step
KW_Next, // Next
// https://www.autoitscript.com/autoit3/docs/keywords/ForInNext.htm
KW_In, // In
// https://www.autoitscript.com/autoit3/docs/keywords/Func.htm
KW_Func, // Func
KW_Return, // Return
KW_EndFunc, // EndFunc
// https://www.autoitscript.com/autoit3/docs/keywords/If.htm
KW_If, // If
KW_Then, // Then
KW_EndIf, // EndIf
// https://www.autoitscript.com/autoit3/docs/keywords/IfElseEndIf.htm
KW_ElseIf, // ElseIf
KW_Else, // Else
// https://www.autoitscript.com/autoit3/docs/keywords/Null.htm
KW_Null, // Null
// https://www.autoitscript.com/autoit3/docs/keywords/ReDim.htm
KW_ReDim, // ReDim
// https://www.autoitscript.com/autoit3/docs/keywords/Select.htm
KW_Select, // Select
KW_Case, // Case
KW_EndSelect, // EndSelect
// https://www.autoitscript.com/autoit3/docs/keywords/Static.htm
KW_Static, // Static
// https://www.autoitscript.com/autoit3/docs/keywords/Switch.htm
KW_Switch, // Switch
KW_EndSwitch, // EndSwitch
// https://www.autoitscript.com/autoit3/docs/keywords/Volatile.htm
KW_Volatile, // Volatile
// https://www.autoitscript.com/autoit3/docs/keywords/While.htm
KW_While, // While
KW_WEnd, // WEnd
// https://www.autoitscript.com/autoit3/docs/keywords/With.htm
KW_With, // With
KW_EndWith, // EndWith
// https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm
KW_And, // And
KW_Or, // Or
KW_Not, // Not
/* Operator */
// https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm
OP_Equals, // = (Note includes assignment and case insensitive comparision)
OP_PlusEquals, // +=
OP_MinusEquals, // -=
OP_MultiplyEquals, // *=
OP_DivideEquals, // /=
OP_Concatenate, // &
OP_ConcatenateEquals, // &=
OP_Plus, // +
OP_Minus, // -
OP_Multiply, // *
OP_Divide, // /
OP_Raise, // ^
OP_EqualsEquals, // ==
OP_NotEqual, // <>
OP_GreaterThan, // >
OP_GreaterThanEqual, // >=
OP_LessThan, // <
OP_LessThanEqual, // <=
OP_TernaryIf, // ?
OP_TernaryElse, // :
};
} // namespace OpenAutoIt
| 41.412698 | 94 | 0.542353 | OpenAutoit |
3976a580c60f6c867eaa81ee34c727b5c0186dbd | 2,118 | cxx | C++ | STEER/STEERBase/AliGenEposEventHeader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | STEER/STEERBase/AliGenEposEventHeader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | STEER/STEERBase/AliGenEposEventHeader.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/*
* AliGenEposEventHeader.h
*
* Header for EPOS generated event.
*
* Author: Piotr Ostrowski
*/
#include "AliGenEposEventHeader.h"
ClassImp(AliGenEposEventHeader)
AliGenEposEventHeader::AliGenEposEventHeader(const char* name):
AliGenEventHeader(name),
fBimevt(0),
fPhievt(0),
fKolevt(0),
fKoievt(0),
fPmxevt(0),
fEgyevt(0),
fNpjevt(0),
fNtgevt(0),
fNpnevt(0),
fNppevt(0),
fNtnevt(0),
fNtpevt(0),
fJpnevt(0),
fJppevt(0),
fJtnevt(0),
fJtpevt(0),
fXbjevt(0),
fQsqevt(0),
fNglevt(0),
fZppevt(0),
fZptevt(0)
{
// Constructor
}
AliGenEposEventHeader::AliGenEposEventHeader() : fBimevt(0),
fPhievt(0),
fKolevt(0),
fKoievt(0),
fPmxevt(0),
fEgyevt(0),
fNpjevt(0),
fNtgevt(0),
fNpnevt(0),
fNppevt(0),
fNtnevt(0),
fNtpevt(0),
fJpnevt(0),
fJppevt(0),
fJtnevt(0),
fJtpevt(0),
fXbjevt(0),
fQsqevt(0),
fNglevt(0),
fZppevt(0),
fZptevt(0)
{
// Default constructor
}
| 25.518072 | 76 | 0.531161 | AllaMaevskaya |
397909e5ff617b46401a0c2a6bf3af3550b1f4c6 | 344 | cpp | C++ | Problemset/climbing-stairs/climbing-stairs.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2020-10-06T01:06:45.000Z | 2020-10-06T01:06:45.000Z | Problemset/climbing-stairs/climbing-stairs.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | null | null | null | Problemset/climbing-stairs/climbing-stairs.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2021-11-17T13:52:51.000Z | 2021-11-17T13:52:51.000Z |
// @Title: 爬楼梯 (Climbing Stairs)
// @Author: Singularity0909
// @Date: 2020-06-11 21:10:10
// @Runtime: 0 ms
// @Memory: 5.6 MB
class Solution {
public:
int ans[50] = { 0 };
int climbStairs(int n) {
if (n <= 3)
return n;
return ans[n] ? ans[n] : ans[n] = climbStairs(n - 1) + climbStairs(n - 2);
}
};
| 19.111111 | 82 | 0.52907 | Singularity0909 |
397adea56a014b5fc6911d96ffdb6695d6a84410 | 2,181 | hpp | C++ | VcppBits/Settings/SettingsException.hpp | faesong/vcppbits | 9ad70f8e398110df48e4e2640a06fca09ef994f9 | [
"MIT"
] | null | null | null | VcppBits/Settings/SettingsException.hpp | faesong/vcppbits | 9ad70f8e398110df48e4e2640a06fca09ef994f9 | [
"MIT"
] | null | null | null | VcppBits/Settings/SettingsException.hpp | faesong/vcppbits | 9ad70f8e398110df48e4e2640a06fca09ef994f9 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright 2015-2020 Vitalii Minnakhmetov <restlessmonkey@ya.ru>
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
#define VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
#include <string>
#include <stdexcept>
#include "VcppBits/Settings/SettingsStringUtils.hpp"
namespace VcppBits {
class SettingsException : std::exception {
public:
enum TYPE { ALREADY_LOADED, NOT_FOUND, OUT_OF_RANGE };
SettingsException (const std::string &setting_name, TYPE t)
: settingName(setting_name),
type (t) {
}
~SettingsException () throw () {}
const std::string& getFullDescription () const {
_errorMessage = std::string("Setting Error ")
+ SettingsStringUtils::toString(this->type) + ": \""
+ settingName + "\"";
return _errorMessage;
}
const char *what () const throw() {
return this->getFullDescription().c_str();
}
const std::string settingName;
mutable std::string _errorMessage;
const TYPE type;
};
} // namespace VcppBits
#endif // VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
| 34.619048 | 76 | 0.727648 | faesong |
302fe2d3f3f102b03543aea9ee36bd7b982fb4a3 | 8,462 | cpp | C++ | ConnectOptionDialog.cpp | hyo0913/MQTT-Client-with-QMQTT | d9974d755dcc4f16c1e89b426c45be3854bcdbb5 | [
"MIT"
] | 1 | 2021-02-10T08:56:12.000Z | 2021-02-10T08:56:12.000Z | ConnectOptionDialog.cpp | hyo0913/MQTT-Client-using-qmqtt | d9974d755dcc4f16c1e89b426c45be3854bcdbb5 | [
"MIT"
] | null | null | null | ConnectOptionDialog.cpp | hyo0913/MQTT-Client-using-qmqtt | d9974d755dcc4f16c1e89b426c45be3854bcdbb5 | [
"MIT"
] | null | null | null | #include "ConnectOptionDialog.h"
#include "ui_ConnectOptionDialog.h"
#include "QFileDialog"
#include "QApplication"
ConnectOptionDialog::ConnectOptionDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ConnectOptionDialog)
{
ui->setupUi(this);
connect(ui->checkBoxWillFlag, SIGNAL(toggled(bool)), this, SLOT(willFlagToggled(bool)));
willFlagToggled(false);
connect(ui->checkBoxUserNameFlag, SIGNAL(toggled(bool)), this, SLOT(userNameFlagToggled(bool)));
userNameFlagToggled(false);
connect(ui->checkBoxAutoReconnect, SIGNAL(toggled(bool)), this, SLOT(autoReconnectToggled(bool)));
autoReconnectToggled(false);
connect(ui->checkBoxSsl, SIGNAL(toggled(bool)), this, SLOT(useSslToggled(bool)));
useSslToggled(false);
connect(ui->toolButtonCertifiacte, SIGNAL(clicked(bool)), this, SLOT(btnCertificateClicked()));
connect(ui->toolButtonPrivateKey, SIGNAL(clicked(bool)), this, SLOT(btnPriavteKeyClicked()));
}
ConnectOptionDialog::~ConnectOptionDialog()
{
delete ui;
}
bool ConnectOptionDialog::needWebsocket() const
{
bool result = false;
if( ui->comboBoxNetwork->currentIndex() == 1 )
{
result = true;
}
return result;
}
quint32 ConnectOptionDialog::port() const
{
return ui->spinBoxPort->value();
}
bool ConnectOptionDialog::cleanSession() const
{
return ui->checkBoxCleanSession->isChecked();
}
bool ConnectOptionDialog::willFlag() const
{
return ui->checkBoxWillFlag->isChecked();
}
bool ConnectOptionDialog::willQosFlag() const
{
return ui->checkBoxWillQoS->isChecked();
}
const QString ConnectOptionDialog::willTopic() const
{
return ui->lineEditWillTopic->text();
}
const QByteArray ConnectOptionDialog::willMessage() const
{
return ui->lineEditWillMessage->text().toUtf8();
}
quint8 ConnectOptionDialog::willQoS() const
{
return static_cast<quint8>(ui->spinBoxWillQoS->value());
}
bool ConnectOptionDialog::willRetainFlag() const
{
return ui->checkBoxWillRetain->isChecked();
}
bool ConnectOptionDialog::userNameFlag() const
{
return ui->checkBoxUserNameFlag->isChecked();
}
const QString ConnectOptionDialog::userName() const
{
return ui->lineEditUserName->text();
}
bool ConnectOptionDialog::passwordFlag() const
{
return ui->checkBoxPasswordFlag->isChecked();
}
const QByteArray ConnectOptionDialog::password() const
{
return ui->lineEditPassword->text().toUtf8();
}
quint16 ConnectOptionDialog::keepAlive() const
{
return static_cast<quint16>(ui->spinBoxKeepAlive->value());
}
bool ConnectOptionDialog::autoReconnect() const
{
return ui->checkBoxAutoReconnect->isChecked();
}
int ConnectOptionDialog::autoReconnectInterval() const
{
return ui->spinBoxAutoReconnectInterval->value();
}
bool ConnectOptionDialog::useSsl() const
{
return ui->checkBoxSsl->isChecked();
}
QSslCertificate ConnectOptionDialog::certificate() const
{
// QSslCertificate result;
// QString certFileName = ui->lineEditCertifiacte->text();
// if( certFileName.isEmpty() ) return QSslCertificate();
// QFile file(certFileName);
// if( file.open(QIODevice::ReadOnly) )
// {
// QByteArray data = file.readAll();
// file.close();
// if( certFileName.contains(".pem") )
// {
// result = QSslCertificate(data, QSsl::Pem);
// }
// else if( certFileName.contains(".der") )
// {
// result = QSslCertificate(data, QSsl::Der);
// }
// }
// return result;
QList<QSslCertificate> lstCerts;
QString certFileName = ui->lineEditCertifiacte->text();
if( certFileName.isEmpty() ) return QSslCertificate();
lstCerts = QSslCertificate::fromPath(certFileName);
if( lstCerts.count() <= 0 ) return QSslCertificate();
return lstCerts.first();
}
QSslKey ConnectOptionDialog::privateKey() const
{
QSslKey result;
QString keyFileName = ui->lineEditPrivateKey->text();
if( keyFileName.isEmpty() ) return QSslKey();
QFile file(keyFileName);
if( file.open(QIODevice::ReadOnly) )
{
result = QSslKey(file.readAll(), QSsl::Rsa);
}
return result;
}
bool ConnectOptionDialog::ignoreSelfSigned() const
{
return ui->checkBoxIgnoreSelfSigned->isChecked();
}
void ConnectOptionDialog::setEditable(bool editable)
{
ui->labelNetwork->setEnabled(editable);
ui->comboBoxNetwork->setEnabled(editable);
ui->labelPort->setEnabled(editable);
ui->spinBoxPort->setEnabled(editable);
ui->checkBoxCleanSession->setEnabled(editable);
ui->checkBoxWillFlag->setEnabled(editable);
ui->labelWillTopic->setEnabled(editable);
ui->lineEditWillTopic->setEnabled(editable);
ui->labelWillMessage->setEnabled(editable);
ui->lineEditWillMessage->setEnabled(editable);
ui->checkBoxWillQoS->setEnabled(editable);
ui->spinBoxWillQoS->setEnabled(editable);
ui->checkBoxWillRetain->setEnabled(editable);
ui->checkBoxUserNameFlag->setEnabled(editable);
ui->lineEditUserName->setEnabled(editable);
ui->checkBoxPasswordFlag->setEnabled(editable);
ui->lineEditPassword->setEnabled(editable);
ui->labelKeepAlive->setEnabled(editable);
ui->spinBoxKeepAlive->setEnabled(editable);
ui->labelKeepAliveSec->setEnabled(editable);
ui->checkBoxAutoReconnect->setEnabled(editable);
ui->labelAutoReconnectInterval->setEnabled(editable);
ui->spinBoxAutoReconnectInterval->setEnabled(editable);
ui->labelAutoReconnectIntervalSec->setEnabled(editable);
ui->checkBoxSsl->setEnabled(editable);
ui->labelCertificate->setEnabled(editable);
ui->lineEditCertifiacte->setEnabled(editable);
ui->toolButtonCertifiacte->setEnabled(editable);
ui->labelPrivateKey->setEnabled(editable);
ui->lineEditPrivateKey->setEnabled(editable);
ui->toolButtonPrivateKey->setEnabled(editable);
ui->checkBoxIgnoreSelfSigned->setEnabled(editable);
if( editable )
{
willFlagToggled(ui->checkBoxWillFlag->isChecked());
userNameFlagToggled(ui->checkBoxUserNameFlag->isChecked());
autoReconnectToggled(ui->checkBoxAutoReconnect->isChecked());
useSslToggled(ui->checkBoxSsl->isChecked());
}
}
void ConnectOptionDialog::willFlagToggled(bool toggled)
{
if( toggled == false )
{
ui->checkBoxWillQoS->setChecked(false);
ui->checkBoxWillRetain->setChecked(false);
}
ui->labelWillTopic->setEnabled(toggled);
ui->labelWillMessage->setEnabled(toggled);
ui->lineEditWillTopic->setEnabled(toggled);
ui->lineEditWillMessage->setEnabled(toggled);
ui->checkBoxWillQoS->setEnabled(toggled);
ui->spinBoxWillQoS->setEnabled(toggled);
ui->checkBoxWillRetain->setEnabled(toggled);
}
void ConnectOptionDialog::userNameFlagToggled(bool toggled)
{
if( toggled == false )
{
ui->checkBoxPasswordFlag->setChecked(false);
}
ui->checkBoxPasswordFlag->setEnabled(toggled);
ui->lineEditPassword->setEnabled(toggled);
}
void ConnectOptionDialog::autoReconnectToggled(bool toggled)
{
ui->labelAutoReconnectInterval->setEnabled(toggled);
ui->spinBoxAutoReconnectInterval->setEnabled(toggled);
ui->labelAutoReconnectIntervalSec->setEnabled(toggled);
}
void ConnectOptionDialog::useSslToggled(bool toggled)
{
ui->labelCertificate->setEnabled(toggled);
ui->lineEditCertifiacte->setEnabled(toggled);
ui->toolButtonCertifiacte->setEnabled(toggled);
ui->labelPrivateKey->setEnabled(toggled);
ui->lineEditPrivateKey->setEnabled(toggled);
ui->toolButtonPrivateKey->setEnabled(toggled);
ui->checkBoxIgnoreSelfSigned->setEnabled(toggled);
}
void ConnectOptionDialog::btnCertificateClicked()
{
QFileDialog dialog(this, "Certificate", QApplication::applicationDirPath(), "Certificate (*.pem *.der)");
if( dialog.exec() )
{
ui->lineEditCertifiacte->setText(dialog.selectedFiles().first());
}
}
void ConnectOptionDialog::btnPriavteKeyClicked()
{
QFileDialog dialog(this, "Private Key", QApplication::applicationDirPath(), "Private Key (*.pem)");
if( dialog.exec() )
{
ui->lineEditPrivateKey->setText(dialog.selectedFiles().first());
}
}
| 28.979452 | 110 | 0.69109 | hyo0913 |
3030085cec3c16ba6b029381746dd0a63baff54c | 1,446 | cc | C++ | test/config_test.cc | lilialexlee/kit | 94492e04832749fcdfb7f9fb8a778bb949d5e7d6 | [
"MIT"
] | 1 | 2015-09-22T15:33:30.000Z | 2015-09-22T15:33:30.000Z | test/config_test.cc | lilialexlee/kit | 94492e04832749fcdfb7f9fb8a778bb949d5e7d6 | [
"MIT"
] | null | null | null | test/config_test.cc | lilialexlee/kit | 94492e04832749fcdfb7f9fb8a778bb949d5e7d6 | [
"MIT"
] | null | null | null | /*
* config_test.cc
*
*/
#include "util/config.h"
#include <iostream>
int main() {
kit::Config config;
config.Init("./test/example_conf");
std::string str_value;
int ret = config.GetStr("str", &str_value);
if (ret == 0) {
std::cout << "get str: " << str_value << "\n";
} else {
std::cerr << "get str failed.\n";
}
std::vector<std::string> str_values;
ret = config.GetStrs("strs", &str_values);
if (ret == 0) {
std::cout << "get strs:";
for (size_t i = 0; i < str_values.size(); ++i) {
std::cout << " " << str_values[i];
}
std::cout << "\n";
} else {
std::cerr << "get strs failed.\n";
}
int int_value;
ret = config.GetInt("int", &int_value);
if (ret == 0) {
std::cout << "get int: " << int_value << "\n";
} else {
std::cerr << "get int failed.\n";
}
std::vector<int> int_values;
ret = config.GetInts("ints", &int_values);
if (ret == 0) {
std::cout << "get ints:";
for (size_t i = 0; i < int_values.size(); ++i) {
std::cout << " " << int_values[i];
}
std::cout << "\n";
} else {
std::cerr << "get ints failed.\n";
}
ret = config.GetStr("not_exist", &str_value);
if (ret == 0) {
std::cerr << "get not exist config.\n";
}
ret = config.GetStr("comments", &str_value);
if (ret == 0) {
std::cerr << "get not exist config.\n";
}
return 0;
}
| 21.909091 | 53 | 0.502766 | lilialexlee |
30315f2c2da15598ac8a5ff4725bec76120052dd | 2,307 | hxx | C++ | src/tcl_iface/array.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/tcl_iface/array.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | null | null | null | src/tcl_iface/array.hxx | AltSysrq/Abendstern | 106e1ad2457f7bfd90080eecf49a33f6079f8e1e | [
"BSD-3-Clause"
] | 1 | 2022-01-29T11:54:41.000Z | 2022-01-29T11:54:41.000Z | /**
* @file
* @author Jason Lingle
* @brief Makes C automatic/static arrays accessible to trusted Tcl.
*/
/*
* array.hxx
* Make C arrays accessible to trusted Tcl.
*
* Created on: 12.07.2010
* Author: jason
*/
#ifndef ARRAY_HXX_
#define ARRAY_HXX_
#include <stdexcept>
#include <exception>
#include "src/core/aobject.hxx"
/** Represents an automatically-allocated array of fixed
* size. Tcl can also create them, in which case the data
* is automatically deleted.
* Uses of this in the definition must always be C++-outgoing,
* immediate, and steal.
*/
template<typename T, unsigned S>
class StaticArray: public AObject {
T* data;
bool del;
public:
/** Tcl constructor */
StaticArray() : data(new T[S]), del(true) {}
/** Construct the array on the given array */
StaticArray(T* d) : data(d), del(false) {}
virtual ~StaticArray() { if (del) delete[] data; }
operator T*() { return data; }
/** Array read */
T at(unsigned i) {
if (i>=0 && i<S) return data[i];
throw std::range_error("Out of bounds");
}
/** Array set */
T set(unsigned i, T t) {
if (i>=0 && i<S) return data[i]=t;
throw std::range_error("Out of bounds");
}
/** Array size */
unsigned size() { return S; }
/** Equality is determined solely by comparing the pointers. */
bool eq(StaticArray<T,S>* other) { return data==other->data; }
};
/** Represents a dynamically-allocated array.
*
* The glue
* definition should ensure that Tcl always has control
* over this class. Tcl is responsible for knowing whether
* to delete the contents.
*
* The array does not keep track of allocation size.
* If Tcl "allocates" an array of size 0, a NULL array
* is actually created.
*/
template<typename T>
class DynArray: public AObject {
T* data;
public:
/** Constructs a DynArray on the given array */
DynArray(T* d) : data(d) {}
/** Allocates an array of the given size */
explicit DynArray(unsigned sz) : data(sz? new T[sz] : 0) {}
operator T*() { return data; }
T at(unsigned i) { return data[i]; } ///< Array read
T set(unsigned i, T t) { return data[i]=t; } ///< Array write
bool eq(DynArray<T>* other) { return other->data==data; } ///< Pointer equality
void del() { delete[] data; } ///< Deallocation
};
#endif /* ARRAY_HXX_ */
| 24.806452 | 81 | 0.647161 | AltSysrq |
30351cdc1536feb813463363d184c60765f63aa0 | 799 | cpp | C++ | 20-Valid_Parentheses.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | 20-Valid_Parentheses.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | 20-Valid_Parentheses.cpp | elsdrium/LeetCode-practice | a3b1fa5dd200155a636d36cd570e2454f7194e10 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isValid(string s) {
list<char> stack;
for( char c : s ) {
switch ( c ) {
case '(':
case '{':
case '[':
stack.push_back(c);
break;
case ')':
if ( stack.back() != '(' ) return false;
stack.pop_back();
break;
case '}':
if ( stack.back() != '{' ) return false;
stack.pop_back();
break;
case ']':
if ( stack.back() != '[' ) return false;
stack.pop_back();
break;
}
}
return stack.empty();
}
};
| 27.551724 | 60 | 0.307885 | elsdrium |
303880210283d85be75660b6f91578dee964ab52 | 4,210 | cpp | C++ | 002_disparity_panorama.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | 002_disparity_panorama.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | 002_disparity_panorama.cpp | DreamVu/Code-Samples | 2fccd9e649fbe7d9895df7d799cb1ec33066d1c2 | [
"MIT"
] | null | null | null | /*
CODE SAMPLE # 002: Disparity panorama
This code will grab the basic stereo panoramas (left and right images) and ALSO the Disparity panorama, and all these 3 images are displayed in an opencv window
>>>>>> Compile this code using the following command....
g++ 002_disparity_panorama.cpp ../lib/libPAL.so `pkg-config --libs --cflags opencv` -g -o 002_disparity_panorama.out -I../include/ -lv4l2 -lpthread -std=c++11
>>>>>> Execute the binary file by typing the following command...
./002_disparity_panorama.out
>>>>>> KEYBOARD CONTROLS:
ESC key closes the window
Press v/V key to toggle the vertical flip of panorama
Press f/F to toggle filter rgb property.
Press d/D to toggle fast depth property
Press r/R to toggle near range property
*/
# include <stdio.h>
# include <opencv2/opencv.hpp>
# include <chrono>
# include <bits/stdc++.h>
# include "PAL.h"
using namespace cv;
using namespace std;
using namespace std::chrono;
int main(int argc, char *argv[])
{
namedWindow("PAL Disparity Panorama", WINDOW_NORMAL); // Create a window for display.
int width, height;
if (PAL::Init(width, height, -1) != PAL::SUCCESS) //Connect to the PAL camera
{
printf("Init failed\n");
return 1;
}
PAL::CameraProperties data;
PAL::Acknowledgement ack = PAL::LoadProperties("../Explorer/SavedPalProperties.txt", &data);
if(ack != PAL::SUCCESS)
{
printf("Error Loading settings\n");
}
PAL::CameraProperties prop;
unsigned int flag = PAL::MODE;
flag = flag | PAL::FD;
flag = flag | PAL::NR;
flag = flag | PAL::FILTER_SPOTS;
flag = flag | PAL::VERTICAL_FLIP;
prop.mode = PAL::Mode::FAST_DEPTH; // The other available option is PAL::Mode::HIGH_QUALITY_DEPTH
prop.fd = 1;
prop.nr = 0;
prop.filter_spots = 1;
prop.vertical_flip =0;
PAL::SetCameraProperties(&prop, &flag);
bool isDisparityNormalized = true;
//width and height are the dimensions of each panorama.
//Each of the panoramas are displayed at quarter their original resolution.
//Since the left+right+disparity are vertically stacked, the window height should be thrice the quarter-height
resizeWindow("PAL Disparity Panorama", width / 4, (height / 4) * 3);
int key = ' ';
printf("Press ESC to close the window\n");
printf("Press v/V key to toggle the vertical flip of panorama\n");
printf("Press f/F to toggle filter rgb property.\n");
printf("Press d/D to toggle fast depth property\n");
printf("Press r/R to toggle near range property\n");
size_t currentResolution = 0;
bool flip = false;
bool filter_spots = true;
bool nr = false;
bool fd = true;
//27 = esc key. Run the loop until the ESC key is pressed
while (key != 27)
{
PAL::Image left, right, depth, disparity;
PAL::GrabFrames(&left, &right, &depth);
Mat output;
//Convert PAL::Image to Mat
Mat l = Mat(left.rows, left.cols, CV_8UC3, left.Raw.u8_data);
Mat r = Mat(right.rows, right.cols, CV_8UC3, right.Raw.u8_data);
Mat d = Mat(depth.rows, depth.cols, CV_32FC1, depth.Raw.f32_data);
d.convertTo(d, CV_8UC1);
cvtColor(d, d, cv::COLOR_GRAY2BGR);
//Vertical concatenation of temp and disparity into the final output
vconcat(l, d, output);
//Display the final output image
imshow("PAL Disparity Panorama", output);
//Wait for the keypress - with a timeout of 1 ms
key = waitKey(1) & 255;
if (key == 'v' || key == 'V')
{
PAL::CameraProperties prop;
flip = !flip;
prop.vertical_flip = flip;
unsigned int flags = PAL::VERTICAL_FLIP;
PAL::SetCameraProperties(&prop, &flags);
}
if (key == 'f' || key == 'F')
{
PAL::CameraProperties prop;
filter_spots = !filter_spots;
prop.filter_spots = filter_spots;
unsigned int flags = PAL::FILTER_SPOTS;
PAL::SetCameraProperties(&prop, &flags);
}
if(key == 'd' || key == 'D')
{
PAL::CameraProperties prop;
fd = !fd;
prop.fd = fd;
unsigned int flags = PAL::FD;
PAL::SetCameraProperties(&prop, &flags);
}
if(key == 'r' || key == 'R')
{
PAL::CameraProperties prop;
nr = !nr;
prop.nr = nr;
unsigned int flags = PAL::NR;
PAL::SetCameraProperties(&prop, &flags);
}
}
printf("exiting the application\n");
PAL::Destroy();
return 0;
}
| 26.3125 | 162 | 0.676485 | DreamVu |
303fb3bc53beaf5ea5c43b46203287c27e904f92 | 13,179 | hpp | C++ | sources/RenderSystem/spShaderClass.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/RenderSystem/spShaderClass.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/RenderSystem/spShaderClass.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2020-02-15T09:17:41.000Z | 2020-05-21T14:10:40.000Z | /*
* Shader class header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_SHADER_CLASS_H__
#define __SP_SHADER_CLASS_H__
#include "Base/spStandard.hpp"
#include "Base/spInputOutput.hpp"
#include "Base/spBaseObject.hpp"
#include "RenderSystem/spShaderConfigTypes.hpp"
namespace sp
{
namespace scene { class MaterialNode; }
namespace video
{
class Shader;
class ShaderResource;
class VertexFormat;
class ConstantBuffer;
/**
Build shader flags. This is used for the two static functions "ShaderClass::getShaderVersion" and "ShaderClass::build".
\since Version 3.2
*/
enum EBuildShaderFlags
{
SHADERBUILD_CG = 0x0002,
SHADERBUILD_GLSL = 0x0004,
SHADERBUILD_HLSL3 = 0x0008,
SHADERBUILD_HLSL5 = 0x0010,
SHADERBUILD_VERTEX = 0x0100,
SHADERBUILD_PIXEL = 0x0200,
SHADERBUILD_GEOMETRY = 0x0400,
SHADERBUILD_HULL = 0x0800,
SHADERBUILD_DOMAIN = 0x1000,
};
/**
C-pre-processor directives used for shading languages.
\todo Move this to a token parser/ lexer or something like that.
\since Version 3.3
*/
enum ECPPDirectives
{
CPPDIRECTIVE_NONE, //!< Invalid CPP directive.
CPPDIRECTIVE_INCLUDE_STRING, //!< #include "HeaderFile.h"
CPPDIRECTIVE_INCLUDE_BRACE, //!< #include <core>
};
//! Shader resource binding structure.
struct SShaderResourceBinding
{
SShaderResourceBinding() :
Resource (0),
AccessFlags (0)
{
}
SShaderResourceBinding(ShaderResource* BindResource, u8 BindAccessFlags) :
Resource (BindResource ),
AccessFlags (BindAccessFlags)
{
}
~SShaderResourceBinding()
{
}
/* Members */
ShaderResource* Resource;
u8 AccessFlags; //!< \see EResourceAccess
};
/**
Shader classes are used to link several shaders (Vertex-, Pixel shaders etc.) to one shader program.
Modern graphics hardware has the following shader stages:
- Vertex Shader
- Hull Shader (In OpenGL "Tessellation Control" Shader)
- Domain Shader (In OpenGL "Tessellation Evaluation" Shader)
- Geometry Shader
- Pixel Shader (In OpenGL "Fragment" Shader)
- Compute Shader (This is seperated from the graphics pipeline)
\ingroup group_shader
*/
class SP_EXPORT ShaderClass : public BaseObject
{
public:
virtual ~ShaderClass();
/* === Functions === */
/**
Binds the table with its shaders.
\param[in] Object Pointer to a MaterialNode object which shall be used for the shader callback if set.
*/
virtual void bind(const scene::MaterialNode* Object = 0) = 0;
//! Unbinds the table with its shaders.
virtual void unbind() = 0;
//! Compiles and links the whole shader class.
virtual bool compile() = 0;
/**
Adds the specified shader resource object.
\param[in] Resource Pointer to the shader resource object which is to be added.
\param[in] AccessFlags Specifies which access parts of the shader resources are to be added.
By default RESOURCE_ACCESS_READ_WRITE which means that the read- and write access resources will be added.
For HLSL the shader-resource-view (SRV) for read access and the unordered-access-view (UAV) for write access will be added.
Use RESOURCE_ACCESS_READ or RESOURCE_ACCESS_WRITE to only bind the SRV or UAV.
\note At first all textures are bound to a shader and then all shader resources.
This is order is important for the resource registers in the shader.
\see ShaderResource
\see addRWTexture
\see EResourceAccess
\since Version 3.3
*/
virtual void addShaderResource(ShaderResource* Resource, u8 AccessFlags = RESOURCE_ACCESS_READ_WRITE);
/**
Removes the specified shader resource object.
\see addShaderResource
\since Version 3.3
*/
virtual void removeShaderResource(ShaderResource* Resource);
virtual void clearShaderResources();
/**
Adds the specified shader R/W texture object.
\param[in] Tex Pointer to the R/W texture object which is to be added.
In this case the texture must be an R/W texture, i.e. from the type TEXTURE_*_RW.
\see addShaderResource
\see Texture
\see ETextureTypes
\since Version 3.3
*/
virtual void addRWTexture(Texture* Tex);
/**
Removes the specified shader R/W texture object.
\see addRWTexture
\since Version 3.3
*/
virtual void removeRWTexture(Texture* Tex);
virtual void clearRWTextures();
/* === Static functions === */
/**
Returns the shader version used for the specified flags.
\param[in] Flags Specifies the build flags. This can be a combination
of the values in the "EBuildShaderFlags" enumeration.
\return Shader version specified in the "EShaderVersions" enumeration.
If no version could be found "DUMMYSHADER_VERSION" will be returned.
\see EBuildShaderFlags
\since Version 3.2
*/
static EShaderVersions getShaderVersion(s32 Flags);
/**
Builds a complete shader class with the specified vertex-format,
shader source code and build flags.
This is particularly used internally for the deferred-renderer and post-processing effects.
\param[in] Name Specifies the shader name and is used for possible error messages.
\param[out] ShdClass Specifies the resulting shader class object.
\param[in] VertFmt Constant pointer to the vertex format used for the shader class.
\param[in] ShdBufferVertex Constant pointer to the vertex shader source code (std::list<io::stringc>).
\param[in] ShdBufferPixel Constant pointer to the pixel shader source code (std::list<io::stringc>).
\param[in] VertexMain Specifies the name of the vertex shader main function.
\param[in] PixelMain Specifies the name of the pixel shader main function.
\param[in] Flags Specifies the compilation flags. This can be one of the following values:
SHADERBUILD_CG, SHADERBUILD_GLSL, SHADERBUILD_HLSL3 or SHADERBUILD_HLSL5.
\return True if the shader class could be created successful.
\note This function always failes if "ShdBufferVertex" is null pointers.
\see VertexFormat
\see EBuildShaderFlags
\since Version 3.2
*/
static bool build(
const io::stringc &Name,
ShaderClass* &ShdClass,
const VertexFormat* VertFmt,
const std::list<io::stringc>* ShdBufferVertex,
const std::list<io::stringc>* ShdBufferPixel,
const io::stringc &VertexMain = "VertexMain",
const io::stringc &PixelMain = "PixelMain",
s32 Flags = SHADERBUILD_CG
);
/**
Loads a shader resource file and parses it for '#include' directives.
\param[in] FileSys Specifies the file system you want to use.
\param[in] Filename Specifies the filename of the shader resource which is to be loaded.
\param[in,out] ShaderBuffer Specifies the shader source code container which is to be filled.
\param[in] UseCg Specifies whether Cg shaders are to be used or not. By default false.
\since Version 3.3
*/
static bool loadShaderResourceFile(
io::FileSystem &FileSys, const io::stringc &Filename, std::list<io::stringc> &ShaderBuffer, bool UseCg = false
);
/**
Determines whether the given string has an '#include' directive.
\param[in] Line Specifies the string (or rather source code line) which is to be parsed.
\param[out] Filename Specifies the output filename which can be expressed between the
quotation marks inside the '#include' directive (e.g. #include "HeaderFile.h" -> will
result in the string "HeaderFile.h").
\return CPPDIRECTIVE_INCLUDE_STRING if the given string has an '#include' directive with a string,
CPPDIRECTIVE_INCLUDE_BRACE if the given string has an '#include' directive with brace or CPPDIRECTIVE_NONE otherwise.
\note This is actually only used by the "loadShaderResourceFile" function.
\see ECPPDirectives
\see loadShaderResourceFile
\since Version 3.3
*/
static ECPPDirectives parseIncludeDirective(const io::stringc &Line, io::stringc &Filename);
/* === Inline functions === */
/**
Sets the shader object callback function.
\param CallbackProc: Callback function in the form of
"void Callback(ShaderClass* Table, const scene::MaterialNode* Object);".
This callback normally is used to update the world- view matrix. In GLSL these matrices
are integrated but in HLSL you have to set these shader-constants manually.
*/
inline void setObjectCallback(const ShaderObjectCallback &CallbackProc)
{
ObjectCallback_ = CallbackProc;
}
/**
Sets the shader surface callback function.
\param[in] CallbackProc Specifies the surface callback function.
This callback normally is used to update texture settings for each surface.
\see ShaderSurfaceCallback
*/
inline void setSurfaceCallback(const ShaderSurfaceCallback &CallbackProc)
{
SurfaceCallback_ = CallbackProc;
}
inline Shader* getVertexShader() const
{
return VertexShader_;
}
inline Shader* getPixelShader() const
{
return PixelShader_;
}
inline Shader* getGeometryShader() const
{
return GeometryShader_;
}
inline Shader* getHullShader() const
{
return HullShader_;
}
inline Shader* getDomainShader() const
{
return DomainShader_;
}
inline Shader* getComputeShader() const
{
return ComputeShader_;
}
/**
Returns the list of all shader constant buffers used in the shader-class.
To get the list of all shader constant buffers used in a single shader object,
use the equivalent function of the respective shader.
\see Shader::getConstantBufferList
*/
inline const std::vector<ConstantBuffer*>& getConstantBufferList() const
{
return ConstBufferList_;
}
//! Returns the count of shader constant buffers.
inline size_t getConstantBufferCount() const
{
return ConstBufferList_.size();
}
/**
Returns the list of all shader resources.
\see SShaderResourceBinding
*/
inline const std::vector<SShaderResourceBinding>& getShaderResourceList() const
{
return ShaderResources_;
}
//! Returns the count of shader resources.
inline size_t getShaderResourceCount() const
{
return ShaderResources_.size();
}
//! Returns the list of all R/W textures.
inline const std::vector<Texture*>& getRWTextureList() const
{
return RWTextures_;
}
//! Returns the count of R/W textures.
inline size_t getRWTextureCount() const
{
return RWTextures_.size();
}
//! Returns true if the shader is a high level shader.
inline bool isHighLevel() const
{
return HighLevel_;
}
//! Returns true if the shader class has been compiled successfully.
inline bool valid() const
{
return CompiledSuccessfully_;
}
protected:
friend class Shader;
ShaderClass();
/* === Functions === */
void printError(const io::stringc &Message);
void printWarning(const io::stringc &Message);
/* === Members === */
ShaderObjectCallback ObjectCallback_;
ShaderSurfaceCallback SurfaceCallback_;
Shader* VertexShader_;
Shader* PixelShader_;
Shader* GeometryShader_;
Shader* HullShader_;
Shader* DomainShader_;
Shader* ComputeShader_;
std::vector<ConstantBuffer*> ConstBufferList_; //!< List of constant buffers of all shaders in the shader-class.
std::vector<SShaderResourceBinding> ShaderResources_;
std::vector<Texture*> RWTextures_;
bool HighLevel_;
bool CompiledSuccessfully_;
};
} // /namespace scene
} // /namespace sp
#endif
// ================================================================================
| 34.865079 | 131 | 0.629866 | rontrek |
303fd170eef267427715ae2218bd05a1403ec51d | 3,942 | hpp | C++ | examples/accumulator/accumulators/stubs/template_function_accumulator.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | examples/accumulator/accumulators/stubs/template_function_accumulator.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | examples/accumulator/accumulators/stubs/template_function_accumulator.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2012 Hartmut Kaiser
// Copyright (c) 2011 Bryce Adelstein-Lelbach
//
// 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)
#if !defined(HPX_EXAMPLES_STUBS_TEMPLATE_FUNCTION_ACCUMULATOR_JUL_12_2012_1056AM)
#define HPX_EXAMPLES_STUBS_TEMPLATE_FUNCTION_ACCUMULATOR_JUL_12_2012_1056AM
#include <hpx/hpx_fwd.hpp>
#include <hpx/include/components.hpp>
#include <hpx/include/applier.hpp>
#include <hpx/include/async.hpp>
#include "../server/template_function_accumulator.hpp"
namespace examples { namespace stubs
{
///////////////////////////////////////////////////////////////////////////
struct managed_accumulator
: hpx::components::stub_base<server::template_function_accumulator>
{
///////////////////////////////////////////////////////////////////////
/// Reset the accumulator's value to 0.
///
/// \note This function has fire-and-forget semantics. It will not wait
/// for the action to be executed. Instead, it will return
/// immediately after the action has has been dispatched.
static void reset_non_blocking(hpx::naming::id_type const& gid)
{
typedef server::template_function_accumulator::reset_action action_type;
hpx::apply<action_type>(gid);
}
/// Reset the accumulator's value to 0.
///
/// \note This function is fully synchronous.
static void reset_sync(hpx::naming::id_type const& gid)
{
typedef server::template_function_accumulator::reset_action action_type;
hpx::async<action_type>(gid).get();
}
///////////////////////////////////////////////////////////////////////
/// Add \p arg to the accumulator's value.
///
/// \note This function has fire-and-forget semantics. It will not wait
/// for the action to be executed. Instead, it will return
/// immediately after the action has has been dispatched.
template <typename T>
static void
add_non_blocking(hpx::naming::id_type const& gid, T arg)
{
typedef server::template_function_accumulator::add_action<T> action_type;
hpx::apply<action_type>(gid, arg);
}
/// Add \p arg to the accumulator's value.
///
/// \note This function is fully synchronous.
//[managed_accumulator_stubs_add_sync
template <typename T>
static void
add_sync(hpx::naming::id_type const& gid, T arg)
{
typedef typename server::template_function_accumulator::add_action<T> action_type;
hpx::async<action_type>(gid, arg).get();
}
///////////////////////////////////////////////////////////////////////
/// Asynchronously query the current value of the accumulator.
///
/// \returns This function returns an \a hpx::lcos::future. When the
/// value of this computation is needed, the get() method of
/// the future should be called. If the value is available,
/// get() will return immediately; otherwise, it will block
/// until the value is ready.
static hpx::lcos::future<double>
query_async(hpx::naming::id_type const& gid)
{
typedef server::template_function_accumulator::query_action action_type;
return hpx::async<action_type>(gid);
}
/// Query the current value of the accumulator.
///
/// \note This function is fully synchronous.
static double query_sync(hpx::naming::id_type const& gid)
{
// The following get yields control while the action is executed.
return query_async(gid).get();
}
};
}}
#endif
| 40.22449 | 94 | 0.58067 | kempj |
30492562f44dbe9294a88209c703116a098d00bd | 7,356 | cpp | C++ | srm 195 div1/FanFailure.cpp | emiliot/topcoder | c58e105424b484a4e5600bad2c58d664cdcae935 | [
"MIT"
] | null | null | null | srm 195 div1/FanFailure.cpp | emiliot/topcoder | c58e105424b484a4e5600bad2c58d664cdcae935 | [
"MIT"
] | null | null | null | srm 195 div1/FanFailure.cpp | emiliot/topcoder | c58e105424b484a4e5600bad2c58d664cdcae935 | [
"MIT"
] | null | null | null | // Paste me into the FileEdit configuration dialog
#include "assert.h"
#include "ctype.h"
#include "float.h"
#include "math.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "stdarg.h"
#include "time.h"
#include "algorithm"
#include "numeric"
#include "functional"
#include "utility"
#include "bitset"
#include "vector"
#include "list"
#include "set"
#include "map"
#include "queue"
#include "stack"
#include "string"
#include "sstream"
#include "iostream"
using namespace std;
#define all(v) (v).begin(), (v).end()
typedef long long i64;
template <class T> void make_unique(T& v) {sort(all(v)); v.resize(unique(all(v)) - v.begin());}
int memo[51][50001];
bool mark[51][50001];
const int INF = 0x3f3f3f3f;
int f(vector <int> &v, int low, int i, int cap){
if(i >= (int)v.size()){
return 0;
}
int &best = memo[i][cap];
if(mark[i][cap])return best;
mark[i][cap] = true;
best = f(v, low, i+1, cap);
if(cap - v[i] >= low){
best = max(best, f(v, low, i+1, cap - v[i]) + 1);
}
return best;
}
int g(vector <int> &v, int low, int i, int cap){
if(i >= (int)v.size()){
if(cap < low)return 0;
else return INF;
}
int &best = memo[i][cap];
if(mark[i][cap])return best;
mark[i][cap] = true;
best = g(v, low, i+1, cap);
best = min(best, g(v, low, i+1, cap - v[i]) + 1);
return best;
}
class FanFailure {
public:
vector <int> getRange( vector <int> capacities, int minCooling ) {
vector <int> res(2, 0);
int cap = 0;
for(int i=0, n=capacities.size(); i<n; ++i)
cap += capacities[i];
memset(mark, false, sizeof(mark));
res[0] = f(capacities, minCooling, 0, cap);
memset(mark, false, sizeof(mark));
res[1] = g(capacities, minCooling, 0, cap)-1;
return res;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << "{"; for (typename vector<T>::const_iterator vi=v.begin(); vi!=v.end(); ++vi) { if (vi != v.begin()) os << ","; os << " " << *vi; } os << " }"; return os; }
int verify_case(int casenum, const vector <int> &expected, const vector <int> &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum__) {
switch (casenum__) {
case 0: {
int capacities[] = {1,2,3};
int minCooling = 2;
int expected__[] = { 2, 1 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 1: {
int capacities[] = {8,5,6,7};
int minCooling = 22;
int expected__[] = { 0, 0 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 2: {
int capacities[] = {676, 11, 223, 413, 823, 122, 547, 187, 28};
int minCooling = 1000;
int expected__[] = { 7, 2 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
case 3: {
int capacities[] = {955, 96, 161, 259, 642, 242, 772, 369, 311, 785, 92, 991, 620, 394, 128, 774, 973, 94, 681, 771, 916, 373, 523, 100, 220, 993, 472, 798, 132, 361, 33, 362, 573, 624, 722, 520, 451, 231, 37, 921, 408, 170, 303, 559, 866, 412, 339, 757, 822, 192};
int minCooling = 3619;
int expected__[] = { 46, 30 };
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}
// custom cases
/* case 4: {
int capacities[] = ;
int minCooling = ;
int expected__[] = ;
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
/* case 5: {
int capacities[] = ;
int minCooling = ;
int expected__[] = ;
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
/* case 6: {
int capacities[] = ;
int minCooling = ;
int expected__[] = ;
clock_t start__ = clock();
vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling);
return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| 30.396694 | 277 | 0.592577 | emiliot |
304f206ea3efb19f7470a6edb5116fce5b896372 | 552 | hpp | C++ | src/Type.hpp | pawelprazak/jeff-native-agent | 1554a8f69d0f0ca719ae5a794564e0e155b82545 | [
"Apache-2.0"
] | 7 | 2017-12-10T16:37:18.000Z | 2021-01-19T06:33:23.000Z | src/Type.hpp | pawelprazak/jeff-native-agent | 1554a8f69d0f0ca719ae5a794564e0e155b82545 | [
"Apache-2.0"
] | 3 | 2016-01-13T13:39:50.000Z | 2016-02-19T18:08:38.000Z | src/Type.hpp | pawelprazak/jeff-native-agent | 1554a8f69d0f0ca719ae5a794564e0e155b82545 | [
"Apache-2.0"
] | 5 | 2015-12-08T09:03:10.000Z | 2019-07-29T16:13:13.000Z | #ifndef JEFF_NATIVE_AGENT_TYPE_HPP
#define JEFF_NATIVE_AGENT_TYPE_HPP
#include <jni.h>
#include <jvmti.h>
#include "Object.hpp"
class Type : Object {
public:
Type();
Type(const std::string signature);
virtual ~Type();
private:
const std::string signature;
public:
static const Type *const from(jvmtiEnv &jvmti, JNIEnv &jni, std::string signature);
static const Type *const from(jvmtiEnv &jvmti, JNIEnv &jni, char primitive_signature);
const std::string getSignature() const;
};
#endif //JEFF_NATIVE_AGENT_TYPE_HPP
| 19.034483 | 90 | 0.721014 | pawelprazak |
30534b9793b2207074a3d48925d19d11f017d241 | 142 | cpp | C++ | src/app/camera/camera.cpp | JonCG90/Goby | da1bfcea23c058427e6bad1c58f1cd5405fe4c5f | [
"MIT"
] | null | null | null | src/app/camera/camera.cpp | JonCG90/Goby | da1bfcea23c058427e6bad1c58f1cd5405fe4c5f | [
"MIT"
] | null | null | null | src/app/camera/camera.cpp | JonCG90/Goby | da1bfcea23c058427e6bad1c58f1cd5405fe4c5f | [
"MIT"
] | null | null | null | //
// camera.cpp
// Goby
//
// Created by Jonathan Graham on 8/18/19.
//
#include "camera.hpp"
namespace Goby
{
} // namespace Goby
| 10.142857 | 42 | 0.598592 | JonCG90 |
3054fbf14a79cbdc41baa36817c2127adc340035 | 12,908 | cpp | C++ | test/diamond_complex.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 1 | 2018-01-27T23:35:21.000Z | 2018-01-27T23:35:21.000Z | test/diamond_complex.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 2 | 2019-08-17T05:37:36.000Z | 2019-08-17T22:57:26.000Z | test/diamond_complex.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 1 | 2021-03-19T11:53:53.000Z | 2021-03-19T11:53:53.000Z | #include "io_count_fixture.hpp"
#include <boost/serialization/export.hpp>
#include <boost/serialization/map.hpp>
#include <boost/test/unit_test.hpp>
#define NVP(name) BOOST_SERIALIZATION_NVP(name)
using boost::serialization::make_nvp;
namespace {
// used to detect when base_diamond class is saved multiple times
int diamond_save_count = 0;
// used to detect when base_diamond class is loaded multiple times
int diamond_load_count = 0;
}
class EX1Level1
{
public:
EX1Level1() : i(0) {}
EX1Level1(int i) : i(i) { m[i] = "text"; }
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level1");
ar << BOOST_SERIALIZATION_NVP(i);
ar << BOOST_SERIALIZATION_NVP(m);
++diamond_save_count;
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level1");
ar >> BOOST_SERIALIZATION_NVP(i);
ar >> BOOST_SERIALIZATION_NVP(m);
++diamond_load_count;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
bool operator==(const EX1Level1& another) const
{
return i == another.i && m == another.m;
}
// make polymorphic by marking at least one function virtual
virtual ~EX1Level1(){};
private:
int i;
std::map<int, std::string> m;
};
// note: the default is for object tracking to be performed if and only
// if and object of the corresponding class is anywhere serialized
// through a pointer. In this example, that doesn't occur so
// by default, the shared EX1Level1 object wouldn't normally be tracked.
// This would leave to multiple save/load operation of the data in
// this shared EX1Level1 class. This wouldn't cause an error, but it would
// be a waste of time. So set the tracking behavior trait of the EX1Level1
// class to always track serialized objects of that class. This permits
// the system to detect and elminate redundent save/load operations.
// (It is concievable that this might someday be detected automatically
// but for now, this is not done so we have to rely on the programmer
// to specify this trait)
BOOST_CLASS_TRACKING(EX1Level1, track_always)
class EX1Level2_A : virtual public EX1Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level2_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level2_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level2_B : virtual public EX1Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level2_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level2_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level3_A : public EX1Level2_A, public EX1Level2_B
{
public:
EX1Level3_A() {}
EX1Level3_A(int i) : EX1Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level3_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level3_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level3_B : public EX1Level2_A, public EX1Level2_B
{
public:
EX1Level3_B() {}
EX1Level3_B(int) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level3_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level3_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX1Level4 : public EX1Level3_B
{
public:
EX1Level4() {}
EX1Level4(int i) : EX1Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX1Level4");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level3_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX1Level4");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level3_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level1
{
public:
EX2Level1() : i(0) {}
EX2Level1(int i) : i(i) { m[i] = "text"; }
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level1");
ar << BOOST_SERIALIZATION_NVP(i);
ar << BOOST_SERIALIZATION_NVP(m);
++diamond_save_count;
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level1");
ar >> BOOST_SERIALIZATION_NVP(i);
ar >> BOOST_SERIALIZATION_NVP(m);
++diamond_load_count;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
bool operator==(const EX2Level1& another) const
{
return i == another.i && m == another.m;
}
// make polymorphic by marking at least one function virtual
virtual ~EX2Level1(){};
private:
int i;
std::map<int, std::string> m;
};
// note: the default is for object tracking to be performed if and only
// if and object of the corresponding class is anywhere serialized
// through a pointer. In this example, that doesn't occur so
// by default, the shared EX2Level1 object wouldn't normally be tracked.
// This would leave to multiple save/load operation of the data in
// this shared EX2Level1 class. This wouldn't cause an error, but it would
// be a waste of time. So set the tracking behavior trait of the EX2Level1
// class to always track serialized objects of that class. This permits
// the system to detect and elminate redundent save/load operations.
// (It is concievable that this might someday be detected automatically
// but for now, this is not done so we have to rely on the programmer
// to specify this trait)
BOOST_CLASS_TRACKING(EX2Level1, track_always)
class EX2Level2_A : virtual public EX2Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level2_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level2_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level2_B : virtual public EX2Level1
{
public:
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level2_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level2_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level3_A : public EX2Level2_A, public EX2Level2_B
{
public:
EX2Level3_A() {}
EX2Level3_A(int i) : EX2Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level3_A");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level3_A");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level3_B : public EX2Level2_A, public EX2Level2_B
{
public:
EX2Level3_B() {}
EX2Level3_B(int i) : EX2Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level3_B");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level3_B");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A);
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
class EX2Level4 : public EX2Level3_B
{
public:
EX2Level4() {}
EX2Level4(int i) : EX2Level1(i) {}
template <class Archive>
void save(Archive& ar, const unsigned int /* file_version */) const
{
BOOST_TEST_MESSAGE("Saving EX2Level4");
ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level3_B);
}
template <class Archive>
void load(Archive& ar, const unsigned int /* file_version */)
{
BOOST_TEST_MESSAGE("Restoring EX2Level4");
ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level3_B);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
};
BOOST_CLASS_EXPORT(EX1Level4)
BOOST_CLASS_EXPORT(EX1Level3_A)
BOOST_CLASS_EXPORT(EX2Level3_A)
BOOST_CLASS_EXPORT(EX2Level4)
BOOST_FIXTURE_TEST_CASE(diamond_complex1, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX1Level3_A ex1L3a_save(3);
const EX1Level1* ex1L1_save = &ex1L3a_save;
{
output() << make_nvp("ex1L1", ex1L1_save);
}
EX1Level1* ex1L1_load;
{
input() >> make_nvp("ex1L1", ex1L1_load);
}
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex1L1_save == *ex1L1_load);
}
BOOST_FIXTURE_TEST_CASE(diamond_complex2, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX1Level4 ex1L4_save(3);
const EX1Level1* ex1L1_save = &ex1L4_save;
{
output() << make_nvp("ex1L1", ex1L1_save);
}
EX1Level1* ex1L1_load;
{
input() >> make_nvp("ex1L1", ex1L1_load);
}
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex1L1_save == *ex1L1_load);
}
BOOST_FIXTURE_TEST_CASE(diamond_complex3, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX2Level3_A ex2L3a_save(3);
const EX2Level1* ex2L1_save = &ex2L3a_save;
{
output() << make_nvp("ex2L1", ex2L1_save);
}
EX2Level1* ex2L1_load;
{
input() >> make_nvp("ex2L1", ex2L1_load);
}
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex2L1_save == *ex2L1_load);
}
BOOST_FIXTURE_TEST_CASE(diamond_complex4, io_count_fixture)
{
diamond_save_count = 0;
diamond_load_count = 0;
const EX2Level4 ex2L4_save(3);
const EX2Level1* ex2L1_save = &ex2L4_save;
{
output() << make_nvp("ex2L1", ex2L1_save);
}
EX2Level1* ex2L1_load;
{
input() >> make_nvp("ex2L1", ex2L1_load);
}
// {
// test_ostream ofs(testfile, TEST_STREAM_FLAGS);
// test_oarchive oa(ofs);
// oa << boost::serialization::make_nvp("ex2L1", ex2L1_save);
// }
// {
// test_istream ifs(testfile, TEST_STREAM_FLAGS);
// test_iarchive ia(ifs);
// ia >> boost::serialization::make_nvp("ex2L1", ex2L1_load);
// }
BOOST_CHECK(1 == diamond_save_count);
BOOST_CHECK(1 == diamond_load_count);
BOOST_CHECK(*ex2L1_save == *ex2L1_load);
}
| 29.47032 | 75 | 0.68353 | rwols |
305b0147381455dd98f6417efd6da68f5d915c91 | 2,275 | cpp | C++ | C++/Brute Force Password Cracker.cpp | CyanCoding/Brute-Force-Password-Cracker | dcc753618e1de8294b118721adca35f87eb2bfe7 | [
"MIT"
] | 30 | 2019-02-07T23:41:24.000Z | 2022-03-13T15:39:37.000Z | C++/Brute Force Password Cracker.cpp | CyanCoding/Brute-Force-Password-Cracker | dcc753618e1de8294b118721adca35f87eb2bfe7 | [
"MIT"
] | 3 | 2020-09-22T19:55:16.000Z | 2021-10-01T19:48:13.000Z | C++/Brute Force Password Cracker.cpp | CyanCoding/Brute-Force-Password-Cracker | dcc753618e1de8294b118721adca35f87eb2bfe7 | [
"MIT"
] | 28 | 2018-06-08T15:27:03.000Z | 2022-02-07T05:40:29.000Z | #include <iostream>
#include <string> // to_string
#include <iomanip> // setprecision
using namespace std;
bool stop = false;
long long amount = 0;
string password;
clock_t start;
const char Alphabet[62] = {
'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', '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'
};
string separateWithCommas(long long num) {
string s = to_string(num);
int thousands = s.length() - 3;
while (thousands > 0) {
s.insert(thousands, ",");
thousands -= 3;
}
return s;
}
void inline crack(unsigned int length, string current) {
if (length == 0 && stop == false) {
amount++;
if (amount % 10000000 == 0) {
cout << '\r' << separateWithCommas(amount) << " - " << current << " - " << separateWithCommas(amount / ((float)(clock() - start) / CLOCKS_PER_SEC)) << " p/sec";
cout.flush();
}
if (current == password) {
stop = true;
}
return;
}
if (stop == false) {
for (unsigned int i = 0; i < 62; i++) {
crack(length - 1, current + Alphabet[i]);
}
}
}
int main() {
// Greet the user
cout << "Welcome to CyanCoding's Brute Force Password Cracker!" << endl << endl;
cout << "What do you want your password to be? > ";
cin >> password;
cout << "\rAttempting to crack " << password << "..." << endl;
start = clock();
while (stop == false) {
static unsigned int pwLength = 1;
crack(pwLength, "");
pwLength++;
if (stop == true) {
break;
}
}
cout << "\rCyanCoding's C++ BFPC cracked the password \"" << password << "\" in " <<
separateWithCommas(amount) << " attempts and " << setprecision(2) << fixed <<
(float)(clock() - start) / CLOCKS_PER_SEC << " seconds." << endl << endl <<
"That's about " << setprecision(0) <<
separateWithCommas(amount / ((float)(clock() - start) / CLOCKS_PER_SEC)) <<
" passwords per second!" << endl << endl;
return 0;
}
| 30.333333 | 311 | 0.487912 | CyanCoding |
305e00e4be433b098a54686754f91b0d53e16b0f | 336 | hpp | C++ | include/mil/utils/index_sequence.hpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | include/mil/utils/index_sequence.hpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | include/mil/utils/index_sequence.hpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | #pragma once
#include <cstddef>
#include "detail/index_sequence.hpp"
namespace mil {
namespace utils {
template <std::size_t... Idx>
using index_sequnece = detail::index_sequnece<Idx...>;
template <std::size_t N>
using make_index_sequence = typename detail::make_index_sequence<N>::type;
} // namespace utils
} // namespace mil
| 18.666667 | 74 | 0.738095 | vhapiak |
30608a5bc5e5b05a736a10130fb51f16f51e84ee | 3,614 | cxx | C++ | FIT/FITcalib/AliFITCalibTimeEq.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | FIT/FITcalib/AliFITCalibTimeEq.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | FIT/FITcalib/AliFITCalibTimeEq.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for FIT calibration TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliFITCalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>
ClassImp(AliFITCalibTimeEq)
//________________________________________________________________
AliFITCalibTimeEq::AliFITCalibTimeEq():TNamed()
{
//
for(Int_t i=0; i<200; i++) {
fTimeEq[i] = 0; // Time Equalized for OCDB
fCFDvalue[i] = 0;
}
}
//________________________________________________________________
AliFITCalibTimeEq::AliFITCalibTimeEq(const char* name):TNamed()
{
//constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
for(Int_t i=0; i<200; i++) {
fTimeEq[i] = 0; // Time Equalized for OCDB
fCFDvalue[i] = 0;
}
}
//________________________________________________________________
AliFITCalibTimeEq::AliFITCalibTimeEq(const AliFITCalibTimeEq& calibda):TNamed(calibda)
{
// copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
((AliFITCalibTimeEq &) calibda).Copy(*this);
}
//________________________________________________________________
AliFITCalibTimeEq &AliFITCalibTimeEq::operator =(const AliFITCalibTimeEq& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
if (this != &calibda) (( AliFITCalibTimeEq &) calibda).Copy(*this);
return *this;
}
//________________________________________________________________
AliFITCalibTimeEq::~AliFITCalibTimeEq()
{
//
// destrictor
}
//________________________________________________________________
void AliFITCalibTimeEq::Reset()
{
//reset values
memset(fCFDvalue,0,200*sizeof(Float_t));
memset(fTimeEq,1,200*sizeof(Float_t));
}
//________________________________________________________________
void AliFITCalibTimeEq::Print(Option_t*) const
{
// print time values
printf("\n ---- PM Arrays ----\n\n");
printf(" Time delay CFD \n");
for (Int_t i=0; i<200; i++)
printf(" CFD %f diff %f \n",fCFDvalue[i],fTimeEq[i]);
}
| 31.982301 | 91 | 0.57969 | AllaMaevskaya |
30657cd12bea49e681cd2756206affac7f565829 | 4,202 | cpp | C++ | src/drive.cpp | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | 7 | 2021-05-13T07:43:10.000Z | 2022-01-09T12:18:48.000Z | src/drive.cpp | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | null | null | null | src/drive.cpp | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright 2016 Gleb Popov <6yearold@gmail.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.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <fcntl.h>
#include <sys/cdio.h>
#include <sys/ioctl.h>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusObjectPath>
#include <QUuid>
#include "bsdisks.h"
#include "drive.h"
Drive::Drive(const QString& devName)
: QDBusContext()
, m_deviceName(devName)
, m_dbusPath(QDBusObjectPath(UDisksDrives + devName))
{
}
const QDBusObjectPath Drive::getDbusPath() const
{
return m_dbusPath;
}
QString Drive::getDeviceName() const
{
return m_deviceName;
}
void Drive::setVendor(const QString& vendor)
{
m_Vendor = vendor;
}
void Drive::setRemovable(bool r)
{
isRemovable = r;
}
void Drive::addBlock(const TBlock& block)
{
qDebug() << "Disk " << getDeviceName() << " add block: " << block->getName();
m_blocks.push_back(block);
}
const TBlockVec Drive::getBlocks() const
{
return m_blocks;
}
void Drive::Eject(const QVariantMap& options)
{
if (!optical())
return;
int fd = open((QStringLiteral("/dev/") + getDeviceName()).toLocal8Bit().constData(), O_RDONLY);
if (fd < 0 && errno != ENXIO) {
QString errorMessage = ::strerror(errno);
connection().send(
message().createErrorReply("org.freedesktop.UDisks2.Error.Failed", errorMessage));
qDebug() << "Eject failed: " << errorMessage;
return;
}
::ioctl(fd, CDIOCALLOW);
int rc = ::ioctl(fd, CDIOCEJECT);
if (rc < 0) {
QString errorMessage = ::strerror(errno);
connection().send(
message().createErrorReply("org.freedesktop.UDisks2.Error.Failed", errorMessage));
qDebug() << "Eject failed: " << errorMessage;
return;
}
}
Configuration Drive::configuration() const
{
Configuration c;
return c;
}
bool Drive::optical() const
{
return getDeviceName().startsWith("cd");
}
QStringList Drive::mediaCompatibility() const
{
if (optical())
return {QStringLiteral("optical_cd")};
return QStringList();
}
QString Drive::vendor() const
{
return m_Vendor;
}
qulonglong Drive::driveSize() const
{
return size;
}
void Drive::setId(const QString& id)
{
m_Id = id;
}
QString Drive::id() const
{
return m_Id;
}
QString Drive::serial() const
{
return m_Duid.toString();
}
void Drive::setSize(qulonglong s)
{
size = s;
}
void Drive::setDuid(const QUuid& duid)
{
m_Duid = duid;
}
bool Drive::ejectable() const
{
return removable();
}
bool Drive::removable() const
{
return optical() || isRemovable;
}
bool Drive::mediaRemovable() const
{
return optical() || removable();
}
QString Drive::connectionBus() const
{
return QString();
}
| 24.011429 | 99 | 0.694669 | sizeofvoid |
3065e0634838c6a4728f0c0528a5fc7a269dc115 | 675 | cpp | C++ | src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp | TypeDefinition/cbtEngine | 9ddbc6a5436cc31efc475f6d1c37fade4a003c0d | [
"MIT"
] | null | null | null | src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp | TypeDefinition/cbtEngine | 9ddbc6a5436cc31efc475f6d1c37fade4a003c0d | [
"MIT"
] | null | null | null | src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp | TypeDefinition/cbtEngine | 9ddbc6a5436cc31efc475f6d1c37fade4a003c0d | [
"MIT"
] | null | null | null | // Include CBT
#include "cbtBufferLayout.h"
NS_CBT_BEGIN
cbtU32 GetByteSize(cbtBufferDataType _dataType)
{
switch (_dataType)
{
case cbtBufferDataType::CBT_S8:
case cbtBufferDataType::CBT_U8:
return 1;
case cbtBufferDataType::CBT_S16:
case cbtBufferDataType::CBT_U16:
case cbtBufferDataType::CBT_F16:
return 2;
case cbtBufferDataType::CBT_S32:
case cbtBufferDataType::CBT_U32:
case cbtBufferDataType::CBT_F32:
return 4;
case cbtBufferDataType::CBT_F64:
return 8;
default:
return 0;
}
}
NS_CBT_END | 24.107143 | 51 | 0.6 | TypeDefinition |
3068245fb2012c6185a50f5ed6d9c464cbf886c1 | 1,717 | cpp | C++ | control_app/joystick.cpp | houcy/wall-e-1 | b159d05b0afa343cb161f60ec98974bc2f063afd | [
"MIT"
] | 1 | 2021-05-05T14:11:03.000Z | 2021-05-05T14:11:03.000Z | control_app/joystick.cpp | houcy/wall-e-1 | b159d05b0afa343cb161f60ec98974bc2f063afd | [
"MIT"
] | null | null | null | control_app/joystick.cpp | houcy/wall-e-1 | b159d05b0afa343cb161f60ec98974bc2f063afd | [
"MIT"
] | null | null | null | #include "joystick.h"
#include "log.h"
#include <QTimer>
// Linux headers
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
/* Standard C++ API does not allow to read char device file in unblocking mode,
* so used Linux API
*/
#define JOYSTICK_FILE "/dev/input/js0"
#define READ_DATA_INTERVAL 50
Joystick::Joystick(QObject *parent) : QObject(parent)
{
if ((jsFile = open(JOYSTICK_FILE, O_RDONLY | O_NONBLOCK,
S_IRUSR | S_IRGRP | S_IROTH)) == -1)
{
critical("Failed to open joystick file %d: %s", errno,
strerror(errno));
return;
}
readDataTimer = new QTimer(this);
connect(readDataTimer, SIGNAL(timeout()), this,
SLOT(slotReadData()));
readDataTimer->setInterval(READ_DATA_INTERVAL);
readDataTimer->start();
}
Joystick::~Joystick()
{
if (jsFile != -1)
{
if (close(jsFile))
critical("Failed to close joystick file");
}
}
void Joystick::slotReadData()
{
int n;
while((n = read(jsFile, &jsEvent, sizeof(jsEvent))) == sizeof(jsEvent))
{
switch (jsEvent.type)
{
case JS_EVENT_TYPE_AXIS:
switch (jsEvent.number)
{
case JS_EVENT_AXIS_X_NS:
case JS_EVENT_AXIS_X_WE:
emit joystickEvent(jsEvent.type, jsEvent.number, jsEvent.value);
default:
break;
}
break;
case JS_EVENT_TYPE_BUTTON:
case JS_EVENT_TYPE_INIT:
default:
break;
}
}
if (!n || (n > 0 && n != sizeof(jsEvent)) || (n == -1 && errno != EAGAIN))
{
critical("Failed to read joystick file");
return;
}
}
| 22.893333 | 80 | 0.576005 | houcy |
3069a83b76d7aa1d62e769e3c75bcc32085ad3e2 | 2,168 | cpp | C++ | src/sorts/CombSort/comb_sort.cpp | delightedok/TGSToolkits | 7570378fde1f3045a545c293fddb275143701114 | [
"MIT"
] | null | null | null | src/sorts/CombSort/comb_sort.cpp | delightedok/TGSToolkits | 7570378fde1f3045a545c293fddb275143701114 | [
"MIT"
] | null | null | null | src/sorts/CombSort/comb_sort.cpp | delightedok/TGSToolkits | 7570378fde1f3045a545c293fddb275143701114 | [
"MIT"
] | null | null | null | #include "../../comms/comm_headers.h"
#include <sorts/comb_sort.h>
#define THIS_FILE "comb_sort.cpp"
#define LOG_TAG "SORTS-COMB"
TGSTK_EXPORT SortCombObject::SortCombObject(SortVTable & vTable, float factor) : SortObject(vTable)
{
this->factor = factor;
if (factor <= 1)
{
mlog_e(LOG_TAG, THIS_FILE, "Param[factor](%d) should be larger than 1. Now set to 1.3F.", factor);
this->factor = 1.3F;
}
}
int SortCombObject::onSort(void * objs, int elemSize, int size, SortType type)
{
COMM_ASSERT_RETURN(objs && size > 0, -1);
int ret = 0;
int rc = 0;
int i = 0;
int hasExchange = 0;
int gap = size;
while (gap > 1 || hasExchange)
{
hasExchange = 0;
gap = gap > 1 ? (int)((float)gap / this->factor) : gap;
for (i = gap; i < size; i++)
{
rc = this->onCompare(COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i));
switch (type)
{
case emSortDesc:
{
if (rc < 0)
{
this->onExchange(
COMM_ARRAY_ELEM(objs, elemSize, i - gap),
COMM_ARRAY_ELEM(objs, elemSize, i));
hasExchange = 1;
}
}
break;
case emSortAsc:
{
if (rc > 0)
{
this->onExchange(
COMM_ARRAY_ELEM(objs, elemSize, i - gap),
COMM_ARRAY_ELEM(objs, elemSize, i));
hasExchange = 1;
}
}
break;
default:
{
ret = -1;
mlog_e(LOG_TAG, THIS_FILE, "Invalid Param[type]: %d\n", type);
}
break;
}
}
}
return ret;
}
| 31.42029 | 112 | 0.398985 | delightedok |
307373a68a63c0a7466f75495fb6cfd8d2e2b32e | 4,271 | cpp | C++ | test/lab/test_client.cpp | brigid-jp/brigid-core | edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589 | [
"MIT"
] | 6 | 2019-12-24T01:55:57.000Z | 2021-01-18T02:51:28.000Z | test/lab/test_client.cpp | brigid-jp/brigid-core | edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589 | [
"MIT"
] | 11 | 2021-09-16T12:58:45.000Z | 2021-12-08T08:14:58.000Z | test/lab/test_client.cpp | brigid-jp/brigid-core | edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 <dev@brigid.jp>
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
#include <brigid/error.hpp>
#include "test_common.hpp"
#include <exception>
#include <iomanip>
#include <iostream>
#include <vector>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
namespace brigid {
namespace {
void run(const char* node, const char* serv) {
int fd = -1;
try {
std::cout << std::setfill('0');
timer t;
t.start();
addrinfo_t ai = getaddrinfo(node, serv, AI_ADDRCONFIG, AF_INET, SOCK_STREAM);
t.stop();
t.print("getaddrinfo");
t.start();
fd = socket(ai->ai_family, ai->ai_socktype, 0);
if (fd == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
t.stop();
t.print("socket");
{
int v = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v)) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
}
t.start();
if (connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
t.stop();
t.print("connect");
t.start();
{
int v = 0;
socklen_t size = sizeof(v);
if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &v, &size) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
std::cout << "SOL_SOCKET SO_SNDBUF " << v << "\n";
std::string buffer = "GET / HTTP/1.0\r\n\r\n";
if (send(fd, buffer.data(), buffer.size(), 0) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
}
t.stop();
t.print("send");
t.start();
{
std::vector<char> buffer(4096);
if (send(fd, buffer.data(), buffer.size(), 0) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
}
t.stop();
t.print("send");
t.start();
{
if (shutdown(fd, SHUT_WR) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
}
t.stop();
t.print("shutdown");
t.start();
{
std::vector<char> buffer(1);
while (true) {
{
int v = 0;
socklen_t size = sizeof(v);
if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &v, &size) == -1) {
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno));
}
std::cout << "SOL_SOCKET SO_RCVBUF " << v << "\n";
}
ssize_t size = read(fd, buffer.data(), buffer.size());
if (size > 0) {
std::cout << "read " << size << "\n";
} else if (size == 0) {
std::cout << "closed\n";
break;
} else {
int code = errno;
throw BRIGID_RUNTIME_ERROR(std::generic_category().message(code), make_error_code("error number", code));
}
struct timespec timeout = {};
timeout.tv_nsec = 100 * 1000 * 1000;
nanosleep(&timeout, nullptr);
}
}
t.stop();
t.print("read");
close(fd);
} catch (...) {
if (fd != -1) {
close(fd);
}
throw;
}
}
}
}
int main(int ac, char* av[]) {
try {
if (ac < 3) {
std::cout << "usage: " << av[0] << " node serv\n";
return 1;
}
brigid::run(av[1], av[2]);
return 0;
} catch (const std::exception& e) {
std::cerr << e.what() << "\n";
}
return 1;
}
| 29.054422 | 123 | 0.510887 | brigid-jp |
30777d7ac5ce4310015b27a34498b181e760e9f1 | 1,068 | cpp | C++ | cpp/UniqueBinarySearchTreesII.cpp | thinksource/code_interview | 08be992240508b73894eaf6b8c025168fd19df19 | [
"Apache-2.0"
] | 12 | 2015-03-12T03:27:26.000Z | 2021-03-11T09:26:16.000Z | cpp/UniqueBinarySearchTreesII.cpp | thinksource/code_interview | 08be992240508b73894eaf6b8c025168fd19df19 | [
"Apache-2.0"
] | null | null | null | cpp/UniqueBinarySearchTreesII.cpp | thinksource/code_interview | 08be992240508b73894eaf6b8c025168fd19df19 | [
"Apache-2.0"
] | 11 | 2015-01-28T16:45:40.000Z | 2017-03-28T20:01:38.000Z | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
vector<TreeNode *> v;
generateTrees(1,n,v);
return v;
}
void generateTrees(int start, int end, vector<TreeNode *>& trees) {
if(start>end) {
trees.push_back(NULL);
return;
}
for(int i=start;i<=end;i++) {
vector<TreeNode *> leftTrees;
generateTrees(start, i-1, leftTrees);
vector<TreeNode *> rightTrees;
generateTrees(i+1, end, rightTrees);
for(int j=0;j<leftTrees.size();j++) {
for(int k=0;k<rightTrees.size();k++) {
TreeNode* t = new TreeNode(i);
t->left = leftTrees[j];
t->right = rightTrees[k];
trees.push_back(t);
}
}
}
}
};
| 27.384615 | 71 | 0.476592 | thinksource |
307e4dcc379f086608ed6971559fccc25010eecc | 2,928 | cpp | C++ | Graphs/MazeRunner.cpp | TheArquitect/Classic-Algorithms | 29ef20af79346142df8c76dd266e728b5e12cd10 | [
"BSD-2-Clause"
] | 1 | 2019-09-30T17:47:41.000Z | 2019-09-30T17:47:41.000Z | Graphs/MazeRunner.cpp | TheArquitect/Classic-Algorithms | 29ef20af79346142df8c76dd266e728b5e12cd10 | [
"BSD-2-Clause"
] | null | null | null | Graphs/MazeRunner.cpp | TheArquitect/Classic-Algorithms | 29ef20af79346142df8c76dd266e728b5e12cd10 | [
"BSD-2-Clause"
] | null | null | null | /**
File : MazeRunner.cpp
Author : Menashe Rosemberg
Created : 2019.04.02 Version: 20190402.12
Check all spaces reachable in a maze from a random start place
BSD License
Copyright (c) 2019 TheArquitect (Menashe Rosemberg) rosemberg@ymail.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 OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include "MazeRunner.h"
#include "MazeRunner_Running.h"
void Run_MazeRunner_DFS() {
MazeMap Maze = {
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW",
"W WWW W W W W",
"W WW W W WWW WWWW WWWWW W WWWW W",
"W W W W W W W W W",
"WWWWWWWWWW W WWWW W W W",
"W W W W WWWWWW W",
"WWWWWW W WW W W WWWW WWW W",
"W W W W W WWWW W W W W WWWW W",
"W WWWW W W W W W W W W",
"W W W W WWWW W W WWW WWWW W",
"WWWWWWWWWWWWWWWWWWW W W W W W W",
"W WW W W",
"W WWWWWWWWWWWWWWWWW WWWWWWWWWWW W W",
"W W WWWWWW W W W",
"W W WWWWWWWWWWWWW W W WWWWWWWWW W W",
"W W W WW W W",
"W WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW W",
"W W",
"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW"
};
RunRunner(Maze);
}
| 49.627119 | 83 | 0.563525 | TheArquitect |
3082d2b7b359e5c3f2df5d7dd1534c7b330b0f79 | 1,299 | cpp | C++ | microcontroller/lib/Timer/Timer.cpp | robfors/nut_sorter-microcontroller | bc909fdaa1cc856341fe16773aefe9f1af773c83 | [
"Apache-2.0"
] | null | null | null | microcontroller/lib/Timer/Timer.cpp | robfors/nut_sorter-microcontroller | bc909fdaa1cc856341fe16773aefe9f1af773c83 | [
"Apache-2.0"
] | null | null | null | microcontroller/lib/Timer/Timer.cpp | robfors/nut_sorter-microcontroller | bc909fdaa1cc856341fe16773aefe9f1af773c83 | [
"Apache-2.0"
] | null | null | null | #include "Timer.h"
//
// public
//
Timer::Timer(Units units)
{
_default_length = 0;
_length = 0;
_units = units;
_is_active = false;
_start_time = 0;
}
Timer::Timer(unsigned long default_length, Units units)
{
_default_length = default_length;
_length = 0;
_units = units;
_is_active = false;
_start_time = 0;
}
boolean Timer::is_complete()
{
return !is_running();
}
boolean Timer::is_running()
{
_update();
return _is_active;
}
void Timer::start()
{
_start_time = _current_time(); // save time first
if (_default_length == 0)
{
_start_time = 0;
return;
}
_length = _default_length;
_is_active = true;
}
void Timer::start(unsigned long length)
{
_start_time = _current_time(); // save time first
_length = length;
_is_active = true;
}
void Timer::stop()
{
_start_time = 0;
_length = 0;
_is_active = false;
}
//
// private
//
unsigned long Timer::_current_time()
{
switch (_units)
{
case Timer::Units::Microseconds:
return micros();
break;
case Timer::Units::Milliseconds:
return millis();
break;
case Timer::Units::Seconds:
return millis()/1000;
break;
}
return 0;
}
void Timer::_update()
{
if (_is_active && _current_time() >= _start_time + _length)
_is_active = false;
}
| 13.121212 | 61 | 0.639723 | robfors |
30863a06f9bb3bb0f2714fb003ace0def7f08e26 | 155 | cpp | C++ | benignware/1000.cpp | CodmingOut/SecretProjectAI | addc43117eab30a25453c18fa042739c33cc6cfb | [
"MIT"
] | 8 | 2018-04-12T15:54:09.000Z | 2020-06-05T07:41:15.000Z | src/1000/1000.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | src/1000/1000.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int count_0 = 0, count_1 = 0;
int main(void)
{
int a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
} | 11.071429 | 29 | 0.574194 | CodmingOut |
308846f94715c810eea8e4c19b8358fdaa42b62a | 309 | cpp | C++ | Sorting-and-Order-Statistics/Selection sort.cpp | Fresher001/Competitive-Programming-2 | e1e953bb1d4ade46cc670b2d0432f68504538ed2 | [
"MIT"
] | 86 | 2016-10-18T23:30:36.000Z | 2022-01-09T21:57:34.000Z | Sorting-and-Order-Statistics/Selection sort.cpp | Fresher001/Competitive-Programming-2 | e1e953bb1d4ade46cc670b2d0432f68504538ed2 | [
"MIT"
] | 1 | 2018-04-13T09:38:36.000Z | 2018-04-13T09:38:36.000Z | Sorting-and-Order-Statistics/Selection sort.cpp | Fresher001/Competitive-Programming-2 | e1e953bb1d4ade46cc670b2d0432f68504538ed2 | [
"MIT"
] | 39 | 2017-03-02T07:25:40.000Z | 2020-12-14T12:13:50.000Z | #include <bits/stdc++.h>
using namespace std;
void selection_sort(int A[], int l, int r)
{
for (int i = l; i < r; ++i)
{
int p = i;
for (int j = i + 1; j <= r; ++j)
if (A[j] < A[p])
p = j;
swap(A[i], A[p]);
}
}
int main()
{
return 0;
}
| 13.434783 | 42 | 0.391586 | Fresher001 |
308acdf55b1fd94729126e79d44df30fb1e46fdf | 419 | hpp | C++ | src/PheromonWeight.hpp | mwieczor/ACO | aa30ecd728d6b205188da4993857e2291a464255 | [
"MIT"
] | null | null | null | src/PheromonWeight.hpp | mwieczor/ACO | aa30ecd728d6b205188da4993857e2291a464255 | [
"MIT"
] | null | null | null | src/PheromonWeight.hpp | mwieczor/ACO | aa30ecd728d6b205188da4993857e2291a464255 | [
"MIT"
] | null | null | null | #pragma once
#include "Ant.hpp"
class WeightGraph;
class Node;
class PheromonWeight{
public:
PheromonWeight(){}
virtual ~PheromonWeight()=default;
protected:
virtual void leavePheromon(IWeightGraph &mGraph, Node lastNode, Node position, double weight);
// virtual void leavePheromon(WeightGraph &mGraph, Node lastNode, Node position);
virtual void evaporatePheromon(IWeightGraph &mGraph);
};
| 19.952381 | 98 | 0.747017 | mwieczor |
3091aa4676803d92ae456bcbb9262bf7557229fb | 5,095 | cpp | C++ | modules/core/src/Slot/gmSlotBase.cpp | GraphMIC/GraphMIC | 8fc2aeb0143ee1292c6757f010fc9e8c68823e2b | [
"BSD-3-Clause"
] | 43 | 2016-04-11T11:34:05.000Z | 2022-03-31T03:37:57.000Z | modules/core/src/Slot/gmSlotBase.cpp | kevinlq/GraphMIC | 8fc2aeb0143ee1292c6757f010fc9e8c68823e2b | [
"BSD-3-Clause"
] | 1 | 2016-05-17T12:58:16.000Z | 2016-05-17T12:58:16.000Z | modules/core/src/Slot/gmSlotBase.cpp | kevinlq/GraphMIC | 8fc2aeb0143ee1292c6757f010fc9e8c68823e2b | [
"BSD-3-Clause"
] | 14 | 2016-05-13T20:23:16.000Z | 2021-12-20T10:33:19.000Z | #include "gmSlotBase.hpp"
#include "gmSlotInput.hpp"
#include "gmSlotOutput.hpp"
#include "gmNodeEditor.hpp"
#include "gmNodeConnector.hpp"
#include "gmSlotInputBase.hpp"
#include "gmSlotOutputBase.hpp"
#include "gmSlotConstraints.hpp"
#include "gmAsync.hpp"
namespace gm
{
namespace Slot
{
Base::Base(Component::Type componentType, Data::Type dataType, const QString& name, Constraints* constraints) : Component::Base(componentType, name), /*m_constraints(constraints),*/ m_dataType(dataType)
{
if (componentType == Component::Type::Input)
{
this->m_slotType = Type::Input;
}
else
{
this->m_slotType = Type::Output;
}
switch (dataType)
{
case Data::Type::Image: this->m_dataTypeString = "image"; break;
case Data::Type::Number: this->m_dataTypeString = "number"; break;
case Data::Type::Vector: this->m_dataTypeString = "vector"; break;
case Data::Type::Pointset: this->m_dataTypeString = "pointset"; break;
}
this->setConstraints(constraints);
}
auto Base::setConstraints(Constraints* constraints) -> void
{
this->m_constraints = constraints;
emit this->constraintsChanged();
}
auto Base::getConstraints() -> Constraints*
{
return this->m_constraints;
}
auto Base::getDataTypeString() -> QString
{
return this->m_dataTypeString;
}
auto Base::moveConnectX(int x) -> void
{
if (this->m_slotType == Type::Output)
{
Node::Connector::instance->setX2(this->m_x + x);
}
else
{
Node::Connector::instance->setX1(this->m_x + x);
}
}
auto Base::moveConnectY(int y) -> void
{
if (this->m_slotType == Type::Output)
{
Node::Connector::instance->setY2(this->m_y + y);
}
else
{
Node::Connector::instance->setY1(this->m_y + y);
}
}
auto Base::setConnecting(bool connecting) -> void
{
if (this->m_connecting != connecting)
{
this->m_connecting = connecting;
if (connecting)
{
Node::Connector::instance->setX1(this->m_x);
Node::Connector::instance->setY1(this->m_y);
Node::Connector::instance->setX2(this->m_x);
Node::Connector::instance->setY2(this->m_y);
Node::Connector::instance->setActive(true);
}
else
{
Node::Connector::instance->setActive(false);
}
}
}
auto Base::getConnecting() -> bool
{
return this->m_connecting;
}
auto Base::setX(int x) -> void
{
this->m_x = x;
emit this->xChanged();
this->onPositionChanged();
}
auto Base::getX() -> int
{
return this->m_x;
}
auto Base::setY(int y) -> void
{
this->m_y = y;
emit this->yChanged();
this->onPositionChanged();
}
auto Base::getY() -> int
{
return this->m_y;
}
auto Base::getDataType() -> Data::Type
{
return this->m_dataType;
}
auto Base::getSlotType() -> Slot::Type
{
return this->m_slotType;
}
auto Base::getSlotTypeID() -> int
{
return this->m_slotType == Type::Output;
}
auto Base::connect(Base* other) -> void
{
if (!other)
{
return;
}
Slot::InputBase* input = reinterpret_cast<Slot::InputBase*>(this->m_slotType == Type::Input ? this : other->m_slotType == Type::Input ? other : nullptr);
Slot::OutputBase* output = reinterpret_cast<Slot::OutputBase*>(this->m_slotType == Type::Output ? this : other->m_slotType == Type::Output ? other : nullptr);
if (input && output)
{
if (input->isConnected(output))
{
return;
}
output->connect(input);
}
}
auto Base::moveToMain() -> void
{
if (this->m_constraints)
{
Async::MoveToMain(this->m_constraints);
}
}
Base::~Base()
{
delete this->m_constraints;
}
}
} | 28.305556 | 210 | 0.452208 | GraphMIC |
30a19e7445d08c0baac9ae0bbc2d884232c675a1 | 1,446 | hpp | C++ | apps/las2oci.hpp | libLAS/libLAS-1.6 | 92b4c1370785481f212cc7fec9623637233c1418 | [
"BSD-3-Clause"
] | 1 | 2019-02-13T14:41:23.000Z | 2019-02-13T14:41:23.000Z | apps/las2oci.hpp | libLAS/libLAS-1.6 | 92b4c1370785481f212cc7fec9623637233c1418 | [
"BSD-3-Clause"
] | 1 | 2018-03-13T07:12:06.000Z | 2018-03-13T07:12:06.000Z | apps/las2oci.hpp | libLAS/libLAS-1.6 | 92b4c1370785481f212cc7fec9623637233c1418 | [
"BSD-3-Clause"
] | 2 | 2021-05-17T02:09:16.000Z | 2021-06-21T12:15:52.000Z | #ifndef LAS2OCI_HPP_INCLUDED
#define LAS2OCI_HPP_INCLUDED
#include "oci_wrapper.h"
#include <stdlib.h>
// god-awful hack because of GDAL/GeoTIFF's shitty include structure
#define CPL_SERV_H_INCLUDED
#include <liblas/liblas.hpp>
#include <boost/cstdint.hpp>
#include <boost/concept_check.hpp>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <exception>
#include <algorithm>
#include <vector>
#include <cctype>
#include <cmath>
#include <sys/stat.h>
using namespace std;
using namespace liblas;
#ifdef _WIN32
#define compare_no_case(a,b,n) _strnicmp( (a), (b), (n) )
#else
#define compare_no_case(a,b,n) strncasecmp( (a), (b), (n) )
#endif
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
typedef std::vector<boost::uint32_t> IDVector;
typedef boost::shared_ptr< IDVector > IDVectorPtr;
typedef struct
{
long* pc_ids;
long* block_ids;
long* num_points;
OCILobLocator** locators; // =(OCILobLocator**) VSIMalloc( sizeof(OCILobLocator*) * 1 );
std::vector<boost::uint8_t>** blobs;
long* srids;
long* gtypes;
OCIArray** element_arrays;
OCIArray** coordinate_arrays;
long size;
} blocks;
// typedef struct
// {
// double x0;
// double x1;
// double y0;
// double y1;
// double z0;
// double z1;
// bool bUse3d;
//
// } extent;
#include "kdx_util.hpp"
#include "oci_util.hpp"
#endif // LAS2OCI
| 17.421687 | 92 | 0.674965 | libLAS |
30a7ede92394a9d33e79057d72973a78de7eb231 | 1,903 | cpp | C++ | detect_all_cycles.cpp | poojacos/graph_algos | a6e5d5f29b2c18fda73cfdace8781cbddc294650 | [
"MIT"
] | null | null | null | detect_all_cycles.cpp | poojacos/graph_algos | a6e5d5f29b2c18fda73cfdace8781cbddc294650 | [
"MIT"
] | null | null | null | detect_all_cycles.cpp | poojacos/graph_algos | a6e5d5f29b2c18fda73cfdace8781cbddc294650 | [
"MIT"
] | null | null | null | // C++ program to print all the cycles
// in an undirected graph
//CONCEPT-use colors
#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
// variables to be used
// in both functions
vector<int> graph[N];
vector<int> cycles[N];
// Function to mark the vertex with
// different colors for different cycles
void dfs_cycle(int node,int parent,int color[],int mark[],int par[],int cyclenumber){
if(color[node]==2)return;
if(color[node]==1){
int curr=parent;
cyclenumber++;
mark[parent]=cyclenumber;
//backtrack
while(curr!=node){
curr=par[curr];
mark[curr]=cyclenumber;
}
return;
}
par[node]=parent;
color[node]=1;
for(int ii=0;ii<graph[node].size();ii++){
//if not visited previously
if(graph[node][ii]==par[node])continue;
dfs_cycle(graph[node][ii],node,color,mark,par,cyclenumber);
}
//all descendants seen so change the color
color[node]=2;
}
// add the edges to the graph
void addEdge(int u, int v)
{
graph[u].push_back(v);
graph[v].push_back(u);
}
// Function to print the cycles
void printCycles(int edges, int mark[], int& cyclenumber)
{
for (int i = 1; i <= edges; i++) {
if (mark[i] != 0)
cycles[mark[i]].push_back(i);
}
// print all the vertex with same cycle
for (int i = 1; i <= cyclenumber; i++) {
// Print the i-th cycle
cout << "Cycle Number " << i << ": ";
for (int x : cycles[i])
cout << x << " ";
cout << endl;
}
}
// Driver Code
int main()
{
addEdge(1, 2);
addEdge(2, 3);
addEdge(3, 4);
addEdge(4, 6);
addEdge(4, 7);
addEdge(5, 6);
addEdge(3, 5);
addEdge(7, 8);
addEdge(6, 10);
addEdge(5, 9);
addEdge(10, 11);
addEdge(11, 12);
addEdge(11, 13);
addEdge(12, 13);
int color[N];
int par[N];
int mark[N];
int cyclenumber = 0;
int edges = 13;
dfs_cycle(1, 0, color, mark, par, cyclenumber);
printCycles(edges, mark, cyclenumber);
}
| 21.144444 | 85 | 0.620074 | poojacos |
dd645f424261ce5b53ea1744ecac4d11c2ca18b4 | 14,422 | hpp | C++ | include/types/mat.hpp | Oxsomi/core2 | 96d64fc5f47b6aee2e205205196e4bb1ddee59f6 | [
"MIT"
] | null | null | null | include/types/mat.hpp | Oxsomi/core2 | 96d64fc5f47b6aee2e205205196e4bb1ddee59f6 | [
"MIT"
] | 12 | 2020-01-17T21:40:53.000Z | 2020-11-18T18:13:35.000Z | include/types/mat.hpp | Oxsomi/core2 | 96d64fc5f47b6aee2e205205196e4bb1ddee59f6 | [
"MIT"
] | null | null | null | #pragma once
#include "vec.hpp"
//Helper for generating matrices
//All rotations and fovs are in radians
//Matrix storage
template<typename T, usz W, usz H>
struct TMatStorage {
union {
T f[W * H];
T m[W][H];
Vec<T, W> axes[H];
};
constexpr inline TMatStorage(): f{} {}
template<typename ...args>
constexpr inline TMatStorage(const Vec<T, W> &axis, const args &...arg): axes{ axis, arg... } {}
};
template<typename T>
struct TMatStorage<T, 2, 2> {
union {
T f[4];
T m[2][2];
Vec2<T> axes[2];
struct { Vec2<T> x, y; };
};
constexpr inline TMatStorage(): f{} {}
template<typename ...args>
constexpr inline TMatStorage(const Vec2<T> &axis, const args &...arg): axes{ axis, arg... } {}
};
template<typename T>
struct TMatStorage<T, 3, 3> {
union {
T f[9];
T m[3][3];
Vec3<T> axes[3];
struct {
Vec3<T> xAxis, yAxis, zAxis;
};
struct {
Vec2<T> x; T wx;
Vec2<T> y; T wy;
Vec2<T> pos; T one;
};
};
constexpr inline TMatStorage(): f{} {}
template<typename ...args>
constexpr inline TMatStorage(const Vec3<T> &axis, const args &...arg): axes{ axis, arg... } {}
};
template<typename T>
struct TMatStorage<T, 4, 4> {
union {
T f[16];
T m[4][4];
Vec4<T> axes[4];
struct {
Vec4<T> xAxis, yAxis, zAxis, pos4;
};
struct {
Vec3<T> x; T wx;
Vec3<T> y; T wy;
Vec3<T> z; T wz;
Vec3<T> pos; T one;
};
};
constexpr inline TMatStorage(): f{} {}
template<typename ...args>
constexpr inline TMatStorage(const Vec4<T> &axis0, const Vec4<T> &axis1, const args &...arg): axes{ axis0, axis1, arg... } {}
};
template<typename T>
struct TMatStorage<T, 4, 3> {
union {
T f[12];
T m[4][3];
Vec3<T> axes[4];
struct {
Vec3<T> x, y, z, pos;
};
};
constexpr inline TMatStorage(): f{} {}
template<typename ...args>
constexpr inline TMatStorage(const Vec3<T> &axis, const args &...arg): axes{ axis, arg... } {}
};
//Col major matrix base
template<typename T, usz W, usz H>
struct Mat : public TMatStorage<T, W, H> {
//Constants and types
static constexpr usz N = W * H, diagonalN = W < H ? W : H;
using Type = T;
using Diagonal = Vec<T, diagonalN>;
using Horizontal = Vec<T, W>;
using Vertical = Vec<T, H>;
using TMatStorage<T, W, H>::TMatStorage;
using TMatStorage<T, W, H>::m;
using TMatStorage<T, W, H>::f;
using TMatStorage<T, W, H>::axes;
static constexpr usz Height = H, Width = W;
//Constructors
Mat(const Mat&) = default;
Mat(Mat&&) = default;
Mat &operator=(const Mat&) = default;
Mat &operator=(Mat&&) = default;
//Scale matrix
explicit constexpr inline Mat(const Diagonal &scale) {
for (usz i = 0; i < diagonalN; ++i) m[i][i] = scale[i];
}
//Identity
constexpr inline Mat(): Mat(Diagonal(1)) { }
//
template<typename ...args>
constexpr inline Mat(const Vec<T, W> &axis0, const Vec<T, W> &axis1, const args &...arg): TMatStorage<T, W, H>{ axis0, axis1, arg... } {}
//Value matrix
constexpr inline Mat(const T &t) {
for (usz i = 0; i < N; ++i) f[i] = t;
}
//TODO: Constructor with T[N] and T[W][H] and T, T, T, ...
//Empty matrix
static constexpr inline Mat nil() { return Mat(0); }
//Access to rows, cols and values
static constexpr usz horizontal() { return W; }
static constexpr usz vertical() { return H; }
Vertical &operator[](const usz i) { return axes[i]; }
constexpr const Vertical &operator[](const usz i) const { return axes[i]; }
T &operator[](const Vec2usz &xy) { return m[xy.x][xy.y]; }
constexpr const T &operator[](const Vec2usz &xy) const { return axes[xy.x][xy.y]; }
constexpr Horizontal getHorizontal(const usz j) const {
Vertical res;
for (usz i = 0; i < W; ++i) res[i] = m[i][j];
return res;
}
constexpr const Vertical &getVertical(const usz i) const { return axes[i]; }
//Arithmetic overloads
constexpr Mat &operator+=(const Mat &other) {
for (usz i = 0; i < W; ++i) axes[i] += other.axes[i];
return *this;
}
constexpr Mat &operator-=(const Mat &other) {
for (usz i = 0; i < W; ++i) axes[i] -= other.axes[i];
return *this;
}
constexpr Mat &operator/=(const Mat &other) {
for (usz i = 0; i < W; ++i) axes[i] /= other.axes[i];
return *this;
}
constexpr Mat &operator%=(const Mat &other) {
for (usz i = 0; i < W; ++i) axes[i] %= other.axes[i];
return *this;
}
constexpr Mat operator+(const Mat &other) const { return Mat(*this) += other; }
constexpr Mat operator-(const Mat &other) const { return Mat(*this) -= other; }
constexpr Mat operator/(const Mat &other) const { return Mat(*this) /= other; }
constexpr Mat operator%(const Mat &other) const { return Mat(*this) %= other; }
//Since Matrix multiply is different, mulVal can be used to perform regular multiplications on the values
constexpr Mat &mulVal(const Mat &other) {
for (usz i = 0; i < W; ++i) axes[i] *= other.axes[i];
return *this;
}
static constexpr inline Mat mulVal(const Mat &a, const Mat &b) { return Mat(a).mulVal(b); }
static constexpr inline Mat scale(const Diagonal &diag) { return Mat(diag); }
//Comparison
constexpr bool operator==(const Mat &other) const {
return std::memcmp(f, other.f, sizeof(other)) == 0;
}
constexpr bool operator!=(const Mat &other) const {
return std::memcmp(f, other.f, sizeof(other));
}
//Matrix math
//TODO: Inverse, determinant
constexpr inline Vec<T, H> operator*(const Vec<T, W> &other) const {
Vec<T, H> res{};
for (usz i = 0; i < W; ++i)
for (usz j = 0; j < H; ++j)
res[j] += m[i][j] * other[i];
return res;
}
constexpr inline Mat operator*(const Mat &other) const {
Mat res;
for (usz i = 0; i < W; ++i)
for (usz j = 0; j < H; ++j)
res.m[i][j] = getHorizontal(j).dot(other.getVertical(i));
return res;
}
constexpr inline Mat &operator*=(const Mat &other) { return *this = *this * other; }
constexpr inline Mat<T, H, W> transpose() const {
Mat<T, H, W> res{};
for (usz i = 0; i < W && i < H; ++i)
for (usz j = 0; j < H && j < W; ++j)
res.m[j][i] = m[i][j];
return res;
}
//Helpers
inline Buffer toData() const {
return Buffer((u8*)f, (u8*)(f + N));
}
template<typename T2, usz W2, usz H2>
constexpr inline Mat<T2, W2, H2> cast() const {
Mat<T2, W2, H2> res{};
for (usz i = 0; i < W && i < W2; ++i)
for (usz j = 0; j < H && j < H2; ++j)
res.m[i][j] = T2(m[i][j]);
return res;
}
template<typename T2>
constexpr inline T2 cast() const {
T2 res{};
for (usz i = 0; i < W && i < T2::horizontal(); ++i)
for (usz j = 0; j < H && j < T2::vertical(); ++j)
res.m[i][j] = typename T2::Type(m[i][j]);
return res;
}
};
//Helper functions that carry to multiple types of matrices
template<typename Mat, typename T>
struct TMatHelper {
static constexpr inline Mat rotateX(T v) {
static_assert(
std::is_floating_point_v<typename Mat::Type>,
"Can't call TMatHelper<Mat>::rotateX if T isn't a floating point"
);
static_assert(
Mat::horizontal() > 2 && Mat::vertical() > 2,
"Can't call TMatHelper<Mat>::rotateX if Mat's dimensions are less than 3x3"
);
Mat res{};
res[1][1] = std::cos(v); res[2][1] = -std::sin(v);
res[1][2] = std::sin(v); res[2][2] = std::cos(v);
return res;
}
static constexpr inline Mat rotateY(T v) {
static_assert(
std::is_floating_point_v<typename Mat::Type>,
"Can't call TMatHelper<Mat>::rotateY if T isn't a floating point"
);
static_assert(
Mat::horizontal() > 2 && Mat::vertical() > 2,
"Can't call TMatHelper<Mat>::rotateY if Mat's dimensions are less than 3x3"
);
Mat res{};
res[0][0] = std::cos(v); res[0][2] = -std::sin(v);
res[2][0] = std::sin(v); res[2][2] = std::cos(v);
return res;
}
static constexpr inline Mat rotateZ(T v) {
static_assert(
std::is_floating_point_v<typename Mat::Type>,
"Can't call TMatHelper<Mat>::rotateZ if T isn't a floating point"
);
static_assert(
Mat::horizontal() > 1 && Mat::vertical() > 1,
"Can't call TMatHelper<Mat>::rotateZ if Mat's dimensions are less than 2x2"
);
Mat res{};
res[0][0] = std::cos(v); res[0][1] = -std::sin(v);
res[1][0] = std::sin(v); res[1][1] = std::cos(v);
return res;
}
};
//2x2 matrix
template<typename T>
struct Mat2x2 : public Mat<T, 2, 2> {
using Mat<T, 2, 2>::Mat;
using Mat<T, 2, 2>::f;
constexpr inline Mat2x2(const Mat<T, 2, 2> &dat) : Mat<T, 2, 2>(dat) {}
constexpr inline Mat2x2(Mat<T, 2, 2> &&dat) : Mat<T, 2, 2>(dat) {}
//Rotate z
static constexpr inline Mat2x2 rotateZ(T v) { return TMatHelper<Mat2x2, T>::rotateZ(v); }
//Pad to vec4s
inline Buffer toGPUData() const {
Buffer result(0x20); //2 vec4s
std::memcpy(result.data() + 0x00, f + 0x00, 0x08);
std::memcpy(result.data() + 0x10, f + 0x08, 0x08);
return result;
}
};
//3x3 matrix
template<typename T>
struct Mat3x3 : public Mat<T, 3, 3> {
using Mat<T, 3, 3>::Mat;
using Mat<T, 3, 3>::f;
constexpr inline Mat3x3(const Mat<T, 3, 3> &dat) : Mat<T, 3, 3>(dat) {}
constexpr inline Mat3x3(Mat<T, 3, 3> &&dat) : Mat<T, 3, 3>(dat) {}
//TODO: rotateY3D, rotateZ3D, translate2D, transform2D, orientation3D, perspective/ortho
//Rotate z
static constexpr Mat3x3 rotateZ(T v) { return TMatHelper<Mat3x3, T>::rotateZ(v); }
//Pad to vec4s
inline Buffer toGPUData() const {
Buffer result(0x30); //3 vec4s
std::memcpy(result.data() + 0x00, f + 0x00, 0x0C);
std::memcpy(result.data() + 0x10, f + 0x0C, 0x0C);
std::memcpy(result.data() + 0x20, f + 0x18, 0x0C);
return result;
}
};
//4x4 matrix
template<typename T, usz W, usz H, typename = std::enable_if_t<W == 4 && (H == 3 || W == 4)>>
struct MatOT : public Mat<T, W, H> {
using Mat<T, W, H>::Mat;
using Mat<T, W, H>::f;
using Mat<T, W, H>::toData;
constexpr inline MatOT(const Mat<T, W, H> &dat) : Mat<T, W, H>(dat) { }
constexpr inline MatOT(Mat<T, W, H> &&dat) : Mat<T, W, H>(dat) {}
//Rotation
static constexpr inline MatOT rotateX(T v) { return TMatHelper<MatOT, T>::rotateX(v); }
static constexpr inline MatOT rotateY(T v) { return TMatHelper<MatOT, T>::rotateY(v); }
static constexpr inline MatOT rotateZ(T v) { return TMatHelper<MatOT, T>::rotateZ(v); }
//Helper functions
static constexpr inline MatOT translate(const Vec3<T> &pos) {
MatOT res{};
res.pos = pos;
return res;
}
static inline MatOT perspective(T fov, T asp, T n, T f) {
static_assert(
std::is_floating_point_v<T>,
"Can't call MatOT::perspective if T isn't a floating point"
);
static_assert(H == 4, "MatOT::perspective only allowed on 4x4 matrices");
T scale = T(1 / tan(fov / 2));
MatOT res(
Vec4<T>(scale / asp, -scale, n / (f - n), 0)
);
res.m[2][3] = -1;
res.m[3][2] = f * n / (f - n);
return res;
}
//TODO: Ortho
static constexpr inline MatOT rotate(const Vec3<T> &rot) {
return rotateX(rot.x) * rotateY(rot.y) * rotateZ(rot.z);
}
static constexpr inline MatOT scale(const Vec3<T> &scl) {
if constexpr (H == 4)
return Mat4x4<T>(Vec4<T>(scl.x, scl.y, scl.z, 1));
else
return Mat4x3<T>(Vec3<T>(scl.x, scl.y, scl.z));
}
static constexpr inline MatOT transform(
const Vec3<T> &pos, const Vec3<T> &rot, const Vec3<T> &scl
) {
return translate(pos) * rotate(rot) * scale(scl);
}
static constexpr inline MatOT view(
const Vec3<T> &pos, const Vec3<T> &rot
) {
return translate(-pos) * rotate(rot);
}
static constexpr inline MatOT lookAt(
const Vec3<T> &eye, const Vec3<T> ¢er, const Vec3<T> &up
) {
Vec3<T> z = (eye - center).normalize();
Vec3<T> x = (up.cross(z)).normalize();
Vec3<T> y = (z.cross(x)).normalize();
MatOT res;
res.x = x;
res.y = y;
res.z = z;
res.pos = -eye;
if constexpr (H == 4)
res.one = 1;
return res;
}
static constexpr inline MatOT lookDirection(
const Vec3<T> &eye, const Vec3<T> &dir, const Vec3<T> &up
) {
Vec3<T> z = dir.normalize();
Vec3<T> x = (z.cross(up)).normalize();
Vec3<T> y = (x.cross(z)).normalize();
MatOT res;
res.x = x;
res.y = y;
res.z = z;
res.pos = -eye;
if constexpr (H == 4)
res.one = 1;
return res;
}
//Get gpu data
inline Buffer toGPUData() const {
return toData();
}
};
//Types
//2x2 matrices (2d orientation)
using Mat2x2i16 = Mat2x2<i16>;
using Mat2x2u16 = Mat2x2<u16>;
using Mat2x2i16 = Mat2x2<i16>;
using Mat2x2u16 = Mat2x2<u16>;
using Mat2x2b32 = Mat2x2<u32>;
using Mat2x2f32 = Mat2x2<f32>;
using Mat2x2i32 = Mat2x2<i32>;
using Mat2x2u32 = Mat2x2<u32>;
using Mat2x2i64 = Mat2x2<i64>;
using Mat2x2u64 = Mat2x2<u64>;
using Mat2x2f64 = Mat2x2<f64>;
//3x3 matrices (3d orientation or 2d orientation + translation)
using Mat3x3i16 = Mat3x3<i16>;
using Mat3x3u16 = Mat3x3<u16>;
using Mat3x3i16 = Mat3x3<i16>;
using Mat3x3u16 = Mat3x3<u16>;
using Mat3x3b32 = Mat3x3<u32>;
using Mat3x3f32 = Mat3x3<f32>;
using Mat3x3i32 = Mat3x3<i32>;
using Mat3x3u32 = Mat3x3<u32>;
using Mat3x3i64 = Mat3x3<i64>;
using Mat3x3u64 = Mat3x3<u64>;
using Mat3x3f64 = Mat3x3<f64>;
//4x4 matrices (3d orientation + translation)
template<typename T>
using Mat4x4 = MatOT<T, 4, 4>;
using Mat4x4i16 = Mat4x4<i16>;
using Mat4x4u16 = Mat4x4<u16>;
using Mat4x4i16 = Mat4x4<i16>;
using Mat4x4u16 = Mat4x4<u16>;
using Mat4x4b32 = Mat4x4<u32>;
using Mat4x4f32 = Mat4x4<f32>;
using Mat4x4i32 = Mat4x4<i32>;
using Mat4x4u32 = Mat4x4<u32>;
using Mat4x4i64 = Mat4x4<i64>;
using Mat4x4u64 = Mat4x4<u64>;
using Mat4x4f64 = Mat4x4<f64>;
//4x3 matrices (3d orientation + translation)
template<typename T>
using Mat4x3 = MatOT<T, 4, 3>;
using Mat4x3i16 = Mat4x3<i16>;
using Mat4x3u16 = Mat4x3<u16>;
using Mat4x3i16 = Mat4x3<i16>;
using Mat4x3u16 = Mat4x3<u16>;
using Mat4x3b32 = Mat4x3<u32>;
using Mat4x3f32 = Mat4x3<f32>;
using Mat4x3i32 = Mat4x3<i32>;
using Mat4x3u32 = Mat4x3<u32>;
using Mat4x3i64 = Mat4x3<i64>;
using Mat4x3u64 = Mat4x3<u64>;
using Mat4x3f64 = Mat4x3<f64>;
namespace oic {
template<typename T>
struct is_matrix { static constexpr bool value = false; };
template<typename T, usz W, usz H>
struct is_matrix<Mat<T, W, H>> { static constexpr bool value = true; };
template<typename T>
struct is_matrix<Mat2x2<T>> { static constexpr bool value = true; };
template<typename T>
struct is_matrix<Mat3x3<T>> { static constexpr bool value = true; };
template<typename T>
struct is_matrix<Mat4x4<T>> { static constexpr bool value = true; };
template<typename T>
struct is_matrix<Mat4x3<T>> { static constexpr bool value = true; };
template<typename T>
static constexpr bool is_matrix_v = is_matrix<T>::value;
}
| 23.112179 | 138 | 0.630495 | Oxsomi |
dd6fc2943c3e92cafa915e06f0f9a2191e0dbd71 | 7,484 | cpp | C++ | source/MultiLibrary/Filesystem/Windows/Filesystem.cpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 2 | 2018-06-22T12:43:57.000Z | 2019-05-31T21:56:27.000Z | source/MultiLibrary/Filesystem/Windows/Filesystem.cpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 1 | 2017-09-09T01:21:31.000Z | 2017-11-12T17:52:56.000Z | source/MultiLibrary/Filesystem/Windows/Filesystem.cpp | danielga/multilibrary | 3d1177dd3affa875e06015f5e3e42dda525f3336 | [
"BSD-3-Clause"
] | 1 | 2022-03-30T18:57:41.000Z | 2022-03-30T18:57:41.000Z | /*************************************************************************
* MultiLibrary - https://danielga.github.io/multilibrary/
* A C++ library that covers multiple low level systems.
*------------------------------------------------------------------------
* Copyright (c) 2014-2022, Daniel Almeida
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include <MultiLibrary/Filesystem/Filesystem.hpp>
#include <MultiLibrary/Filesystem/File.hpp>
#include <MultiLibrary/Filesystem/FileSimple.hpp>
#include <MultiLibrary/Common/Unicode.hpp>
#include <cstdlib>
#include <cstdio>
#include <iterator>
#include <sys/stat.h>
#include <windows.h>
#include <direct.h>
#undef CreateFile
namespace MultiLibrary
{
namespace Internal
{
static uint64_t Find( const std::wstring &widefind, std::vector<std::wstring> &files, std::vector<std::wstring> &folders )
{
WIN32_FIND_DATA find_data;
uint64_t num_files = 0;
HANDLE find_handle = FindFirstFileEx( widefind.c_str( ), FindExInfoStandard, &find_data, FindExSearchNameMatch, nullptr, 0 );
while( find_handle != INVALID_HANDLE_VALUE )
{
std::wstring filename = find_data.cFileName;
if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( filename != L"." && filename != L".." )
{
folders.push_back( filename );
++num_files;
}
}
else
{
files.push_back( filename );
++num_files;
}
if( FindNextFile( find_handle, &find_data ) == FALSE )
break;
}
FindClose( find_handle );
return num_files;
}
static bool IsFolder( const std::wstring &widepath )
{
struct _stat64 stat;
if( _wstat64( widepath.c_str( ), &stat ) != 0 )
return false;
return ( stat.st_mode & S_IFMT ) == S_IFDIR;
}
static bool RemoveFolder( const std::wstring &widepath, bool recursive )
{
if( !IsFolder( widepath ) )
return false;
if( recursive )
{
std::vector<std::wstring> files;
std::vector<std::wstring> folders;
Find( widepath + L"/*", files, folders );
for( size_t k = 0; k != files.size( ); ++k )
if ( _wunlink( widepath.c_str( ) ) != 0 )
return false;
for( size_t k = 0; k < folders.size( ); ++k )
if ( !RemoveFolder( widepath + L"/" + folders[k], true ) )
return false;
}
return _wrmdir( widepath.c_str( ) ) == 0;
}
}
Filesystem::~Filesystem( )
{
std::vector<FileInternal *>::iterator it, end = open_files.end( );
for( it = open_files.begin( ); it != end; ++it )
fclose( static_cast<FILE *>( ( *it )->Release( ) ) );
}
File Filesystem::Open( const std::string &path, const char *mode )
{
std::wstring widepath;
UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) );
std::wstring widemode;
UTF16::FromUTF8( mode, mode + strlen( mode ), std::back_inserter( widemode ) );
FILE *file = _wfopen( widepath.c_str( ), widemode.c_str( ) );
if( file == nullptr )
return File( std::shared_ptr<FileInternal>( ) );
FileSimple *finternal = new FileSimple( this, file, path );
open_files.push_back( finternal );
return File( std::shared_ptr<FileInternal>( finternal ) );
}
int64_t Filesystem::Size( const std::string &path )
{
std::wstring widepath;
UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) );
struct _stat64 stat;
if( _wstat64( widepath.c_str( ), &stat ) == 0 )
return stat.st_size;
return -1;
}
bool Filesystem::Exists( const std::string &path )
{
File file = Open( path, "r" );
if( file.IsValid( ) )
{
file.Close( );
return true;
}
return false;
}
bool Filesystem::RemoveFile( const std::string &path )
{
std::wstring widepath;
UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) );
return _wunlink( widepath.c_str( ) ) == 0;
}
uint64_t Filesystem::Find( const std::string &find, std::vector<std::string> &files, std::vector<std::string> &folders )
{
std::wstring widefind;
UTF16::FromUTF8( find.begin( ), find.end( ), std::back_inserter( widefind ) );
std::vector<std::wstring> wfiles;
std::vector<std::wstring> wfolders;
uint64_t num_files = Internal::Find( widefind, wfiles, wfolders );
files.reserve( wfiles.size( ) );
folders.reserve( wfolders.size( ) );
for( std::vector<std::wstring>::iterator it = wfiles.begin( ); it != wfiles.end( ); ++it )
{
std::wstring &wfile = *it;
std::string file;
UTF8::FromUTF16( wfile.begin( ), wfile.end( ), std::back_inserter( file ) );
files.push_back( file );
}
for( std::vector<std::wstring>::iterator it = wfolders.begin( ); it != wfolders.end( ); ++it )
{
std::wstring &wfolder = *it;
std::string folder;
UTF8::FromUTF16( wfolder.begin( ), wfolder.end( ), std::back_inserter( folder ) );
folders.push_back( folder );
}
return num_files;
}
bool Filesystem::IsFolder( const std::string &path )
{
std::wstring widepath;
UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) );
return Internal::IsFolder( widepath );
}
bool Filesystem::CreateFolder( const std::string &path )
{
std::wstring widepath;
UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) );
return _wmkdir( widepath.c_str( ) ) == 0;
}
bool Filesystem::RemoveFolder( const std::string &path, bool recursive )
{
std::wstring widepath;
UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) );
return Internal::RemoveFolder( widepath, recursive );
}
std::string Filesystem::GetExecutablePath( )
{
std::string path;
wchar_t *widepath = _wpgmptr;
if( widepath == nullptr )
return path;
UTF8::FromUTF16( widepath, widepath + wcslen( widepath ), std::back_inserter( path ) );
return path;
}
bool Filesystem::Close( FileInternal *file )
{
if( file == nullptr )
return false;
std::vector<FileInternal *>::iterator it, end = open_files.end( );
for( it = open_files.begin( ); it != end; ++it )
if( *it == file )
{
fclose( static_cast<FILE *>( file->Release( ) ) );
open_files.erase( it );
return true;
}
return false;
}
} // namespace MultiLibrary
| 29.234375 | 126 | 0.671833 | danielga |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.