text stringlengths 54 60.6k |
|---|
<commit_before>#ifndef SILICIUM_SILICIUM_CONFIG_HPP
#define SILICIUM_SILICIUM_CONFIG_HPP
#include <memory>
#include <boost/config.hpp>
#ifdef NDEBUG
# ifdef _MSC_VER
# define SILICIUM_UNREACHABLE() __assume(false)
# else
# define SILICIUM_UNREACHABLE() __builtin_unreachable()
# endif
#else
# define SILICIUM_UNREACHABLE() do { throw ::std::logic_error("unreachable " __FILE__ ":" BOOST_STRINGIZE(__LINE__)); } while(false)
#endif
#if (defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408)) || defined(__clang__)
# define SILICIUM_COMPILER_GENERATES_MOVES 1
#else
# define SILICIUM_COMPILER_GENERATES_MOVES 0
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT 1
#else
# define SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT 0
#endif
#ifdef _MSC_VER
# define SILICIUM_NORETURN __declspec(noreturn)
#else
// GCC
# define SILICIUM_NORETURN __attribute__ ((__noreturn__))
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER 1
#else
# define SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER 0
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE 1
#else
# define SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE 0
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE 1
#else
# define SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE 0
#endif
#ifdef BOOST_DELETED_FUNCTION
# define SILICIUM_DELETED_FUNCTION BOOST_DELETED_FUNCTION
#else
# define SILICIUM_DELETED_FUNCTION(f) private: f;
#endif
namespace Si
{
struct nothing
{
BOOST_CONSTEXPR nothing() BOOST_NOEXCEPT
{
}
};
template <class T, class ...Args>
auto make_unique(Args &&...args) -> std::unique_ptr<T>
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif
<commit_msg>avoid a VC++ 2013 warning<commit_after>#ifndef SILICIUM_SILICIUM_CONFIG_HPP
#define SILICIUM_SILICIUM_CONFIG_HPP
#include <memory>
#include <boost/config.hpp>
#ifdef _MSC_VER
//avoid useless warning C4127 (conditional expression is constant)
# define SILICIUM_FALSE (!"")
#else
# define SILICIUM_FALSE false
#endif
#ifdef NDEBUG
# ifdef _MSC_VER
# define SILICIUM_UNREACHABLE() __assume(false)
# else
# define SILICIUM_UNREACHABLE() __builtin_unreachable()
# endif
#else
# define SILICIUM_UNREACHABLE() do { throw ::std::logic_error("unreachable " __FILE__ ":" BOOST_STRINGIZE(__LINE__)); } while(SILICIUM_FALSE)
#endif
#if (defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408)) || defined(__clang__)
# define SILICIUM_COMPILER_GENERATES_MOVES 1
#else
# define SILICIUM_COMPILER_GENERATES_MOVES 0
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT 1
#else
# define SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT 0
#endif
#ifdef _MSC_VER
# define SILICIUM_NORETURN __declspec(noreturn)
#else
// GCC
# define SILICIUM_NORETURN __attribute__ ((__noreturn__))
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER 1
#else
# define SILICIUM_COMPILER_HAS_RVALUE_THIS_QUALIFIER 0
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE 1
#else
# define SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE 0
#endif
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) || defined(__clang__)
# define SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE 1
#else
# define SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE 0
#endif
#ifdef BOOST_DELETED_FUNCTION
# define SILICIUM_DELETED_FUNCTION BOOST_DELETED_FUNCTION
#else
# define SILICIUM_DELETED_FUNCTION(f) private: f;
#endif
namespace Si
{
struct nothing
{
BOOST_CONSTEXPR nothing() BOOST_NOEXCEPT
{
}
};
template <class T, class ...Args>
auto make_unique(Args &&...args) -> std::unique_ptr<T>
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif
<|endoftext|> |
<commit_before>#include <complex>
#include "functions/trig.hh"
#include "functions/full_function_defs.hh"
#include "pointwise_equal.hh"
#include "functions/all_simplifications.hh"
#include <boost/test/unit_test.hpp>
#include "functions/operators.hh"
#include <limits>
BOOST_AUTO_TEST_CASE(trig_tests) {
using namespace manifolds;
Sin s;
Cos c;
Tan t;
PointwiseEqual(s, [](auto x) { return std::sin(std::get<0>(x)); });
PointwiseEqual(c, [](auto x) { return std::cos(std::get<0>(x)); });
PointwiseEqual(t, [](auto x) { return std::tan(std::get<0>(x)); });
Sinh sh;
Cosh ch;
Tanh th;
PointwiseEqual(sh, [](auto x) { return std::sinh(std::get<0>(x)); });
PointwiseEqual(ch, [](auto x) { return std::cosh(std::get<0>(x)); });
PointwiseEqual(th, [](auto x) { return std::tanh(std::get<0>(x)); });
std::complex<double> i(0, 1);
BOOST_CHECK_EQUAL(std::abs(s(i)), sh(1));
BOOST_CHECK_EQUAL(std::abs(sh(i)), s(1));
ACos ac;
ASin as;
ATan at;
double min = -0.9999;
double max = -min;
PointwiseEqual(as, [](auto x) { return std::asin(std::get<0>(x)); }, 100, 0,
min, max);
PointwiseEqual(ac, [](auto x) { return std::acos(std::get<0>(x)); }, 100, 0,
min, max);
PointwiseEqual(at, [](auto x) { return std::atan(std::get<0>(x)); }, 100, 0,
min, max);
ACosh ach;
ASinh ash;
ATanh ath;
PointwiseEqual(ash, [](auto x) { return std::asinh(std::get<0>(x)); }, 100,
0);
PointwiseEqual(ach, [](auto x) { return std::acosh(std::get<0>(x)); }, 100, 0,
1, 25);
PointwiseEqual(ath, [](auto x) { return std::atanh(std::get<0>(x)); }, 100, 0,
min, max);
BOOST_CHECK_EQUAL(Simplify(ACos()(Cos())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ASin()(Sin())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ATan()(Tan())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ACosh()(Cosh())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ASinh()(Sinh())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ATanh()(Tanh())(x)), x);
static_assert(is_all_but_last_0<0,0,2>::value, "");
BOOST_CHECK_EQUAL(Simplify(Sin()(GetIPolynomial<0,-2>())(x)),
(GetIPolynomial<0,-2>()((Sin()*Cos()))(x)));
BOOST_CHECK_EQUAL(Simplify(Cos()(GetIPolynomial<0,-2>())(x)),
(Cos()*Cos()-Sin()*Sin())(x));
auto p = Simplify(Sin()(GetIPolynomial<0,3>()(x)));
std::cout << get_cpp_name<decltype(p)>() << '\n';
std::cout << '\n' << p << '\n';
}
<commit_msg>Added more tests<commit_after>#include <complex>
#include "functions/trig.hh"
#include "functions/full_function_defs.hh"
#include "pointwise_equal.hh"
#include "functions/all_simplifications.hh"
#include <boost/test/unit_test.hpp>
#include "functions/operators.hh"
#include <limits>
BOOST_AUTO_TEST_CASE(trig_tests) {
using namespace manifolds;
Sin s;
Cos c;
Tan t;
PointwiseEqual(s, [](auto x) { return std::sin(std::get<0>(x)); });
PointwiseEqual(c, [](auto x) { return std::cos(std::get<0>(x)); });
PointwiseEqual(t, [](auto x) { return std::tan(std::get<0>(x)); });
Sinh sh;
Cosh ch;
Tanh th;
PointwiseEqual(sh, [](auto x) { return std::sinh(std::get<0>(x)); });
PointwiseEqual(ch, [](auto x) { return std::cosh(std::get<0>(x)); });
PointwiseEqual(th, [](auto x) { return std::tanh(std::get<0>(x)); });
std::complex<double> i(0, 1);
BOOST_CHECK_EQUAL(std::abs(s(i)), sh(1));
BOOST_CHECK_EQUAL(std::abs(sh(i)), s(1));
ACos ac;
ASin as;
ATan at;
double min = -0.9999;
double max = -min;
PointwiseEqual(as, [](auto x) { return std::asin(std::get<0>(x)); }, 100, 0,
min, max);
PointwiseEqual(ac, [](auto x) { return std::acos(std::get<0>(x)); }, 100, 0,
min, max);
PointwiseEqual(at, [](auto x) { return std::atan(std::get<0>(x)); }, 100, 0,
min, max);
ACosh ach;
ASinh ash;
ATanh ath;
PointwiseEqual(ash, [](auto x) { return std::asinh(std::get<0>(x)); }, 100,
0);
PointwiseEqual(ach, [](auto x) { return std::acosh(std::get<0>(x)); }, 100, 0,
1, 25);
PointwiseEqual(ath, [](auto x) { return std::atanh(std::get<0>(x)); }, 100, 0,
min, max);
BOOST_CHECK_EQUAL(Simplify(ACos()(Cos())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ASin()(Sin())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ATan()(Tan())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ACosh()(Cosh())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ASinh()(Sinh())(x)), x);
BOOST_CHECK_EQUAL(Simplify(ATanh()(Tanh())(x)), x);
static_assert(is_all_but_last_0<0,0,2>::value, "");
BOOST_CHECK_EQUAL(Simplify(Sin()(GetIPolynomial<0,-2>())(x)),
(GetIPolynomial<0,-2>()((Sin()*Cos()))(x)));
BOOST_CHECK_EQUAL(Simplify(Cos()(GetIPolynomial<0,-2>())(x)),
(Cos()*Cos()-Sin()*Sin())(x));
BOOST_CHECK_EQUAL(Simplify(Sin()(GetIPolynomial<0,3>()(x))),
ComposeRaw(GetIPolynomial<0,3,0,-4>(), Sin(), x));
PointwiseEqual(Simplify(Cos()(GetIPolynomial<0,3>())(x)),
(Composition<Cos,IntegralPolynomial<0,3>, decltype(x)>()),
100, 1E-9);
}
<|endoftext|> |
<commit_before>/* This is a fuzz test of the permessage-deflate module */
#define WIN32_EXPORT
#include <cstdio>
#include <string>
/* We test the permessage deflate module */
#include "../src/PerMessageDeflate.h"
#include "helpers.h"
struct StaticData {
uWS::ZlibContext zlibContext;
uWS::InflationStream inflationStream;
uWS::DeflationStream deflationStream;
} staticData;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
/* Why is this padded? */
makeChunked(makePadded(data, size), size, [](const uint8_t *data, size_t size) {
std::string_view inflation = staticData.inflationStream.inflate(&staticData.zlibContext, std::string_view((char *) data, size), 256);
if (inflation.length() > 256) {
/* Cause ASAN to freak out */
delete (int *) (void *) 1;
}
});
makeChunked(makePadded(data, size), size, [](const uint8_t *data, size_t size) {
/* Always reset */
staticData.deflationStream.deflate(&staticData.zlibContext, std::string_view((char *) data, size), true);
});
return 0;
}
<commit_msg>Fix fuzzing of permessage-deflate<commit_after>/* This is a fuzz test of the permessage-deflate module */
#define WIN32_EXPORT
#include <cstdio>
#include <string>
/* We test the permessage deflate module */
#include "../src/PerMessageDeflate.h"
#include "helpers.h"
struct StaticData {
uWS::ZlibContext zlibContext;
uWS::InflationStream inflationStream;
uWS::DeflationStream deflationStream = DEDICATED_COMPRESSOR_8KB;
} staticData;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
/* Why is this padded? */
makeChunked(makePadded(data, size), size, [](const uint8_t *data, size_t size) {
std::string_view inflation = staticData.inflationStream.inflate(&staticData.zlibContext, std::string_view((char *) data, size), 256);
if (inflation.length() > 256) {
/* Cause ASAN to freak out */
delete (int *) (void *) 1;
}
});
makeChunked(makePadded(data, size), size, [](const uint8_t *data, size_t size) {
/* Always reset */
staticData.deflationStream.deflate(&staticData.zlibContext, std::string_view((char *) data, size), true);
});
return 0;
}
<|endoftext|> |
<commit_before>#include "sexpr.hpp"
#include "parse.hpp"
#include <algorithm>
template<char ... c>
static int matches(int x) {
static const char data[] = {c..., 0};
for(const char* i = data; *i; ++i) {
if(*i == x) return true;
}
return false;
}
const char selection_prefix = '.';
const char injection_prefix = '|';
template<class T>
static const std::ios::pos_type try_parse(std::istream& in) {
const parser::stream_state backup(in);
T t;
in >> t;
return parser::stream_state(in).pos;
}
maybe<sexpr> sexpr::parse(std::istream& in) {
using namespace parser;
static const auto separator_parser = // parser::debug("sep") |=
noskip(chr<std::isspace>());
static const auto integer_parser = // parser::debug("real") |=
value<integer>();
static const auto real_parser = // parser::debug("real") |=
value<double>();
static const auto semicolon = chr<matches<';'>>();
static const auto endl = chr<matches<'\n'>>();
static const auto comment_parser = debug("comment") |=
semicolon >> then(noskip(*!endl >> then(endl)));
static const auto skip_parser = debug("skip") |=
+comment_parser;
static const auto as_expr = parser::cast<sexpr>();
static const auto number_parser = [](std::istream& in) {
const auto pr = try_parse<real>(in);
const auto pi = try_parse<integer>(in);
if(pr == pi) return (integer_parser >> as_expr)(in);
return (real_parser >> as_expr)(in);
};
static const auto initial_parser = chr<std::isalpha>() | chr<matches<'_'>>();
static const auto rest_parser = chr<std::isalnum>() | chr<matches<'-', '_'>>();
static const auto op_parser =
(token("!=") | token("<=") | token(">=") | token("->") | token("=>")
| token(">>=") )
>> [](const char* s) {
return pure(symbol(s));
} | chr<matches<'+', '-', '*', '/', '=', '<', '>', '%' >>() >> [](char c) {
return pure(symbol(std::string(1, c)));
};
static const auto identifier_parser = initial_parser >> [](char c) {
return noskip(*rest_parser >> [c](std::deque<char>&& rest) {
const std::string tmp = c + std::string(rest.begin(), rest.end());
return pure(symbol(tmp));
});
};
static const auto symbol_parser = identifier_parser | op_parser;
static const auto qualified_parser =
(symbol_parser % chr<matches<selection_prefix>>()) >>
[](std::deque<symbol> parts) {
sexpr res = parts.front();
parts.pop_front();
for(symbol s : parts) {
res = symbol(std::string(1, selection_prefix) + s.get())
>>= res >>= sexpr::list();
}
return pure(res);
};
static const auto selection_parser =
chr<matches<selection_prefix>>() >> [](char c) {
return symbol_parser >> [c](symbol s) {
return pure(symbol(c + std::string(s.get())));
};
};
static const auto injection_parser =
chr<matches<injection_prefix>>() >> [](char c) {
return symbol_parser >> [c](symbol s) {
return pure(symbol(c + std::string(s.get())));
};
};
static auto expr_parser = any<sexpr>();
static const auto lparen = // debug("lparen") |=
token("(");
static const auto rparen = // debug("rparen") |=
skip(skip_parser, token(")"));
static const auto exprs_parser = // debug("exprs") |=
parser::ref(expr_parser) % separator_parser;
static const auto list_parser = // debug("list") |=
lparen >>= (exprs_parser | pure<std::deque<sexpr>>()) >> drop(rparen)
>> [](std::deque<sexpr>&& es) {
return pure(make_list(es.begin(), es.end()));
};
static const auto once =
(expr_parser =
skip(skip_parser,
debug("expr") |=
(qualified_parser >> as_expr)
| (selection_parser >> as_expr)
| (injection_parser >> as_expr)
| (op_parser >> as_expr)
| number_parser
| (list_parser >> as_expr))
, 0); (void) once;
debug::stream = &std::clog;
return expr_parser(in);
}
void sexpr::iter(std::istream& in, std::function<void(sexpr)> cont) {
using namespace parser;
using exprs_type = std::deque<sexpr>;
static const auto program_parser = debug("prog") |=
kleene(parse) >> drop(debug("eof") |= eof())
| parser::error<exprs_type>("parse error");
(program_parser >> [cont](exprs_type es) {
std::for_each(es.begin(), es.end(), cont);
return pure(unit());
})(in);
}
<commit_msg>removed debug<commit_after>#include "sexpr.hpp"
#include "parse.hpp"
#include <algorithm>
template<char ... c>
static int matches(int x) {
static const char data[] = {c..., 0};
for(const char* i = data; *i; ++i) {
if(*i == x) return true;
}
return false;
}
const char selection_prefix = '.';
const char injection_prefix = '|';
template<class T>
static const std::ios::pos_type try_parse(std::istream& in) {
const parser::stream_state backup(in);
T t;
in >> t;
return parser::stream_state(in).pos;
}
maybe<sexpr> sexpr::parse(std::istream& in) {
using namespace parser;
static const auto separator_parser = // parser::debug("sep") |=
noskip(chr<std::isspace>());
static const auto integer_parser = // parser::debug("real") |=
value<integer>();
static const auto real_parser = // parser::debug("real") |=
value<double>();
static const auto semicolon = chr<matches<';'>>();
static const auto endl = chr<matches<'\n'>>();
static const auto comment_parser = debug("comment") |=
semicolon >> then(noskip(*!endl >> then(endl)));
static const auto skip_parser = debug("skip") |=
+comment_parser;
static const auto as_expr = parser::cast<sexpr>();
static const auto number_parser = [](std::istream& in) {
const auto pr = try_parse<real>(in);
const auto pi = try_parse<integer>(in);
if(pr == pi) return (integer_parser >> as_expr)(in);
return (real_parser >> as_expr)(in);
};
static const auto initial_parser = chr<std::isalpha>() | chr<matches<'_'>>();
static const auto rest_parser = chr<std::isalnum>() | chr<matches<'-', '_'>>();
static const auto op_parser =
(token("!=") | token("<=") | token(">=") | token("->") | token("=>")
| token(">>=") )
>> [](const char* s) {
return pure(symbol(s));
} | chr<matches<'+', '-', '*', '/', '=', '<', '>', '%' >>() >> [](char c) {
return pure(symbol(std::string(1, c)));
};
static const auto identifier_parser = initial_parser >> [](char c) {
return noskip(*rest_parser >> [c](std::deque<char>&& rest) {
const std::string tmp = c + std::string(rest.begin(), rest.end());
return pure(symbol(tmp));
});
};
static const auto symbol_parser = identifier_parser | op_parser;
static const auto qualified_parser =
(symbol_parser % chr<matches<selection_prefix>>()) >>
[](std::deque<symbol> parts) {
sexpr res = parts.front();
parts.pop_front();
for(symbol s : parts) {
res = symbol(std::string(1, selection_prefix) + s.get())
>>= res >>= sexpr::list();
}
return pure(res);
};
static const auto selection_parser =
chr<matches<selection_prefix>>() >> [](char c) {
return symbol_parser >> [c](symbol s) {
return pure(symbol(c + std::string(s.get())));
};
};
static const auto injection_parser =
chr<matches<injection_prefix>>() >> [](char c) {
return symbol_parser >> [c](symbol s) {
return pure(symbol(c + std::string(s.get())));
};
};
static auto expr_parser = any<sexpr>();
static const auto lparen = // debug("lparen") |=
token("(");
static const auto rparen = // debug("rparen") |=
skip(skip_parser, token(")"));
static const auto exprs_parser = // debug("exprs") |=
parser::ref(expr_parser) % separator_parser;
static const auto list_parser = // debug("list") |=
lparen >>= (exprs_parser | pure<std::deque<sexpr>>()) >> drop(rparen)
>> [](std::deque<sexpr>&& es) {
return pure(make_list(es.begin(), es.end()));
};
static const auto once =
(expr_parser =
skip(skip_parser,
debug("expr") |=
(qualified_parser >> as_expr)
| (selection_parser >> as_expr)
| (injection_parser >> as_expr)
| (op_parser >> as_expr)
| number_parser
| (list_parser >> as_expr))
, 0); (void) once;
// debug::stream = &std::clog;
return expr_parser(in);
}
void sexpr::iter(std::istream& in, std::function<void(sexpr)> cont) {
using namespace parser;
using exprs_type = std::deque<sexpr>;
static const auto program_parser = debug("prog") |=
kleene(parse) >> drop(debug("eof") |= eof())
| parser::error<exprs_type>("parse error");
(program_parser >> [cont](exprs_type es) {
std::for_each(es.begin(), es.end(), cont);
return pure(unit());
})(in);
}
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <FreeImagePlus.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <fstream>
#include <vector>
using std::cout;
using std::vector;
using std::string;
using std::ifstream;
using std::ios_base;
using glm::vec3;
using glm::vec4;
using glm::mat4;
using glm::translate;
using glm::rotate;
using glm::scale;
using glm::value_ptr;
const auto WINDOW_WIDTH = 800;
const auto WINDOW_HEIGHT = 600;
const auto WINDOW_TITLE = "GL Cook Book - Loading Textures.";
void updateKey(GLFWwindow* window, int key, int code, int action, int mode);
void printShaderStatus(GLuint shader);
GLuint makeMesh(vector<GLfloat> vertices, vector<GLuint> ids);
GLuint makeShader(GLenum shaderType, string text);
GLuint makeVertexShader(string path);
GLuint makeFragmentShader(string path);
GLuint makeShaderProgram(vector<GLuint> shaders);
GLuint makeTexture(string path);
string makeString(string path);
int main(int argc, char const *argv[])
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// GLEW has a bug for OS X where it still calls some legacy functions.
// We need this for now to prevent GLFW from crashing when legacy
// functions are called.
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
auto window = glfwCreateWindow(
WINDOW_WIDTH,
WINDOW_HEIGHT,
WINDOW_TITLE,
nullptr,
nullptr);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, updateKey);
glewExperimental = GL_TRUE;
glewInit();
// OS X has a bug that does not normalise the viewport coordinates
// at all so only uncomment this when it's really needed since GLFW
// have a normalized default anyway.
// glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
auto vertexShaderPath = "res/transform/vertex.glsl";
auto vertexShader = makeVertexShader(vertexShaderPath);
printShaderStatus(vertexShader);
auto fragmentShaderPath = "res/transform/fragment.glsl";
auto fragmentShader = makeFragmentShader(fragmentShaderPath);
printShaderStatus(fragmentShader);
auto program = makeShaderProgram({vertexShader, fragmentShader});
vector<GLfloat> vertices = {
// Positions // Colors // Texture Coords
0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 2.0f, 2.0f, // Top Right
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 2.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 2.0f // Top Left
};
vector<GLuint> ids = {
2, 3, 0,
0, 1, 2
};
auto vao = makeMesh(vertices, ids);
auto tex1 = makeTexture("res/images/container.jpg");
auto tex2 = makeTexture("res/images/awesomeface.png");
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
while (! glfwWindowShouldClose(window))
{
auto curTime = static_cast<float>(glfwGetTime());
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
auto trans1 = mat4(1.0f);
trans1 = rotate(trans1, curTime * 100.0f, vec3(0.0f, 0.0f, 1.0f));
trans1 = scale(trans1, vec3(0.5f, 0.5f, 0.5f));
trans1 = translate(trans1, vec3(0.75f, -0.75f, 0.0f));
auto transformId = glGetUniformLocation(program, "transform");
glUniformMatrix4fv(transformId, 1, GL_FALSE, value_ptr(trans1));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex1);
glUniform1i(glGetUniformLocation(program, "ourTexture1"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tex2);
glUniform1i(glGetUniformLocation(program, "ourTexture2"), 1);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, ids.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
auto trans2 = mat4(1.0f);
trans2 = rotate(trans2, curTime * 100.0f, vec3(0.0f, 0.0f, 1.0f));
trans2 = scale(trans2, vec3(0.5f, 0.5f, 0.5f));
trans2 = translate(trans2, vec3(-0.75f, 0.75f, 0.0f));
glUniformMatrix4fv(transformId, 1, GL_FALSE, value_ptr(trans2));
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, ids.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteProgram(program);
glfwTerminate();
return 0;
}
void updateKey(GLFWwindow* window, int key, int code, int action, int mode)
{
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void printShaderStatus(GLuint shader)
{
GLint success;
GLchar infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (! success) {
glGetShaderInfoLog(shader, 512, nullptr, infoLog);
std::cout << infoLog << "\n";
}
}
GLuint makeShader(GLenum shaderType, string text)
{
auto shader = glCreateShader(shaderType);
auto cstring = text.c_str();
glShaderSource(shader, 1, &cstring, nullptr);
glCompileShader(shader);
return shader;
}
GLuint makeVertexShader(string path)
{
return makeShader(GL_VERTEX_SHADER, makeString(path));
}
GLuint makeFragmentShader(string path)
{
return makeShader(GL_FRAGMENT_SHADER, makeString(path));
}
GLuint makeShaderProgram(vector<GLuint> shaders)
{
GLuint program = glCreateProgram();
for (auto s : shaders)
glAttachShader(program, s);
glLinkProgram(program);
return program;
}
GLuint makeTexture(string path)
{
GLuint id;
glGenTextures(1, &id);
fipImage image;
image.load(path.c_str());
image.convertTo32Bits();
auto data = image.accessPixels();
auto w = image.getWidth();
auto h = image.getHeight();
auto minSetting = GL_LINEAR_MIPMAP_LINEAR;
auto magSetting = GL_LINEAR;
glBindTexture(GL_TEXTURE_2D,id);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_BGRA,GL_UNSIGNED_BYTE,data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,minSetting);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,magSetting);
glGenerateMipmap(GL_TEXTURE_2D);
image.clear();
return id;
}
GLuint makeMesh(vector<GLfloat> vertices, vector<GLuint> ids)
{
GLuint vbo;
glGenBuffers(1, &vbo);
GLuint vao;
glGenVertexArrays(1, &vao);
GLuint ebo;
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
auto vtSize = vertices.size() * sizeof(GLfloat);
auto vtData = vertices.data();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vtSize, vtData, GL_STATIC_DRAW);
auto idSize = ids.size() * sizeof(GLuint);
auto idData = ids.data();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, idSize, idData, GL_STATIC_DRAW);
auto stride = sizeof(GLfloat) * 7;
auto vertexOff = (GLvoid*)(0);
auto colorOff = (GLvoid*)(sizeof(GLfloat) * 2);
auto texOff = (GLvoid*)(sizeof(GLfloat) * 5);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, vertexOff);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, colorOff);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride, texOff);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
return vao;
}
string makeString(string path)
{
ifstream file(path);
try
{
file.exceptions(ifstream::failbit);
}
catch (const ios_base::failure& err)
{
throw ios_base::failure(path + " is not available.");
}
file.seekg(0, std::ios::end);
auto size = file.tellg();
string buffer(size, ' ');
file.seekg(0);
file.read(&buffer[0], size);
file.close();
return buffer;
}<commit_msg>transform: Changed window title.<commit_after>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <FreeImagePlus.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <fstream>
#include <vector>
using std::cout;
using std::vector;
using std::string;
using std::ifstream;
using std::ios_base;
using glm::vec3;
using glm::vec4;
using glm::mat4;
using glm::translate;
using glm::rotate;
using glm::scale;
using glm::value_ptr;
const auto WINDOW_WIDTH = 800;
const auto WINDOW_HEIGHT = 600;
const auto WINDOW_TITLE = "GL Cook Book - Playing with Transformations.";
void updateKey(GLFWwindow* window, int key, int code, int action, int mode);
void printShaderStatus(GLuint shader);
GLuint makeMesh(vector<GLfloat> vertices, vector<GLuint> ids);
GLuint makeShader(GLenum shaderType, string text);
GLuint makeVertexShader(string path);
GLuint makeFragmentShader(string path);
GLuint makeShaderProgram(vector<GLuint> shaders);
GLuint makeTexture(string path);
string makeString(string path);
int main(int argc, char const *argv[])
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// GLEW has a bug for OS X where it still calls some legacy functions.
// We need this for now to prevent GLFW from crashing when legacy
// functions are called.
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
auto window = glfwCreateWindow(
WINDOW_WIDTH,
WINDOW_HEIGHT,
WINDOW_TITLE,
nullptr,
nullptr);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, updateKey);
glewExperimental = GL_TRUE;
glewInit();
// OS X has a bug that does not normalise the viewport coordinates
// at all so only uncomment this when it's really needed since GLFW
// have a normalized default anyway.
// glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
auto vertexShaderPath = "res/transform/vertex.glsl";
auto vertexShader = makeVertexShader(vertexShaderPath);
printShaderStatus(vertexShader);
auto fragmentShaderPath = "res/transform/fragment.glsl";
auto fragmentShader = makeFragmentShader(fragmentShaderPath);
printShaderStatus(fragmentShader);
auto program = makeShaderProgram({vertexShader, fragmentShader});
vector<GLfloat> vertices = {
// Positions // Colors // Texture Coords
0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 2.0f, 2.0f, // Top Right
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 2.0f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 2.0f // Top Left
};
vector<GLuint> ids = {
2, 3, 0,
0, 1, 2
};
auto vao = makeMesh(vertices, ids);
auto tex1 = makeTexture("res/images/container.jpg");
auto tex2 = makeTexture("res/images/awesomeface.png");
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
while (! glfwWindowShouldClose(window))
{
auto curTime = static_cast<float>(glfwGetTime());
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
auto trans1 = mat4(1.0f);
trans1 = rotate(trans1, curTime * 100.0f, vec3(0.0f, 0.0f, 1.0f));
trans1 = scale(trans1, vec3(0.5f, 0.5f, 0.5f));
trans1 = translate(trans1, vec3(0.75f, -0.75f, 0.0f));
auto transformId = glGetUniformLocation(program, "transform");
glUniformMatrix4fv(transformId, 1, GL_FALSE, value_ptr(trans1));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex1);
glUniform1i(glGetUniformLocation(program, "ourTexture1"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tex2);
glUniform1i(glGetUniformLocation(program, "ourTexture2"), 1);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, ids.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
auto trans2 = mat4(1.0f);
trans2 = rotate(trans2, curTime * 100.0f, vec3(0.0f, 0.0f, 1.0f));
trans2 = scale(trans2, vec3(0.5f, 0.5f, 0.5f));
trans2 = translate(trans2, vec3(-0.75f, 0.75f, 0.0f));
glUniformMatrix4fv(transformId, 1, GL_FALSE, value_ptr(trans2));
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, ids.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteProgram(program);
glfwTerminate();
return 0;
}
void updateKey(GLFWwindow* window, int key, int code, int action, int mode)
{
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
void printShaderStatus(GLuint shader)
{
GLint success;
GLchar infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (! success) {
glGetShaderInfoLog(shader, 512, nullptr, infoLog);
std::cout << infoLog << "\n";
}
}
GLuint makeShader(GLenum shaderType, string text)
{
auto shader = glCreateShader(shaderType);
auto cstring = text.c_str();
glShaderSource(shader, 1, &cstring, nullptr);
glCompileShader(shader);
return shader;
}
GLuint makeVertexShader(string path)
{
return makeShader(GL_VERTEX_SHADER, makeString(path));
}
GLuint makeFragmentShader(string path)
{
return makeShader(GL_FRAGMENT_SHADER, makeString(path));
}
GLuint makeShaderProgram(vector<GLuint> shaders)
{
GLuint program = glCreateProgram();
for (auto s : shaders)
glAttachShader(program, s);
glLinkProgram(program);
return program;
}
GLuint makeTexture(string path)
{
GLuint id;
glGenTextures(1, &id);
fipImage image;
image.load(path.c_str());
image.convertTo32Bits();
auto data = image.accessPixels();
auto w = image.getWidth();
auto h = image.getHeight();
auto minSetting = GL_LINEAR_MIPMAP_LINEAR;
auto magSetting = GL_LINEAR;
glBindTexture(GL_TEXTURE_2D,id);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_BGRA,GL_UNSIGNED_BYTE,data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,minSetting);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,magSetting);
glGenerateMipmap(GL_TEXTURE_2D);
image.clear();
return id;
}
GLuint makeMesh(vector<GLfloat> vertices, vector<GLuint> ids)
{
GLuint vbo;
glGenBuffers(1, &vbo);
GLuint vao;
glGenVertexArrays(1, &vao);
GLuint ebo;
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
auto vtSize = vertices.size() * sizeof(GLfloat);
auto vtData = vertices.data();
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vtSize, vtData, GL_STATIC_DRAW);
auto idSize = ids.size() * sizeof(GLuint);
auto idData = ids.data();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, idSize, idData, GL_STATIC_DRAW);
auto stride = sizeof(GLfloat) * 7;
auto vertexOff = (GLvoid*)(0);
auto colorOff = (GLvoid*)(sizeof(GLfloat) * 2);
auto texOff = (GLvoid*)(sizeof(GLfloat) * 5);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, vertexOff);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, colorOff);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride, texOff);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
return vao;
}
string makeString(string path)
{
ifstream file(path);
try
{
file.exceptions(ifstream::failbit);
}
catch (const ios_base::failure& err)
{
throw ios_base::failure(path + " is not available.");
}
file.seekg(0, std::ios::end);
auto size = file.tellg();
string buffer(size, ' ');
file.seekg(0);
file.read(&buffer[0], size);
file.close();
return buffer;
}<|endoftext|> |
<commit_before>
#include "Path.hpp"
#include<iostream>
namespace Ethereum{namespace Connector{
const std::string& Path::toString() const
{
return _path;
}
const char *Path::toCString() const
{
return _path.c_str();
}
std::string DefaultGethPath::RootDirectory()
{
std::string path;
#if defined(__APPLE_OS__)
path += getenv("HOME");
path += "/Library/Ethereum/";
#elif defined(__LINUX_OS__)
path += getenv("HOME");
path += "/.ethereum/";
#elif defined(__WINDOWS_OS__)
path += getenv("HOMEPATH");
path += "\\AppData\\Roaming\\Ethereum\\";
#else
#warning "No OS detected"
#endif
return path;
}
DefaultGethPath::DefaultGethPath()
{
_path = "ipc:";
_path += RootDirectory();
_path += "geth.ipc";
}
std::string DefaultEthPath::RootDirectory()
{
std::string path;
#if defined(__APPLE_OS__)
path += getenv("HOME");
path += "/.ethereum/";
#elif defined(__LINUX_OS__)
path += getenv("HOME");
path += "/.ethereum/";
#elif defined(__WINDOWS_OS__)
path += getenv("HOMEPATH");
path += "\\AppData\\Roaming\\Ethereum\\";
#else
#warning "No OS detected"
#endif
return path;
}
DefaultEthPath::DefaultEthPath()
{
_path = "ipc:";
_path += RootDirectory();
_path += "eth.ipc";
}
}}
<commit_msg>cleanup<commit_after>
#include "Path.hpp"
namespace Ethereum{namespace Connector{
const std::string& Path::toString() const
{
return _path;
}
const char *Path::toCString() const
{
return _path.c_str();
}
std::string DefaultGethPath::RootDirectory()
{
std::string path;
#if defined(__APPLE_OS__)
path += getenv("HOME");
path += "/Library/Ethereum/";
#elif defined(__LINUX_OS__)
path += getenv("HOME");
path += "/.ethereum/";
#elif defined(__WINDOWS_OS__)
path += getenv("HOMEPATH");
path += "\\AppData\\Roaming\\Ethereum\\";
#else
#warning "No OS detected"
#endif
return path;
}
DefaultGethPath::DefaultGethPath()
{
_path = "ipc:";
_path += RootDirectory();
_path += "geth.ipc";
}
std::string DefaultEthPath::RootDirectory()
{
std::string path;
#if defined(__APPLE_OS__)
path += getenv("HOME");
path += "/.ethereum/";
#elif defined(__LINUX_OS__)
path += getenv("HOME");
path += "/.ethereum/";
#elif defined(__WINDOWS_OS__)
path += getenv("HOMEPATH");
path += "\\AppData\\Roaming\\Ethereum\\";
#else
#warning "No OS detected"
#endif
return path;
}
DefaultEthPath::DefaultEthPath()
{
_path = "ipc:";
_path += RootDirectory();
_path += "eth.ipc";
}
}}
<|endoftext|> |
<commit_before>#include "tests.h"
using namespace swoole;
static void coro1(void *arg)
{
long cid = coroutine_get_current_cid();
Coroutine *co = coroutine_get_by_id(cid);
co->yield();
}
TEST(coroutine, create)
{
long cid = Coroutine::create(coro1, NULL);
ASSERT_GT(cid, 0);
coroutine_get_by_id(cid)->resume();
}
static void coro2(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9801, 0.5);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ECONNREFUSED);
}
TEST(coroutine, socket_connect_refused)
{
long cid = Coroutine::create(coro2, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro3(void *arg)
{
Socket sock(SW_SOCK_TCP);
sock.set_timeout(0.5);
bool retval = sock.connect("192.0.0.1", 9801);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ETIMEDOUT);
}
TEST(coroutine, socket_connect_timeout)
{
long cid = Coroutine::create(coro3, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro4(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("www.baidu.com", 80, 0.5);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_connect_with_dns)
{
long cid = Coroutine::create(coro4, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro5(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("echo", 5);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(strcmp(buf, "hello world\n"), 0);
}
TEST(coroutine, socket_recv_success)
{
long cid = Coroutine::create(coro5, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro6(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("close", 6);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(n, 0);
}
TEST(coroutine, socket_recv_fail)
{
long cid = Coroutine::create(coro6, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
TEST(coroutine, socket_bind_success)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
}
TEST(coroutine, socket_bind_fail)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("192.111.11.1", 9909);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, EADDRNOTAVAIL);
}
TEST(coroutine, socket_listen)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
}
/**
* Accept
*/
static void coro7(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
Socket *conn = sock.accept();
ASSERT_NE(conn, nullptr);
}
/**
* Connect
*/
static void coro8(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9909, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_accept)
{
Coroutine::create(coro7, NULL);
Coroutine::create(coro8, NULL);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro9(void *arg)
{
Socket sock(SW_SOCK_TCP);
auto retval = sock.resolve("www.qq.com");
ASSERT_EQ(retval, "180.163.26.39");
}
TEST(coroutine, socket_resolve)
{
Coroutine::create(coro9, NULL);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
<commit_msg>added default value<commit_after>#include "tests.h"
using namespace swoole;
static void coro1(void *arg)
{
long cid = coroutine_get_current_cid();
Coroutine *co = coroutine_get_by_id(cid);
co->yield();
}
TEST(coroutine, create)
{
long cid = Coroutine::create(coro1);
ASSERT_GT(cid, 0);
coroutine_get_by_id(cid)->resume();
}
static void coro2(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9801, 0.5);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ECONNREFUSED);
}
TEST(coroutine, socket_connect_refused)
{
long cid = Coroutine::create(coro2);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro3(void *arg)
{
Socket sock(SW_SOCK_TCP);
sock.set_timeout(0.5);
bool retval = sock.connect("192.0.0.1", 9801);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, ETIMEDOUT);
}
TEST(coroutine, socket_connect_timeout)
{
long cid = Coroutine::create(coro3, NULL);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro4(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("www.baidu.com", 80, 0.5);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_connect_with_dns)
{
long cid = Coroutine::create(coro4);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro5(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("echo", 5);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(strcmp(buf, "hello world\n"), 0);
}
TEST(coroutine, socket_recv_success)
{
long cid = Coroutine::create(coro5);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro6(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9501, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
sock.send("close", 6);
char buf[128];
int n = sock.recv(buf, sizeof(buf));
ASSERT_EQ(n, 0);
}
TEST(coroutine, socket_recv_fail)
{
long cid = Coroutine::create(coro6);
if (cid < 0)
{
return;
}
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
TEST(coroutine, socket_bind_success)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
}
TEST(coroutine, socket_bind_fail)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("192.111.11.1", 9909);
ASSERT_EQ(retval, false);
ASSERT_EQ(sock.errCode, EADDRNOTAVAIL);
}
TEST(coroutine, socket_listen)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
}
/**
* Accept
*/
static void coro7(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.bind("127.0.0.1", 9909);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.listen(128), true);
Socket *conn = sock.accept();
ASSERT_NE(conn, nullptr);
}
/**
* Connect
*/
static void coro8(void *arg)
{
Socket sock(SW_SOCK_TCP);
bool retval = sock.connect("127.0.0.1", 9909, -1);
ASSERT_EQ(retval, true);
ASSERT_EQ(sock.errCode, 0);
}
TEST(coroutine, socket_accept)
{
Coroutine::create(coro7);
Coroutine::create(coro8);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
static void coro9(void *arg)
{
Socket sock(SW_SOCK_TCP);
auto retval = sock.resolve("www.qq.com");
ASSERT_EQ(retval, "180.163.26.39");
}
TEST(coroutine, socket_resolve)
{
Coroutine::create(coro9);
SwooleG.main_reactor->wait(SwooleG.main_reactor, nullptr);
}
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1
#endif
#include "main.hxx"
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/disable_warnings.hh>
# if HAVE_DUNE_GRID
# include <dune/grid/sgrid.hh>
# endif
# include <dune/geometry/quadraturerules.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/functions/flattop.hh>
#include "functions.hh"
#if HAVE_DUNE_GRID
using namespace Dune;
using namespace Stuff;
template< class G >
class FlatTopFunctionType
{
typedef typename G::template Codim< 0 >::Entity E;
typedef typename G::ctype D;
static const unsigned int d = G::dimension;
typedef double R;
static const unsigned int r = 1;
static const unsigned int rC = 1;
public:
typedef Functions::FlatTop< E, D, d, R, r, rC > value;
}; // struct FlatTopFunctionType
template< class DimDomain >
class FlatTopFunctionTest
: public FunctionTest< typename FlatTopFunctionType< SGrid< DimDomain::value, DimDomain::value > >::value >
{
protected:
typedef SGrid< DimDomain::value, DimDomain::value > GridType;
typedef typename FlatTopFunctionType< GridType >::value FunctionType;
static std::shared_ptr< GridType > create_grid()
{
return Stuff::Grid::Providers::Cube< GridType >(0.0, 3.0, 12).grid_ptr();
}
template< class... Args >
static std::unique_ptr< FunctionType > create(Args&& ...args)
{
return std::unique_ptr< FunctionType >(new FunctionType(std::forward< Args >(args)...));
}
template< class P, class V, class L, class R, class D, class E >
static void check(const P& point, const V& value, const L& left, const R& right, const D& delta, const E& top_value)
{
if (Common::FloatCmp::lt(point, left - delta) || Common::FloatCmp::gt(point, right + delta)) {
// outside
EXPECT_EQ(0.0, value) << point;
} else if (Common::FloatCmp::ge(point, left) && Common::FloatCmp::le(point, right)) {
// inside
EXPECT_EQ(top_value, value) << point;
} else {
// boundary layer
if (top_value > 0.0) {
EXPECT_GE(top_value, value) << point[0];
EXPECT_LE(0.0, value) << point[0];
} else {
EXPECT_LE(top_value, value) << point[0];
EXPECT_GE(0.0, value) << point[0];
}
}
} // ... check(...)
}; // class FlatTopFunctionTest
typedef testing::Types<
Int< 1 >
, Int< 2 >
, Int< 3 >
> DimDomains;
TYPED_TEST_CASE(FlatTopFunctionTest, DimDomains);
TYPED_TEST(FlatTopFunctionTest, static_interface_check) {
this->static_interface_check();
}
TYPED_TEST(FlatTopFunctionTest, static_create_check) {
this->static_create_check();
}
TYPED_TEST(FlatTopFunctionTest, dynamic_interface_check) {
this->dynamic_interface_check(*(this->create()), *(this->create_grid()));
}
TYPED_TEST(FlatTopFunctionTest, copy_check) {
this->copy_check(*(this->create()));
}
TYPED_TEST(FlatTopFunctionTest, evaluate_check) {
auto grid_ptr = this->create_grid();
typedef FieldVector< double, TypeParam::value > DomainType;
const DomainType left(1.0);
const DomainType right(2.0);
const DomainType delta(0.25);
const double value = 1.75;
auto func = this->create(left, right, delta, value, "bar");
// func->visualize(grid_ptr->leafGridView(), "foo");
for (const auto& entity : Stuff::Common::viewRange(grid_ptr->leafGridView())) {
const auto local_func = func->local_function(entity);
const auto& quadrature
= QuadratureRules< double, TypeParam::value >::rule(entity.type(),
boost::numeric_cast< int >(local_func->order() + 2));
for (const auto& element : quadrature) {
const auto& local_point = element.position();
const auto point = entity.geometry().global(local_point);
const auto val = local_func->evaluate(local_point);
this->check(point, val, left, right, delta, value);
}
}
}
#else // HAVE_DUNE_GRID
TYPED_TEST(DISABLED_FlatTopFunctionTest, static_interface_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, static_create_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, dynamic_interface_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, copy_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, evaluate_check) {}
#endif // HAVE_DUNE_GRID
<commit_msg>[test.functions_flattop] update<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1
#endif
#include "main.hxx"
#include <memory>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/stuff/common/disable_warnings.hh>
# if HAVE_DUNE_GRID
# include <dune/grid/sgrid.hh>
# endif
# include <dune/geometry/quadraturerules.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/functions/flattop.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/fvector.hh>
#include "functions.hh"
#if HAVE_DUNE_GRID
using namespace Dune;
using namespace Stuff;
template< class G >
class FlatTopFunctionType
{
typedef typename G::template Codim< 0 >::Entity E;
typedef typename G::ctype D;
static const unsigned int d = G::dimension;
typedef double R;
static const unsigned int r = 1;
static const unsigned int rC = 1;
public:
typedef Functions::FlatTop< E, D, d, R, r, rC > value;
}; // struct FlatTopFunctionType
template< class DimDomain >
class FlatTopFunctionTest
: public FunctionTest< typename FlatTopFunctionType< SGrid< DimDomain::value, DimDomain::value > >::value >
{
protected:
typedef SGrid< DimDomain::value, DimDomain::value > GridType;
typedef typename FlatTopFunctionType< GridType >::value FunctionType;
static std::shared_ptr< GridType > create_grid()
{
return Stuff::Grid::Providers::Cube< GridType >(0, 3, 12).grid_ptr();
}
template< class P, class V, class L, class R, class D, class E >
static void check(const P& point, const V& value, const L& left, const R& right, const D& delta, const E& top_value)
{
if (Common::FloatCmp::lt(point, left - delta) || Common::FloatCmp::gt(point, right + delta)) {
// outside
EXPECT_EQ(0.0, value) << point;
} else if (Common::FloatCmp::ge(point, left + delta) && Common::FloatCmp::le(point, right - delta)) {
// inside
EXPECT_EQ(top_value, value) << point;
} else {
// boundary layer
if (top_value > 0.0) {
EXPECT_GE(top_value, value) << point[0];
EXPECT_LE(0.0, value) << point[0];
} else {
EXPECT_LE(top_value, value) << point[0];
EXPECT_GE(0.0, value) << point[0];
}
}
} // ... check(...)
}; // class FlatTopFunctionTest
typedef testing::Types<
Int< 1 >
, Int< 2 >
, Int< 3 >
> DimDomains;
TYPED_TEST_CASE(FlatTopFunctionTest, DimDomains);
TYPED_TEST(FlatTopFunctionTest, static_interface_check) {
this->static_interface_check();
}
TYPED_TEST(FlatTopFunctionTest, static_create_check) {
this->static_create_check();
}
TYPED_TEST(FlatTopFunctionTest, dynamic_interface_check) {
this->dynamic_interface_check(*(TestFixture::FunctionType::create()), *(this->create_grid()));
}
TYPED_TEST(FlatTopFunctionTest, copy_check) {
this->copy_check(*(TestFixture::FunctionType::create()));
}
TYPED_TEST(FlatTopFunctionTest, evaluate_check) {
auto grid_ptr = this->create_grid();
typedef DSC::FieldVector< double, TypeParam::value > DomainType;
const DomainType left(1);
const DomainType right(2);
const DomainType delta(1e-6);
const double value = 20;
typename TestFixture::FunctionType func(left, right, delta, value, "bar");
func.visualize(grid_ptr->leafGridView(), "dim_" + DSC::toString(int(TypeParam::value)));
for (const auto& entity : Stuff::Common::viewRange(grid_ptr->leafGridView())) {
const auto local_func = func.local_function(entity);
const auto& quadrature
= QuadratureRules< double, TypeParam::value >::rule(entity.type(),
boost::numeric_cast< int >(local_func->order() + 2));
for (const auto& element : quadrature) {
const auto& local_point = element.position();
const auto point = entity.geometry().global(local_point);
const auto val = local_func->evaluate(local_point);
this->check(point, val, left, right, delta, value);
}
}
}
#else // HAVE_DUNE_GRID
TYPED_TEST(DISABLED_FlatTopFunctionTest, static_interface_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, static_create_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, dynamic_interface_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, copy_check) {}
TYPED_TEST(DISABLED_FlatTopFunctionTest, evaluate_check) {}
#endif // HAVE_DUNE_GRID
<|endoftext|> |
<commit_before>/*
* TTBlue 4rth order Butterworth Lowpass Filter Object
* Copyright © 2008, Trond Lossius
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTLowpassButterworth4.h"
TTLowpassButterworth4::TTLowpassButterworth4(TTUInt16 newMaxNumChannels)
: TTAudioObject("filter.lowpass.butterworth", newMaxNumChannels),
xm1(NULL), xm2(NULL), xm3(NULL), xm4(NULL), ym1(NULL), ym2(NULL), ym3(NULL), ym4(NULL)
{
// register attributes
registerAttribute(TT("frequency"), kTypeFloat64, &attrFrequency, (TTSetterMethod)&TTLowpassButterworth4::setFrequency);
// register for notifications from the parent class so we can allocate memory as required
registerMessage(TT("updateMaxNumChannels"), (TTMethod)&TTLowpassButterworth4::updateMaxNumChannels);
// register for notifications from the parent class so we can recalculate coefficients as required
registerMessage(TT("updateSr"), (TTMethod)&TTLowpassButterworth4::updateSr, kTTMessagePassNone);
// make the clear method available to the outside world
registerMessage(TT("clear"), (TTMethod)&TTLowpassButterworth4::clear, kTTMessagePassNone);
// Set Defaults...
setAttributeValue(TT("maxNumChannels"), newMaxNumChannels); // This attribute is inherited
setAttributeValue(TT("frequency"), 1000.0);
setProcess((TTProcessMethod)&TTLowpassButterworth4::processAudio);
}
TTLowpassButterworth4::~TTLowpassButterworth4()
{
free(xm1);
free(xm2);
free(xm3);
free(xm4);
free(ym1);
free(ym2);
free(ym3);
free(xm4);
}
TTErr TTLowpassButterworth4::updateMaxNumChannels(const TTValue& oldMaxNumChannels)
{
if(xm1)
free(xm1);
if(xm2)
free(xm2);
if(xm3)
free(xm3);
if(xm4)
free(xm4);
if(ym1)
free(ym1);
if(ym2)
free(ym2);
if(ym3)
free(ym3);
if(ym4)
free(ym4);
xm1 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
xm2 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
xm3 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
xm4 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym1 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym2 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym3 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym4 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
clear();
return kTTErrNone;
}
TTErr TTLowpassButterworth4::updateSr()
{
TTValue v(attrFrequency);
return setFrequency(v);
}
TTErr TTLowpassButterworth4::clear()
{
short i;
for(i=0; i<maxNumChannels; i++){
xm1[i] = 0.0;
xm2[i] = 0.0;
xm3[i] = 0.0;
xm4[i] = 0.0;
ym1[i] = 0.0;
ym2[i] = 0.0;
ym3[i] = 0.0;
ym4[i] = 0.0;
}
return kTTErrNone;
}
TTErr TTLowpassButterworth4::setFrequency(const TTValue& newValue)
{
attrFrequency = TTClip((double)newValue, 10., (sr*0.475));
wc = 2*kTTPi*attrFrequency;
wc2 = wc*wc;
wc3 = wc2*wc;
wc4 = wc3*wc;
k = 2*kTTPi*attrFrequency/tan(kTTPi*attrFrequency/sr);
k2 = k*k;
k3 = k2 * k;
k4 = k3 * k;
a = 2*(cos(kTTPi/8)+cos(3*kTTPi/8));
b = 2*(1+2*cos(kTTPi/8)*cos(3*kTTPi/8));
a0 = (wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a1 = (4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a2 = (6*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a3 = (4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a4 = (wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b1 = (-4*k4 - 2*a*wc*k3 + 2*a*wc3*k + 4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b2 = (6*k4 - 2*b*wc2*k2 + 6*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b3 = (-4*k4 + 2*a*wc*k3 - 2*a*wc3*k + 4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b4 = (k4 - a*wc*k3 + b*wc2*k2 - a*wc3*k + wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);;
return kTTErrNone;
}
TTErr TTLowpassButterworth4::processAudio(TTAudioSignal& in, TTAudioSignal& out)
{
TTUInt16 vs;
TTSampleValue *inSample,
*outSample;
TTFloat64 tempx,
tempy;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
// This outside loop works through each channel one at a time
for(channel=0; channel<numchannels; channel++){
inSample = in.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
// This inner loop works through each sample within the channel one at a time
while(vs--){
tempx = *inSample++;
tempy = antiDenormal(a0*tempx + a1*xm1[channel] + a2*xm2[channel] + a3*xm3[channel] + a4*xm4[channel]
- b1*ym1[channel] - b2*ym2[channel] - b3*ym3[channel] - b4*ym4[channel]);
xm4[channel] = xm3[channel];
xm3[channel] = xm2[channel];
xm2[channel] = xm1[channel];
xm1[channel] = tempx;
ym4[channel] = ym3[channel];
ym3[channel] = ym2[channel];
ym2[channel] = ym1[channel];
ym1[channel] = tempy;
*outSample++ = tempy;
}
}
return kTTErrNone;
}
<commit_msg>Fix for crash caused by trying to free memory that was already freed due to what looks like a typo in the 4-pole butterworth filter.<commit_after>/*
* TTBlue 4rth order Butterworth Lowpass Filter Object
* Copyright © 2008, Trond Lossius
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTLowpassButterworth4.h"
TTLowpassButterworth4::TTLowpassButterworth4(TTUInt16 newMaxNumChannels)
: TTAudioObject("filter.lowpass.butterworth", newMaxNumChannels),
xm1(NULL), xm2(NULL), xm3(NULL), xm4(NULL), ym1(NULL), ym2(NULL), ym3(NULL), ym4(NULL)
{
// register attributes
registerAttribute(TT("frequency"), kTypeFloat64, &attrFrequency, (TTSetterMethod)&TTLowpassButterworth4::setFrequency);
// register for notifications from the parent class so we can allocate memory as required
registerMessage(TT("updateMaxNumChannels"), (TTMethod)&TTLowpassButterworth4::updateMaxNumChannels);
// register for notifications from the parent class so we can recalculate coefficients as required
registerMessage(TT("updateSr"), (TTMethod)&TTLowpassButterworth4::updateSr, kTTMessagePassNone);
// make the clear method available to the outside world
registerMessage(TT("clear"), (TTMethod)&TTLowpassButterworth4::clear, kTTMessagePassNone);
// Set Defaults...
setAttributeValue(TT("maxNumChannels"), newMaxNumChannels); // This attribute is inherited
setAttributeValue(TT("frequency"), 1000.0);
setProcess((TTProcessMethod)&TTLowpassButterworth4::processAudio);
}
TTLowpassButterworth4::~TTLowpassButterworth4()
{
free(xm1);
free(xm2);
free(xm3);
free(xm4);
free(ym1);
free(ym2);
free(ym3);
free(ym4);
}
TTErr TTLowpassButterworth4::updateMaxNumChannels(const TTValue& oldMaxNumChannels)
{
if(xm1)
free(xm1);
if(xm2)
free(xm2);
if(xm3)
free(xm3);
if(xm4)
free(xm4);
if(ym1)
free(ym1);
if(ym2)
free(ym2);
if(ym3)
free(ym3);
if(ym4)
free(ym4);
xm1 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
xm2 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
xm3 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
xm4 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym1 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym2 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym3 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
ym4 = (TTFloat64*)malloc(sizeof(TTFloat64) * maxNumChannels);
clear();
return kTTErrNone;
}
TTErr TTLowpassButterworth4::updateSr()
{
TTValue v(attrFrequency);
return setFrequency(v);
}
TTErr TTLowpassButterworth4::clear()
{
short i;
for(i=0; i<maxNumChannels; i++){
xm1[i] = 0.0;
xm2[i] = 0.0;
xm3[i] = 0.0;
xm4[i] = 0.0;
ym1[i] = 0.0;
ym2[i] = 0.0;
ym3[i] = 0.0;
ym4[i] = 0.0;
}
return kTTErrNone;
}
TTErr TTLowpassButterworth4::setFrequency(const TTValue& newValue)
{
attrFrequency = TTClip((double)newValue, 10., (sr*0.475));
wc = 2*kTTPi*attrFrequency;
wc2 = wc*wc;
wc3 = wc2*wc;
wc4 = wc3*wc;
k = 2*kTTPi*attrFrequency/tan(kTTPi*attrFrequency/sr);
k2 = k*k;
k3 = k2 * k;
k4 = k3 * k;
a = 2*(cos(kTTPi/8)+cos(3*kTTPi/8));
b = 2*(1+2*cos(kTTPi/8)*cos(3*kTTPi/8));
a0 = (wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a1 = (4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a2 = (6*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a3 = (4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
a4 = (wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b1 = (-4*k4 - 2*a*wc*k3 + 2*a*wc3*k + 4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b2 = (6*k4 - 2*b*wc2*k2 + 6*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b3 = (-4*k4 + 2*a*wc*k3 - 2*a*wc3*k + 4*wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);
b4 = (k4 - a*wc*k3 + b*wc2*k2 - a*wc3*k + wc4) / (k4 + a*wc*k3 + b*wc2*k2 + a*wc3*k + wc4);;
return kTTErrNone;
}
TTErr TTLowpassButterworth4::processAudio(TTAudioSignal& in, TTAudioSignal& out)
{
TTUInt16 vs;
TTSampleValue *inSample,
*outSample;
TTFloat64 tempx,
tempy;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
// This outside loop works through each channel one at a time
for(channel=0; channel<numchannels; channel++){
inSample = in.sampleVectors[channel];
outSample = out.sampleVectors[channel];
vs = in.getVectorSize();
// This inner loop works through each sample within the channel one at a time
while(vs--){
tempx = *inSample++;
tempy = antiDenormal(a0*tempx + a1*xm1[channel] + a2*xm2[channel] + a3*xm3[channel] + a4*xm4[channel]
- b1*ym1[channel] - b2*ym2[channel] - b3*ym3[channel] - b4*ym4[channel]);
xm4[channel] = xm3[channel];
xm3[channel] = xm2[channel];
xm2[channel] = xm1[channel];
xm1[channel] = tempx;
ym4[channel] = ym3[channel];
ym3[channel] = ym2[channel];
ym2[channel] = ym1[channel];
ym1[channel] = tempy;
*outSample++ = tempy;
}
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <svl/intitem.hxx>
#include <editeng/editeng.hxx>
#include <editeng/editview.hxx>
#include <editeng/editdata.hxx>
#include <editeng/eerdll.hxx>
#include <editeng/lrspitem.hxx>
#include <editeng/fhgtitem.hxx>
#define _OUTLINER_CXX
#include <editeng/outliner.hxx>
#include <outleeng.hxx>
#include <paralist.hxx>
#include <editeng/editrids.hrc>
#include <svl/itemset.hxx>
#include <editeng/eeitem.hxx>
#include <editeng/editstat.hxx>
#include "outlundo.hxx"
OutlinerEditEng::OutlinerEditEng( Outliner* pEngOwner, SfxItemPool* pPool )
: EditEngine( pPool )
{
pOwner = pEngOwner;
}
OutlinerEditEng::~OutlinerEditEng()
{
}
void OutlinerEditEng::PaintingFirstLine( sal_uInt16 nPara, const Point& rStartPos, long nBaseLineY, const Point& rOrigin, short nOrientation, OutputDevice* pOutDev )
{
if( GetControlWord() && EE_CNTRL_OUTLINER )
{
PaintFirstLineInfo aInfo( nPara, rStartPos, nBaseLineY, rOrigin, nOrientation, pOutDev );
pOwner->maPaintFirstLineHdl.Call( &aInfo );
}
pOwner->PaintBullet( nPara, rStartPos, rOrigin, nOrientation, pOutDev );
}
const SvxNumberFormat* OutlinerEditEng::GetNumberFormat( sal_uInt16 nPara ) const
{
const SvxNumberFormat* pFmt = NULL;
if (pOwner)
pFmt = pOwner->GetNumberFormat( nPara );
return pFmt;
}
Rectangle OutlinerEditEng::GetBulletArea( sal_uInt16 nPara )
{
Rectangle aBulletArea = Rectangle( Point(), Point() );
if ( nPara < pOwner->pParaList->GetParagraphCount() )
{
if ( pOwner->ImplHasBullet( nPara ) )
aBulletArea = pOwner->ImpCalcBulletArea( nPara, sal_False, sal_False );
}
return aBulletArea;
}
void OutlinerEditEng::ParagraphInserted( sal_uInt16 nNewParagraph )
{
pOwner->ParagraphInserted( nNewParagraph );
EditEngine::ParagraphInserted( nNewParagraph );
}
void OutlinerEditEng::ParagraphDeleted( sal_uInt16 nDeletedParagraph )
{
pOwner->ParagraphDeleted( nDeletedParagraph );
EditEngine::ParagraphDeleted( nDeletedParagraph );
}
void OutlinerEditEng::ParagraphConnected( sal_uInt16 /*nLeftParagraph*/, sal_uInt16 nRightParagraph )
{
if( pOwner && pOwner->IsUndoEnabled() && !const_cast<EditEngine&>(pOwner->GetEditEngine()).IsInUndo() )
{
Paragraph* pPara = pOwner->GetParagraph( nRightParagraph );
if( pPara && pOwner->HasParaFlag( pPara, PARAFLAG_ISPAGE ) )
{
pOwner->InsertUndo( new OutlinerUndoChangeParaFlags( pOwner, nRightParagraph, PARAFLAG_ISPAGE, 0 ) );
}
}
}
void OutlinerEditEng::StyleSheetChanged( SfxStyleSheet* pStyle )
{
pOwner->StyleSheetChanged( pStyle );
}
void OutlinerEditEng::ParaAttribsChanged( sal_uInt16 nPara )
{
pOwner->ParaAttribsChanged( nPara );
}
sal_Bool OutlinerEditEng::SpellNextDocument()
{
return pOwner->SpellNextDocument();
}
sal_Bool OutlinerEditEng::ConvertNextDocument()
{
return pOwner->ConvertNextDocument();
}
XubString OutlinerEditEng::GetUndoComment( sal_uInt16 nUndoId ) const
{
switch( nUndoId )
{
case OLUNDO_DEPTH:
return XubString( EditResId( RID_OUTLUNDO_DEPTH ));
case OLUNDO_EXPAND:
return XubString( EditResId( RID_OUTLUNDO_EXPAND ));
case OLUNDO_COLLAPSE:
return XubString( EditResId( RID_OUTLUNDO_COLLAPSE ));
case OLUNDO_ATTR:
return XubString( EditResId( RID_OUTLUNDO_ATTR ));
case OLUNDO_INSERT:
return XubString( EditResId( RID_OUTLUNDO_INSERT ));
default:
return EditEngine::GetUndoComment( nUndoId );
}
}
void OutlinerEditEng::DrawingText( const Point& rStartPos, const XubString& rText, sal_uInt16 nTextStart, sal_uInt16 nTextLen,
const sal_Int32* pDXArray, const SvxFont& rFont, sal_uInt16 nPara, sal_uInt16 nIndex, sal_uInt8 nRightToLeft,
const EEngineData::WrongSpellVector* pWrongSpellVector,
const SvxFieldData* pFieldData,
bool bEndOfLine,
bool bEndOfParagraph,
bool bEndOfBullet,
const ::com::sun::star::lang::Locale* pLocale,
const Color& rOverlineColor,
const Color& rTextLineColor)
{
pOwner->DrawingText(rStartPos,rText,nTextStart,nTextLen,pDXArray,rFont,nPara,nIndex,nRightToLeft,
pWrongSpellVector, pFieldData, bEndOfLine, bEndOfParagraph, bEndOfBullet, pLocale, rOverlineColor, rTextLineColor);
}
void OutlinerEditEng::DrawingTab( const Point& rStartPos, long nWidth, const String& rChar,
const SvxFont& rFont, sal_uInt16 nPara, xub_StrLen nIndex, sal_uInt8 nRightToLeft,
bool bEndOfLine, bool bEndOfParagraph,
const Color& rOverlineColor, const Color& rTextLineColor)
{
pOwner->DrawingTab(rStartPos, nWidth, rChar, rFont, nPara, nIndex, nRightToLeft,
bEndOfLine, bEndOfParagraph, rOverlineColor, rTextLineColor );
}
void OutlinerEditEng::FieldClicked( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos )
{
EditEngine::FieldClicked( rField, nPara, nPos ); // If URL
pOwner->FieldClicked( rField, nPara, nPos );
}
void OutlinerEditEng::FieldSelected( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos )
{
pOwner->FieldSelected( rField, nPara, nPos );
}
XubString OutlinerEditEng::CalcFieldValue( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos, Color*& rpTxtColor, Color*& rpFldColor )
{
return pOwner->CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor );
}
void OutlinerEditEng::SetParaAttribs( sal_uInt16 nPara, const SfxItemSet& rSet )
{
Paragraph* pPara = pOwner->pParaList->GetParagraph( nPara );
if( pPara )
{
if ( !IsInUndo() && IsUndoEnabled() )
pOwner->UndoActionStart( OLUNDO_ATTR );
EditEngine::SetParaAttribs( (sal_uInt16)nPara, rSet );
pOwner->ImplCheckNumBulletItem( (sal_uInt16)nPara );
// #i100014#
// It is not a good idea to substract 1 from a count and cast the result
// to USHORT without check, if the count is 0.
pOwner->ImplCheckParagraphs( (sal_uInt16)nPara, (sal_uInt16) (pOwner->pParaList->GetParagraphCount()) );
if ( !IsInUndo() && IsUndoEnabled() )
pOwner->UndoActionEnd( OLUNDO_ATTR );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: use of logical '&&' with constant operand<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <svl/intitem.hxx>
#include <editeng/editeng.hxx>
#include <editeng/editview.hxx>
#include <editeng/editdata.hxx>
#include <editeng/eerdll.hxx>
#include <editeng/lrspitem.hxx>
#include <editeng/fhgtitem.hxx>
#define _OUTLINER_CXX
#include <editeng/outliner.hxx>
#include <outleeng.hxx>
#include <paralist.hxx>
#include <editeng/editrids.hrc>
#include <svl/itemset.hxx>
#include <editeng/eeitem.hxx>
#include <editeng/editstat.hxx>
#include "outlundo.hxx"
OutlinerEditEng::OutlinerEditEng( Outliner* pEngOwner, SfxItemPool* pPool )
: EditEngine( pPool )
{
pOwner = pEngOwner;
}
OutlinerEditEng::~OutlinerEditEng()
{
}
void OutlinerEditEng::PaintingFirstLine( sal_uInt16 nPara, const Point& rStartPos, long nBaseLineY, const Point& rOrigin, short nOrientation, OutputDevice* pOutDev )
{
if( GetControlWord() & EE_CNTRL_OUTLINER )
{
PaintFirstLineInfo aInfo( nPara, rStartPos, nBaseLineY, rOrigin, nOrientation, pOutDev );
pOwner->maPaintFirstLineHdl.Call( &aInfo );
}
pOwner->PaintBullet( nPara, rStartPos, rOrigin, nOrientation, pOutDev );
}
const SvxNumberFormat* OutlinerEditEng::GetNumberFormat( sal_uInt16 nPara ) const
{
const SvxNumberFormat* pFmt = NULL;
if (pOwner)
pFmt = pOwner->GetNumberFormat( nPara );
return pFmt;
}
Rectangle OutlinerEditEng::GetBulletArea( sal_uInt16 nPara )
{
Rectangle aBulletArea = Rectangle( Point(), Point() );
if ( nPara < pOwner->pParaList->GetParagraphCount() )
{
if ( pOwner->ImplHasBullet( nPara ) )
aBulletArea = pOwner->ImpCalcBulletArea( nPara, sal_False, sal_False );
}
return aBulletArea;
}
void OutlinerEditEng::ParagraphInserted( sal_uInt16 nNewParagraph )
{
pOwner->ParagraphInserted( nNewParagraph );
EditEngine::ParagraphInserted( nNewParagraph );
}
void OutlinerEditEng::ParagraphDeleted( sal_uInt16 nDeletedParagraph )
{
pOwner->ParagraphDeleted( nDeletedParagraph );
EditEngine::ParagraphDeleted( nDeletedParagraph );
}
void OutlinerEditEng::ParagraphConnected( sal_uInt16 /*nLeftParagraph*/, sal_uInt16 nRightParagraph )
{
if( pOwner && pOwner->IsUndoEnabled() && !const_cast<EditEngine&>(pOwner->GetEditEngine()).IsInUndo() )
{
Paragraph* pPara = pOwner->GetParagraph( nRightParagraph );
if( pPara && pOwner->HasParaFlag( pPara, PARAFLAG_ISPAGE ) )
{
pOwner->InsertUndo( new OutlinerUndoChangeParaFlags( pOwner, nRightParagraph, PARAFLAG_ISPAGE, 0 ) );
}
}
}
void OutlinerEditEng::StyleSheetChanged( SfxStyleSheet* pStyle )
{
pOwner->StyleSheetChanged( pStyle );
}
void OutlinerEditEng::ParaAttribsChanged( sal_uInt16 nPara )
{
pOwner->ParaAttribsChanged( nPara );
}
sal_Bool OutlinerEditEng::SpellNextDocument()
{
return pOwner->SpellNextDocument();
}
sal_Bool OutlinerEditEng::ConvertNextDocument()
{
return pOwner->ConvertNextDocument();
}
XubString OutlinerEditEng::GetUndoComment( sal_uInt16 nUndoId ) const
{
switch( nUndoId )
{
case OLUNDO_DEPTH:
return XubString( EditResId( RID_OUTLUNDO_DEPTH ));
case OLUNDO_EXPAND:
return XubString( EditResId( RID_OUTLUNDO_EXPAND ));
case OLUNDO_COLLAPSE:
return XubString( EditResId( RID_OUTLUNDO_COLLAPSE ));
case OLUNDO_ATTR:
return XubString( EditResId( RID_OUTLUNDO_ATTR ));
case OLUNDO_INSERT:
return XubString( EditResId( RID_OUTLUNDO_INSERT ));
default:
return EditEngine::GetUndoComment( nUndoId );
}
}
void OutlinerEditEng::DrawingText( const Point& rStartPos, const XubString& rText, sal_uInt16 nTextStart, sal_uInt16 nTextLen,
const sal_Int32* pDXArray, const SvxFont& rFont, sal_uInt16 nPara, sal_uInt16 nIndex, sal_uInt8 nRightToLeft,
const EEngineData::WrongSpellVector* pWrongSpellVector,
const SvxFieldData* pFieldData,
bool bEndOfLine,
bool bEndOfParagraph,
bool bEndOfBullet,
const ::com::sun::star::lang::Locale* pLocale,
const Color& rOverlineColor,
const Color& rTextLineColor)
{
pOwner->DrawingText(rStartPos,rText,nTextStart,nTextLen,pDXArray,rFont,nPara,nIndex,nRightToLeft,
pWrongSpellVector, pFieldData, bEndOfLine, bEndOfParagraph, bEndOfBullet, pLocale, rOverlineColor, rTextLineColor);
}
void OutlinerEditEng::DrawingTab( const Point& rStartPos, long nWidth, const String& rChar,
const SvxFont& rFont, sal_uInt16 nPara, xub_StrLen nIndex, sal_uInt8 nRightToLeft,
bool bEndOfLine, bool bEndOfParagraph,
const Color& rOverlineColor, const Color& rTextLineColor)
{
pOwner->DrawingTab(rStartPos, nWidth, rChar, rFont, nPara, nIndex, nRightToLeft,
bEndOfLine, bEndOfParagraph, rOverlineColor, rTextLineColor );
}
void OutlinerEditEng::FieldClicked( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos )
{
EditEngine::FieldClicked( rField, nPara, nPos ); // If URL
pOwner->FieldClicked( rField, nPara, nPos );
}
void OutlinerEditEng::FieldSelected( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos )
{
pOwner->FieldSelected( rField, nPara, nPos );
}
XubString OutlinerEditEng::CalcFieldValue( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos, Color*& rpTxtColor, Color*& rpFldColor )
{
return pOwner->CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor );
}
void OutlinerEditEng::SetParaAttribs( sal_uInt16 nPara, const SfxItemSet& rSet )
{
Paragraph* pPara = pOwner->pParaList->GetParagraph( nPara );
if( pPara )
{
if ( !IsInUndo() && IsUndoEnabled() )
pOwner->UndoActionStart( OLUNDO_ATTR );
EditEngine::SetParaAttribs( (sal_uInt16)nPara, rSet );
pOwner->ImplCheckNumBulletItem( (sal_uInt16)nPara );
// #i100014#
// It is not a good idea to substract 1 from a count and cast the result
// to USHORT without check, if the count is 0.
pOwner->ImplCheckParagraphs( (sal_uInt16)nPara, (sal_uInt16) (pOwner->pParaList->GetParagraphCount()) );
if ( !IsInUndo() && IsUndoEnabled() )
pOwner->UndoActionEnd( OLUNDO_ATTR );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>DevTools: fix potential crash. BUG=15373<commit_after><|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief 菊水電源インターフェース・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <boost/format.hpp>
#include "utils/serial_win32.hpp"
#include "utils/fixed_fifo.hpp"
#include "utils/input.hpp"
#include "utils/string_utils.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 菊水電源インターフェース・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class kikusui {
device::serial_win32& serial_;
typedef utils::fixed_fifo<char, 1024> FIFO;
FIFO fifo_;
enum class task {
idle,
state, ///< 菊水の電源が接続されているか?
refc, ///< 下駄を履かせた分の基準電流の測定
refc_wait,
refc_sync,
volt,
curr,
};
task task_;
float volt_;
float curr_;
uint32_t volt_id_;
uint32_t curr_id_;
uint32_t loop_;
bool timeout_;
uint32_t refc_wait_;
float refc_;
std::string rt_;
std::string idn_;
bool get_text_()
{
while(fifo_.length() > 0) {
auto ch = fifo_.get();
if(ch == '\n') {
return true;
} else if(ch != '\r') {
rt_ += ch;
}
}
return false;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
kikusui(device::serial_win32& serial) : serial_(serial),
fifo_(), task_(task::idle), volt_(0.0f), curr_(0.0f),
volt_id_(0), curr_id_(0), loop_(0), timeout_(false),
refc_wait_(0), refc_(0.0f), idn_()
{ }
//-----------------------------------------------------------------//
/*!
@brief 開始
*/
//-----------------------------------------------------------------//
void start()
{
std::string s = "INST:NSEL 6;*IDN?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::state;
loop_ = 60; // *IDN? time out 1 sec
}
//-----------------------------------------------------------------//
/*!
@brief IDN の取得
@return IDN
*/
//-----------------------------------------------------------------//
const std::string& get_idn() const { return idn_; }
//-----------------------------------------------------------------//
/*!
@brief 停止
*/
//-----------------------------------------------------------------//
void stop()
{
std::string s = "CURR 0 A\r\n";
serial_.write(s.c_str(), s.size());
s = "VOLT 0 V\r\n";
serial_.write(s.c_str(), s.size());
s = "OUTP 0\r\n";
serial_.write(s.c_str(), s.size());
}
//-----------------------------------------------------------------//
/*!
@brief 出力設定
@param[in] ena 許可の場合「true」
*/
//-----------------------------------------------------------------//
void set_output(bool ena)
{
std::string s;
if(ena) {
s = "OUTP 1\r\n";
} else {
s = "OUTP 0\r\n";
}
serial_.write(s.c_str(), s.size());
// std::cout << s << std::flush;
}
//-----------------------------------------------------------------//
/*!
@brief 電圧設定
@param[in] volt 設定電圧
@param[in] curr 最大電流
*/
//-----------------------------------------------------------------//
void set_volt(float volt, float curr)
{
auto s = (boost::format("CURR %5.4f A;VOLT %5.4f V\r\n")
% (curr + refc_) % volt).str();
serial_.write(s.c_str(), s.size());
// std::cout << "VOLT: " << s << std::flush;
}
//-----------------------------------------------------------------//
/*!
@brief 電流設定
@param[in] curr 設定電流
@param[in] volt 最大電圧
*/
//-----------------------------------------------------------------//
void set_curr(float curr, float volt)
{
auto s = (boost::format("VOLT %5.4f V;CURR %5.4f A\r\n")
% volt % (curr + refc_)).str();
serial_.write(s.c_str(), s.size());
// std::cout << "CURR: " << s << std::flush;
}
//-----------------------------------------------------------------//
/*!
@brief 電圧測定要求
*/
//-----------------------------------------------------------------//
void req_volt()
{
std::string s = "MEAS:VOLT:DC?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::volt;
}
//-----------------------------------------------------------------//
/*!
@brief 電流測定要求
*/
//-----------------------------------------------------------------//
void req_curr()
{
std::string s = "MEAS:CURR:DC?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::curr;
}
//-----------------------------------------------------------------//
/*!
@brief 電圧 ID を取得
@return 電圧 ID
*/
//-----------------------------------------------------------------//
uint32_t get_volt_id() const { return volt_id_; }
//-----------------------------------------------------------------//
/*!
@brief 電圧を取得 [V]
@return 電圧
*/
//-----------------------------------------------------------------//
float get_volt() const { return volt_; }
//-----------------------------------------------------------------//
/*!
@brief 電流 ID を取得
@return 電流 ID
*/
//-----------------------------------------------------------------//
uint32_t get_curr_id() const { return curr_id_; }
//-----------------------------------------------------------------//
/*!
@brief 基準電流を取得 [A]
@return 基準電流
*/
//-----------------------------------------------------------------//
float get_ref_curr() const { return refc_; }
//-----------------------------------------------------------------//
/*!
@brief 電流を取得 [A]
@return 電流
*/
//-----------------------------------------------------------------//
float get_curr() const {
auto a = curr_ - refc_;
// 負電流の場合は、絶対値にしとく・・
if(a < 0.0f) a = std::abs(a);
return a;
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
char tmp[256];
auto rl = serial_.read(tmp, sizeof(tmp));
for(uint32_t i = 0; i < rl; ++i) {
char ch = tmp[i];
fifo_.put(ch);
}
switch(task_) {
case task::state:
if(get_text_()) {
idn_ = rt_;
task_ = task::refc;
} else {
if(loop_ > 0) {
--loop_;
} else {
timeout_ = true;
task_ = task::idle;
}
}
break;
case task::refc:
set_output(1);
refc_wait_ = 90;
task_ = task::refc_wait;
break;
case task::refc_wait:
if(refc_wait_ > 0) {
refc_wait_--;
} else {
std::string s = "MEAS:CURR:DC?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::refc_sync;
}
break;
case task::refc_sync:
if(get_text_()) {
if((utils::input("%f", rt_.c_str()) % refc_).status()) {
}
set_output(0);
task_ = task::idle;
}
break;
case task::volt:
if(get_text_()) {
if((utils::input("%f", rt_.c_str()) % volt_).status()) {
++volt_id_;
}
task_ = task::idle;
}
break;
case task::curr:
if(get_text_()) {
if((utils::input("%f", rt_.c_str()) % curr_).status()) {
++curr_id_;
}
task_ = task::idle;
}
break;
case task::idle:
default:
while(fifo_.length() > 0) {
fifo_.get();
}
break;
}
}
};
}
<commit_msg>update: comment<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief 菊水電源インターフェース・クラス @n
※0.14 mA 以下の電流を測定出来ない為、停電流源による下駄を @n
履かせている。@n
その為、起動時に定電流源の基準を測定している。
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <boost/format.hpp>
#include "utils/serial_win32.hpp"
#include "utils/fixed_fifo.hpp"
#include "utils/input.hpp"
#include "utils/string_utils.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 菊水電源インターフェース・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class kikusui {
device::serial_win32& serial_;
typedef utils::fixed_fifo<char, 1024> FIFO;
FIFO fifo_;
enum class task {
idle,
state, ///< 菊水の電源が接続されているか?
refc, ///< 下駄を履かせた分の基準電流の測定
refc_wait,
refc_sync,
volt,
curr,
};
task task_;
float volt_;
float curr_;
uint32_t volt_id_;
uint32_t curr_id_;
uint32_t loop_;
bool timeout_;
uint32_t refc_wait_;
float refc_;
std::string rt_;
std::string idn_;
bool get_text_()
{
while(fifo_.length() > 0) {
auto ch = fifo_.get();
if(ch == '\n') {
return true;
} else if(ch != '\r') {
rt_ += ch;
}
}
return false;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
kikusui(device::serial_win32& serial) : serial_(serial),
fifo_(), task_(task::idle), volt_(0.0f), curr_(0.0f),
volt_id_(0), curr_id_(0), loop_(0), timeout_(false),
refc_wait_(0), refc_(0.0f), idn_()
{ }
//-----------------------------------------------------------------//
/*!
@brief 開始
*/
//-----------------------------------------------------------------//
void start()
{
std::string s = "INST:NSEL 6;*IDN?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::state;
loop_ = 60; // *IDN? time out 1 sec
}
//-----------------------------------------------------------------//
/*!
@brief IDN の取得
@return IDN
*/
//-----------------------------------------------------------------//
const std::string& get_idn() const { return idn_; }
//-----------------------------------------------------------------//
/*!
@brief 停止
*/
//-----------------------------------------------------------------//
void stop()
{
std::string s = "CURR 0 A\r\n";
serial_.write(s.c_str(), s.size());
s = "VOLT 0 V\r\n";
serial_.write(s.c_str(), s.size());
s = "OUTP 0\r\n";
serial_.write(s.c_str(), s.size());
}
//-----------------------------------------------------------------//
/*!
@brief 出力設定
@param[in] ena 許可の場合「true」
*/
//-----------------------------------------------------------------//
void set_output(bool ena)
{
std::string s;
if(ena) {
s = "OUTP 1\r\n";
} else {
s = "OUTP 0\r\n";
}
serial_.write(s.c_str(), s.size());
// std::cout << s << std::flush;
}
//-----------------------------------------------------------------//
/*!
@brief 電圧設定
@param[in] volt 設定電圧
@param[in] curr 最大電流
*/
//-----------------------------------------------------------------//
void set_volt(float volt, float curr)
{
auto s = (boost::format("CURR %5.4f A;VOLT %5.4f V\r\n")
% (curr + refc_) % volt).str();
serial_.write(s.c_str(), s.size());
// std::cout << "VOLT: " << s << std::flush;
}
//-----------------------------------------------------------------//
/*!
@brief 電流設定
@param[in] curr 設定電流
@param[in] volt 最大電圧
*/
//-----------------------------------------------------------------//
void set_curr(float curr, float volt)
{
auto s = (boost::format("VOLT %5.4f V;CURR %5.4f A\r\n")
% volt % (curr + refc_)).str();
serial_.write(s.c_str(), s.size());
// std::cout << "CURR: " << s << std::flush;
}
//-----------------------------------------------------------------//
/*!
@brief 電圧測定要求
*/
//-----------------------------------------------------------------//
void req_volt()
{
std::string s = "MEAS:VOLT:DC?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::volt;
}
//-----------------------------------------------------------------//
/*!
@brief 電流測定要求
*/
//-----------------------------------------------------------------//
void req_curr()
{
std::string s = "MEAS:CURR:DC?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::curr;
}
//-----------------------------------------------------------------//
/*!
@brief 電圧 ID を取得
@return 電圧 ID
*/
//-----------------------------------------------------------------//
uint32_t get_volt_id() const { return volt_id_; }
//-----------------------------------------------------------------//
/*!
@brief 電圧を取得 [V]
@return 電圧
*/
//-----------------------------------------------------------------//
float get_volt() const { return volt_; }
//-----------------------------------------------------------------//
/*!
@brief 電流 ID を取得
@return 電流 ID
*/
//-----------------------------------------------------------------//
uint32_t get_curr_id() const { return curr_id_; }
//-----------------------------------------------------------------//
/*!
@brief 基準電流を取得 [A]
@return 基準電流
*/
//-----------------------------------------------------------------//
float get_ref_curr() const { return refc_; }
//-----------------------------------------------------------------//
/*!
@brief 電流を取得 [A]
@return 電流
*/
//-----------------------------------------------------------------//
float get_curr() const {
auto a = curr_ - refc_;
// 負電流の場合は、絶対値にしとく・・
if(a < 0.0f) a = std::abs(a);
return a;
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
char tmp[256];
auto rl = serial_.read(tmp, sizeof(tmp));
for(uint32_t i = 0; i < rl; ++i) {
char ch = tmp[i];
fifo_.put(ch);
}
switch(task_) {
case task::state:
if(get_text_()) {
idn_ = rt_;
task_ = task::refc;
} else {
if(loop_ > 0) {
--loop_;
} else {
timeout_ = true;
task_ = task::idle;
}
}
break;
case task::refc:
set_output(1);
refc_wait_ = 90;
task_ = task::refc_wait;
break;
case task::refc_wait:
if(refc_wait_ > 0) {
refc_wait_--;
} else {
std::string s = "MEAS:CURR:DC?\r\n";
serial_.write(s.c_str(), s.size());
rt_.clear();
task_ = task::refc_sync;
}
break;
case task::refc_sync:
if(get_text_()) {
if((utils::input("%f", rt_.c_str()) % refc_).status()) {
}
set_output(0);
task_ = task::idle;
}
break;
case task::volt:
if(get_text_()) {
if((utils::input("%f", rt_.c_str()) % volt_).status()) {
++volt_id_;
}
task_ = task::idle;
}
break;
case task::curr:
if(get_text_()) {
if((utils::input("%f", rt_.c_str()) % curr_).status()) {
++curr_id_;
}
task_ = task::idle;
}
break;
case task::idle:
default:
while(fifo_.length() > 0) {
fifo_.get();
}
break;
}
}
};
}
<|endoftext|> |
<commit_before>#include <sstream>
#include "slice.hpp"
namespace Vole {
using std::stringstream;
template <typename T>
Slice<T>::Slice(size_t l, size_t c)
: mem(new T[c]),
beg(mem),
len(l),
cap(c)
{ }
template <typename T>
Slice<T>::Slice(T* m, T* b, size_t l, size_t c)
: mem(m),
beg(b),
len(l),
cap(c)
{ }
template <typename T>
template <typename Allocator>
Slice<T>::Slice(size_t l, size_t c, Allocator& a)
: mem(a.template alloc<T>(c)),
beg(mem),
len(l),
cap(c)
{ }
template <typename T>
template <typename Allocator>
Slice<T>::Slice(size_t l, size_t c, Allocator* a)
: mem(a->template alloc<T>(c)),
beg(mem),
len(l),
cap(c)
{ }
template <typename T>
T& Slice<T>::operator[](size_t i) {
if (!(i < len)) {
// TODO: use an error class with more metadata
throw "slice index out of bounds";
}
return beg[i];
}
template <typename T>
Slice<T> Slice<T>::slice(size_t start, size_t end) {
if (end > len || start > end) {
// TODO: use an error class with more metadata
throw "invalid range for slice";
}
return { mem, beg + start, end - beg, cap - beg };
}
template <typename T>
T& Slice<T>::first() {
return (*this)[0];
}
template <typename T>
T& Slice<T>::last() {
return (*this)[len-1];
}
template <typename T>
Slice<T> Slice<T>::take(size_t n) {
return slice(0, n);
}
template <typename T>
Slice<T> Slice<T>::drop(size_t n) {
return slice(n, len);
}
template <typename T>
Slice<T>::operator string() {
stringstream ss;
ss << '(';
for (size_t i = 0; i < len; ++i) {
ss << (i ? " " : "") << beg[i];
}
ss << ')';
return ss.str();
}
}<commit_msg>fix up the range calculations; they were totally wrong<commit_after>#include <sstream>
#include "slice.hpp"
namespace Vole {
using std::stringstream;
template <typename T>
Slice<T>::Slice(size_t l, size_t c)
: mem(new T[c]),
beg(mem),
len(l),
cap(c)
{ }
template <typename T>
Slice<T>::Slice(T* m, T* b, size_t l, size_t c)
: mem(m),
beg(b),
len(l),
cap(c)
{ }
template <typename T>
template <typename Allocator>
Slice<T>::Slice(size_t l, size_t c, Allocator& a)
: mem(a.template alloc<T>(c)),
beg(mem),
len(l),
cap(c)
{ }
template <typename T>
template <typename Allocator>
Slice<T>::Slice(size_t l, size_t c, Allocator* a)
: mem(a->template alloc<T>(c)),
beg(mem),
len(l),
cap(c)
{ }
template <typename T>
T& Slice<T>::operator[](size_t i) {
if (!(i < len)) {
// TODO: use an error class with more metadata
throw "slice index out of bounds";
}
return beg[i];
}
template <typename T>
Slice<T> Slice<T>::slice(size_t lower, size_t upper) {
if (upper > len || lower > upper) {
// TODO: use an error class with more metadata
throw "invalid range for slice";
}
return { mem, beg + lower, upper - lower, cap - lower };
}
template <typename T>
T& Slice<T>::first() {
return (*this)[0];
}
template <typename T>
T& Slice<T>::last() {
return (*this)[len-1];
}
template <typename T>
Slice<T> Slice<T>::take(size_t n) {
return slice(0, n);
}
template <typename T>
Slice<T> Slice<T>::drop(size_t n) {
return slice(n, len);
}
template <typename T>
Slice<T>::operator string() {
stringstream ss;
ss << '(';
for (size_t i = 0; i < len; ++i) {
ss << (i ? " " : "") << beg[i];
}
ss << ')';
return ss.str();
}
}<|endoftext|> |
<commit_before>#include <string>
class Object
{
public:
virtual std::string toString() = 0;
};
#include <any.h>
#include <nullable.h>
#include <sequence.h>
#include <reflect.h>
#include <org/w3c/dom/NameList.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/css/CSSStyleDeclaration.h>
#include <org/w3c/dom/Document.h>
#include <org/w3c/dom/Element.h>
#include <org/w3c/dom/html/ApplicationCache.h>
#include <org/w3c/dom/html/BarProp.h>
#include <org/w3c/dom/html/Function.h>
#include <org/w3c/dom/html/History.h>
#include <org/w3c/dom/html/Location.h>
#include <org/w3c/dom/html/MessagePort.h>
#include <org/w3c/dom/html/Navigator.h>
#include <org/w3c/dom/html/Screen.h>
#include <org/w3c/dom/html/Selection.h>
#include <org/w3c/dom/html/StyleMedia.h>
#include <org/w3c/dom/html/UndoManager.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/webdatabase/Database.h>
#include <org/w3c/dom/webdatabase/DatabaseCallback.h>
#include <org/w3c/dom/webstorage/Storage.h>
#include <iostream>
#include <string>
using namespace std;
using namespace org::w3c::dom;
template<class B>
class Object_Bridge : public B
{
public:
virtual std::string toString()
{
return "";
}
};
Any invoke(Object* object, unsigned interfaceNumber, unsigned methodNumber,
const char* meta, unsigned offset,
unsigned paramCount, Any* arguments)
{
Reflect::Interface interface(meta);
cout << interface.getName() << endl;
Reflect::Method method(meta + offset);
cout << method.getName() << ':' << method.getParameterCount() << endl;
return Nullable<string>("Hi");
}
int main()
{
Object_Bridge<NameList_Bridge<Any, invoke> > nameList;
Nullable<string> name = nameList.getName(3);
cout << name.value() << endl;
name = nameList.getNamespaceURI(2);
cout << name.value() << endl;
Object_Bridge<html::Window_Bridge<Any, invoke> > window;
window.close();
window.setLength(100);
window.postMessage("hi", "hmm");
}
<commit_msg>(invoke) : Clean up.<commit_after>#include <string>
class Object
{
public:
virtual std::string toString() = 0;
};
#include <any.h>
#include <nullable.h>
#include <sequence.h>
#include <reflect.h>
#include <org/w3c/dom/NameList.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/css/CSSStyleDeclaration.h>
#include <org/w3c/dom/Document.h>
#include <org/w3c/dom/Element.h>
#include <org/w3c/dom/html/ApplicationCache.h>
#include <org/w3c/dom/html/BarProp.h>
#include <org/w3c/dom/html/Function.h>
#include <org/w3c/dom/html/History.h>
#include <org/w3c/dom/html/Location.h>
#include <org/w3c/dom/html/MessagePort.h>
#include <org/w3c/dom/html/Navigator.h>
#include <org/w3c/dom/html/Screen.h>
#include <org/w3c/dom/html/Selection.h>
#include <org/w3c/dom/html/StyleMedia.h>
#include <org/w3c/dom/html/UndoManager.h>
#include <org/w3c/dom/html/Window.h>
#include <org/w3c/dom/webdatabase/Database.h>
#include <org/w3c/dom/webdatabase/DatabaseCallback.h>
#include <org/w3c/dom/webstorage/Storage.h>
#include <iostream>
#include <string>
using namespace std;
using namespace org::w3c::dom;
template<class B>
class Object_Bridge : public B
{
public:
virtual std::string toString()
{
return "";
}
};
Any invoke(Object* object, unsigned interfaceNumber, unsigned methodNumber,
const char* meta, unsigned offset,
unsigned argumentCount, Any* arguments)
{
Reflect::Interface interface(meta);
cout << interface.getName() << endl;
Reflect::Method method(meta + offset);
cout << method.getName() << ':' << method.getParameterCount() << endl;
return Nullable<string>("Hi");
}
int main()
{
Object_Bridge<NameList_Bridge<Any, invoke> > nameList;
Nullable<string> name = nameList.getName(3);
cout << name.value() << endl;
name = nameList.getNamespaceURI(2);
cout << name.value() << endl;
Object_Bridge<html::Window_Bridge<Any, invoke> > window;
window.close();
window.setLength(100);
window.postMessage("hi", "hmm");
}
<|endoftext|> |
<commit_before><commit_msg>fix -Wabsolute-value<commit_after><|endoftext|> |
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "config.h"
#include <iostream>
#include "utils/timer.h"
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "utils/exception.h"
#include "ed_reader.h"
#include "type/data.h"
#include "utils/init.h"
namespace po = boost::program_options;
namespace pt = boost::posix_time;
int main(int argc, char * argv[])
{
navitia::init_app();
auto logger = log4cplus::Logger::getInstance("log");
std::string output, connection_string, region_name;
double min_non_connected_graph_ratio;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Affiche l'aide")
("version,v", "Affiche la version")
("config-file", po::value<std::string>(), "Path to config file")
("output,o", po::value<std::string>(&output)->default_value("data.nav.lz4"),
"Output file")
("name,n", po::value<std::string>(®ion_name)->default_value("default"),
"Name of the region you are extracting")
("min_non_connected_ratio,m",
po::value<double>(&min_non_connected_graph_ratio)->default_value(0.1),
"min ratio for the size of non connected graph")
("connection-string", po::value<std::string>(&connection_string)->required(),
"database connection parameters: host=localhost user=navitia dbname=navitia password=navitia");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if(vm.count("version")){
std::cout << argv[0] << " V" << KRAKEN_VERSION << " " << NAVITIA_BUILD_TYPE << std::endl;
return 0;
}
if(vm.count("config-file")){
std::ifstream stream;
stream.open(vm["config-file"].as<std::string>());
if(!stream.is_open()){
throw navitia::exception("Unable to load config file");
}else{
po::store(po::parse_config_file(stream, desc), vm);
}
}
if(vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
po::notify(vm);
pt::ptime start, now;
int read, save;
navitia::type::Data data;
//on init now pour le moment à now, à rendre paramétrable pour le debug
now = start = pt::microsec_clock::local_time();
ed::EdReader reader(connection_string);
try {
reader.fill(data, min_non_connected_graph_ratio);
}
catch (const navitia::exception& e) {
LOG4CPLUS_ERROR(logger, "error while reading the database " << e.what());
LOG4CPLUS_ERROR(logger, "stack: " << e.backtrace());
throw;
}
read = (pt::microsec_clock::local_time() - start).total_milliseconds();
data.complete();
LOG4CPLUS_INFO(logger, "line: " << data.pt_data->lines.size());
LOG4CPLUS_INFO(logger, "route: " << data.pt_data->routes.size());
LOG4CPLUS_INFO(logger, "journey_pattern: " << data.pt_data->journey_patterns.size());
LOG4CPLUS_INFO(logger, "stoparea: " << data.pt_data->stop_areas.size());
LOG4CPLUS_INFO(logger, "stoppoint: " << data.pt_data->stop_points.size());
LOG4CPLUS_INFO(logger, "vehiclejourney: " << data.pt_data->vehicle_journeys.size());
LOG4CPLUS_INFO(logger, "stop: " << data.pt_data->stop_times.size());
LOG4CPLUS_INFO(logger, "connection: " << data.pt_data->stop_point_connections.size());
LOG4CPLUS_INFO(logger, "journey_pattern points: " << data.pt_data->journey_pattern_points.size());
LOG4CPLUS_INFO(logger, "modes: " << data.pt_data->physical_modes.size());
LOG4CPLUS_INFO(logger, "validity pattern : " << data.pt_data->validity_patterns.size());
LOG4CPLUS_INFO(logger, "calendars: " << data.pt_data->calendars.size());
LOG4CPLUS_INFO(logger, "synonyms : " << data.geo_ref->synonyms.size());
LOG4CPLUS_INFO(logger, "fare tickets: " << data.fare->fare_map.size());
LOG4CPLUS_INFO(logger, "fare transitions: " << data.fare->nb_transitions());
LOG4CPLUS_INFO(logger, "fare od: " << data.fare->od_tickets.size());
LOG4CPLUS_INFO(logger, "Begin to save ...");
start = pt::microsec_clock::local_time();
try {
data.save(output);
} catch(const navitia::exception &e) {
LOG4CPLUS_ERROR(logger, "Unable to save");
LOG4CPLUS_ERROR(logger, e.what());
return 1;
}
save = (pt::microsec_clock::local_time() - start).total_milliseconds();
LOG4CPLUS_INFO(logger, "Data saved");
LOG4CPLUS_INFO(logger, "Computing times");
LOG4CPLUS_INFO(logger, "\t File reading: " << read << "ms");
LOG4CPLUS_INFO(logger, "\t Data writing: " << save << "ms");
return 0;
}
<commit_msg>Ed: fill the publication_date of the nav at the end of ed2nav<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "config.h"
#include <iostream>
#include "utils/timer.h"
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "utils/exception.h"
#include "ed_reader.h"
#include "type/data.h"
#include "utils/init.h"
#include "type/meta_data.h"
namespace po = boost::program_options;
namespace pt = boost::posix_time;
int main(int argc, char * argv[])
{
navitia::init_app();
auto logger = log4cplus::Logger::getInstance("log");
std::string output, connection_string, region_name;
double min_non_connected_graph_ratio;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Affiche l'aide")
("version,v", "Affiche la version")
("config-file", po::value<std::string>(), "Path to config file")
("output,o", po::value<std::string>(&output)->default_value("data.nav.lz4"),
"Output file")
("name,n", po::value<std::string>(®ion_name)->default_value("default"),
"Name of the region you are extracting")
("min_non_connected_ratio,m",
po::value<double>(&min_non_connected_graph_ratio)->default_value(0.1),
"min ratio for the size of non connected graph")
("connection-string", po::value<std::string>(&connection_string)->required(),
"database connection parameters: host=localhost user=navitia dbname=navitia password=navitia");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if(vm.count("version")){
std::cout << argv[0] << " V" << KRAKEN_VERSION << " " << NAVITIA_BUILD_TYPE << std::endl;
return 0;
}
if(vm.count("config-file")){
std::ifstream stream;
stream.open(vm["config-file"].as<std::string>());
if(!stream.is_open()){
throw navitia::exception("Unable to load config file");
}else{
po::store(po::parse_config_file(stream, desc), vm);
}
}
if(vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
po::notify(vm);
pt::ptime start, now;
int read, save;
navitia::type::Data data;
//on init now pour le moment à now, à rendre paramétrable pour le debug
now = start = pt::microsec_clock::local_time();
ed::EdReader reader(connection_string);
try {
reader.fill(data, min_non_connected_graph_ratio);
}
catch (const navitia::exception& e) {
LOG4CPLUS_ERROR(logger, "error while reading the database " << e.what());
LOG4CPLUS_ERROR(logger, "stack: " << e.backtrace());
throw;
}
read = (pt::microsec_clock::local_time() - start).total_milliseconds();
data.complete();
data.meta->publication_date = pt::microsec_clock::local_time();
LOG4CPLUS_INFO(logger, "line: " << data.pt_data->lines.size());
LOG4CPLUS_INFO(logger, "route: " << data.pt_data->routes.size());
LOG4CPLUS_INFO(logger, "journey_pattern: " << data.pt_data->journey_patterns.size());
LOG4CPLUS_INFO(logger, "stoparea: " << data.pt_data->stop_areas.size());
LOG4CPLUS_INFO(logger, "stoppoint: " << data.pt_data->stop_points.size());
LOG4CPLUS_INFO(logger, "vehiclejourney: " << data.pt_data->vehicle_journeys.size());
LOG4CPLUS_INFO(logger, "stop: " << data.pt_data->stop_times.size());
LOG4CPLUS_INFO(logger, "connection: " << data.pt_data->stop_point_connections.size());
LOG4CPLUS_INFO(logger, "journey_pattern points: " << data.pt_data->journey_pattern_points.size());
LOG4CPLUS_INFO(logger, "modes: " << data.pt_data->physical_modes.size());
LOG4CPLUS_INFO(logger, "validity pattern : " << data.pt_data->validity_patterns.size());
LOG4CPLUS_INFO(logger, "calendars: " << data.pt_data->calendars.size());
LOG4CPLUS_INFO(logger, "synonyms : " << data.geo_ref->synonyms.size());
LOG4CPLUS_INFO(logger, "fare tickets: " << data.fare->fare_map.size());
LOG4CPLUS_INFO(logger, "fare transitions: " << data.fare->nb_transitions());
LOG4CPLUS_INFO(logger, "fare od: " << data.fare->od_tickets.size());
LOG4CPLUS_INFO(logger, "Begin to save ...");
start = pt::microsec_clock::local_time();
try {
data.save(output);
} catch(const navitia::exception &e) {
LOG4CPLUS_ERROR(logger, "Unable to save");
LOG4CPLUS_ERROR(logger, e.what());
return 1;
}
save = (pt::microsec_clock::local_time() - start).total_milliseconds();
LOG4CPLUS_INFO(logger, "Data saved");
LOG4CPLUS_INFO(logger, "Computing times");
LOG4CPLUS_INFO(logger, "\t File reading: " << read << "ms");
LOG4CPLUS_INFO(logger, "\t Data writing: " << save << "ms");
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: textundo.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:58:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TEXTUNDO_HXX
#define _TEXTUNDO_HXX
#ifndef _UNDO_HXX
#include <undo.hxx>
#endif
class TextEngine;
class TextUndoManager : public SfxUndoManager
{
TextEngine* mpTextEngine;
protected:
void UndoRedoStart();
void UndoRedoEnd();
TextView* GetView() const { return mpTextEngine->GetActiveView(); }
public:
TextUndoManager( TextEngine* pTextEngine );
~TextUndoManager();
virtual BOOL Undo( USHORT nCount=1 );
virtual BOOL Redo( USHORT nCount=1 );
};
class TextUndo : public SfxUndoAction
{
private:
USHORT mnId;
TextEngine* mpTextEngine;
protected:
TextView* GetView() const { return mpTextEngine->GetActiveView(); }
void SetSelection( const TextSelection& rSel );
TextDoc* GetDoc() const { return mpTextEngine->mpDoc; }
TEParaPortions* GetTEParaPortions() const { return mpTextEngine->mpTEParaPortions; }
public:
TYPEINFO();
TextUndo( USHORT nId, TextEngine* pTextEngine );
virtual ~TextUndo();
TextEngine* GetTextEngine() const { return mpTextEngine; }
virtual void Undo() = 0;
virtual void Redo() = 0;
virtual XubString GetComment() const;
virtual USHORT GetId() const;
};
#endif // _TEXTUNDO_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1110); FILE MERGED 2005/09/05 14:52:49 rt 1.1.1.1.1110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textundo.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:29:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TEXTUNDO_HXX
#define _TEXTUNDO_HXX
#ifndef _UNDO_HXX
#include <undo.hxx>
#endif
class TextEngine;
class TextUndoManager : public SfxUndoManager
{
TextEngine* mpTextEngine;
protected:
void UndoRedoStart();
void UndoRedoEnd();
TextView* GetView() const { return mpTextEngine->GetActiveView(); }
public:
TextUndoManager( TextEngine* pTextEngine );
~TextUndoManager();
virtual BOOL Undo( USHORT nCount=1 );
virtual BOOL Redo( USHORT nCount=1 );
};
class TextUndo : public SfxUndoAction
{
private:
USHORT mnId;
TextEngine* mpTextEngine;
protected:
TextView* GetView() const { return mpTextEngine->GetActiveView(); }
void SetSelection( const TextSelection& rSel );
TextDoc* GetDoc() const { return mpTextEngine->mpDoc; }
TEParaPortions* GetTEParaPortions() const { return mpTextEngine->mpTEParaPortions; }
public:
TYPEINFO();
TextUndo( USHORT nId, TextEngine* pTextEngine );
virtual ~TextUndo();
TextEngine* GetTextEngine() const { return mpTextEngine; }
virtual void Undo() = 0;
virtual void Redo() = 0;
virtual XubString GetComment() const;
virtual USHORT GetId() const;
};
#endif // _TEXTUNDO_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xtextedt.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-06-19 21:03:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <xtextedt.hxx>
#include <vcl/svapp.hxx> // International
#include <unotools/textsearch.hxx>
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
using namespace ::com::sun::star;
// -------------------------------------------------------------------------
// class ExtTextEngine
// -------------------------------------------------------------------------
ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) )
{
}
ExtTextEngine::~ExtTextEngine()
{
}
TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const
{
TextSelection aSel( rCursor );
USHORT nPos = rCursor.GetIndex();
ULONG nPara = rCursor.GetPara();
ULONG nParas = GetParagraphCount();
if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) )
{
USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) );
if ( nMatchChar != STRING_NOTFOUND )
{
if ( ( nMatchChar % 2 ) == 0 )
{
// Vorwaerts suchen...
sal_Unicode nSC = maGroupChars.GetChar( nMatchChar );
sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 );
USHORT nCur = nPos+1;
USHORT nLevel = 1;
while ( nLevel && ( nPara < nParas ) )
{
XubString aStr = GetText( nPara );
while ( nCur < aStr.Len() )
{
if ( aStr.GetChar( nCur ) == nSC )
nLevel++;
else if ( aStr.GetChar( nCur ) == nEC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
nCur++;
}
if ( nLevel )
{
nPara++;
nCur = 0;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetEnd() = TextPaM( nPara, nCur+1 );
}
}
else
{
// Rueckwaerts suchen...
xub_Unicode nEC = maGroupChars.GetChar( nMatchChar );
xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 );
USHORT nCur = rCursor.GetIndex()-1;
USHORT nLevel = 1;
while ( nLevel )
{
if ( GetTextLen( nPara ) )
{
XubString aStr = GetText( nPara );
while ( nCur )
{
if ( aStr.GetChar( nCur ) == nSC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
else if ( aStr.GetChar( nCur ) == nEC )
nLevel++;
nCur--;
}
}
if ( nLevel )
{
if ( nPara )
{
nPara--;
nCur = GetTextLen( nPara )-1; // egal ob negativ, weil if Len()
}
else
break;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetStart().GetIndex()++; // hinter das Zeichen
aSel.GetEnd() = TextPaM( nPara, nCur );
}
}
}
}
return aSel;
}
BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward )
{
TextSelection aSel( rSel );
aSel.Justify();
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
TextPaM aStartPaM( aSel.GetEnd() );
if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) )
{
aStartPaM = aSel.GetStart();
}
BOOL bFound = FALSE;
ULONG nStartNode, nEndNode;
if ( bSearchInSelection )
nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara();
else
nEndNode = bForward ? (GetParagraphCount()-1) : 0;
nStartNode = aStartPaM.GetPara();
util::SearchOptions aOptions( rSearchOptions );
aOptions.Locale = Application::GetSettings().GetLocale();
utl::TextSearch aSearcher( rSearchOptions );
// ueber die Absaetze iterieren...
for ( ULONG nNode = nStartNode;
bForward ? ( nNode <= nEndNode) : ( nNode >= nEndNode );
bForward ? nNode++ : nNode-- )
{
String aText = GetText( nNode );
USHORT nStartPos = 0;
USHORT nEndPos = aText.Len();
if ( nNode == nStartNode )
{
if ( bForward )
nStartPos = aStartPaM.GetIndex();
else
nEndPos = aStartPaM.GetIndex();
}
if ( ( nNode == nEndNode ) && bSearchInSelection )
{
if ( bForward )
nEndPos = aSel.GetEnd().GetIndex();
else
nStartPos = aSel.GetStart().GetIndex();
}
if ( bForward )
bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos );
else
bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos );
if ( bFound )
{
rSel.GetStart().GetPara() = nNode;
rSel.GetStart().GetIndex() = nStartPos;
rSel.GetEnd().GetPara() = nNode;
rSel.GetEnd().GetIndex() = nEndPos;
// Ueber den Absatz selektieren?
// Select over the paragraph?
// FIXME This should be max long...
if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 !
{
if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() )
{
rSel.GetEnd().GetPara()++;
rSel.GetEnd().GetIndex() = 0;
}
else
{
rSel.GetEnd().GetIndex() = nStartPos;
bFound = FALSE;
}
}
break;
}
if ( !bForward && !nNode ) // Bei rueckwaertsuche, wenn nEndNode = 0:
break;
}
return bFound;
}
// -------------------------------------------------------------------------
// class ExtTextView
// -------------------------------------------------------------------------
ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow )
: TextView( pEng, pWindow )
{
}
ExtTextView::~ExtTextView()
{
}
BOOL ExtTextView::MatchGroup()
{
TextSelection aTmpSel( GetSelection() );
aTmpSel.Justify();
if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) ||
( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) )
{
return FALSE;
}
TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() );
if ( aMatchSel.HasRange() )
SetSelection( aMatchSel );
return aMatchSel.HasRange() ? TRUE : FALSE;
}
BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward )
{
BOOL bFound = FALSE;
TextSelection aSel( GetSelection() );
if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) )
{
bFound = TRUE;
// Erstmal den Anfang des Wortes als Selektion einstellen,
// damit das ganze Wort in den sichtbaren Bereich kommt.
SetSelection( aSel.GetStart() );
ShowCursor( TRUE, FALSE );
}
else
{
aSel = GetSelection().GetEnd();
}
SetSelection( aSel );
ShowCursor();
return bFound;
}
USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward )
{
USHORT nFound = 0;
if ( !bAll )
{
if ( GetSelection().HasRange() )
{
InsertText( rSearchOptions.replaceString );
nFound = 1;
Search( rSearchOptions, bForward ); // gleich zum naechsten
}
else
{
if( Search( rSearchOptions, bForward ) )
nFound = 1;
}
}
else
{
// Der Writer ersetzt alle, vom Anfang bis Ende...
ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine();
// HideSelection();
TextSelection aSel;
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
if ( bSearchInSelection )
{
aSel = GetSelection();
aSel.Justify();
}
TextSelection aSearchSel( aSel );
BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
if ( bFound )
pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL );
while ( bFound )
{
nFound++;
TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString );
aSel = aSearchSel;
aSel.GetStart() = aNewStart;
bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
}
if ( nFound )
{
SetSelection( aSel.GetStart() );
pTextEngine->FormatAndUpdate( this );
pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL );
}
}
return nFound;
}
BOOL ExtTextView::ImpIndentBlock( BOOL bRight )
{
BOOL bDone = FALSE;
TextSelection aSel = GetSelection();
aSel.Justify();
HideSelection();
GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
ULONG nStartPara = aSel.GetStart().GetPara();
ULONG nEndPara = aSel.GetEnd().GetPara();
if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() )
{
nEndPara--; // den dann nicht einruecken...
}
for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ )
{
if ( bRight )
{
// Tabs hinzufuegen
GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' );
bDone = TRUE;
}
else
{
// Tabs/Blanks entfernen
String aText = GetTextEngine()->GetText( nPara );
if ( aText.Len() && (
( aText.GetChar( 0 ) == '\t' ) ||
( aText.GetChar( 0 ) == ' ' ) ) )
{
GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) );
bDone = TRUE;
}
}
}
GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
BOOL bRange = aSel.HasRange();
if ( bRight )
{
aSel.GetStart().GetIndex()++;
if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) )
aSel.GetEnd().GetIndex()++;
}
else
{
if ( aSel.GetStart().GetIndex() )
aSel.GetStart().GetIndex()--;
if ( bRange && aSel.GetEnd().GetIndex() )
aSel.GetEnd().GetIndex()--;
}
ImpSetSelection( aSel );
GetTextEngine()->FormatAndUpdate( this );
return bDone;
}
BOOL ExtTextView::IndentBlock()
{
return ImpIndentBlock( TRUE );
}
BOOL ExtTextView::UnindentBlock()
{
return ImpIndentBlock( FALSE );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.92); FILE MERGED 2006/09/01 17:43:04 kaib 1.11.92.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xtextedt.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:49:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <xtextedt.hxx>
#include <vcl/svapp.hxx> // International
#include <unotools/textsearch.hxx>
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
using namespace ::com::sun::star;
// -------------------------------------------------------------------------
// class ExtTextEngine
// -------------------------------------------------------------------------
ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) )
{
}
ExtTextEngine::~ExtTextEngine()
{
}
TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const
{
TextSelection aSel( rCursor );
USHORT nPos = rCursor.GetIndex();
ULONG nPara = rCursor.GetPara();
ULONG nParas = GetParagraphCount();
if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) )
{
USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) );
if ( nMatchChar != STRING_NOTFOUND )
{
if ( ( nMatchChar % 2 ) == 0 )
{
// Vorwaerts suchen...
sal_Unicode nSC = maGroupChars.GetChar( nMatchChar );
sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 );
USHORT nCur = nPos+1;
USHORT nLevel = 1;
while ( nLevel && ( nPara < nParas ) )
{
XubString aStr = GetText( nPara );
while ( nCur < aStr.Len() )
{
if ( aStr.GetChar( nCur ) == nSC )
nLevel++;
else if ( aStr.GetChar( nCur ) == nEC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
nCur++;
}
if ( nLevel )
{
nPara++;
nCur = 0;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetEnd() = TextPaM( nPara, nCur+1 );
}
}
else
{
// Rueckwaerts suchen...
xub_Unicode nEC = maGroupChars.GetChar( nMatchChar );
xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 );
USHORT nCur = rCursor.GetIndex()-1;
USHORT nLevel = 1;
while ( nLevel )
{
if ( GetTextLen( nPara ) )
{
XubString aStr = GetText( nPara );
while ( nCur )
{
if ( aStr.GetChar( nCur ) == nSC )
{
nLevel--;
if ( !nLevel )
break; // while nCur...
}
else if ( aStr.GetChar( nCur ) == nEC )
nLevel++;
nCur--;
}
}
if ( nLevel )
{
if ( nPara )
{
nPara--;
nCur = GetTextLen( nPara )-1; // egal ob negativ, weil if Len()
}
else
break;
}
}
if ( nLevel == 0 ) // gefunden
{
aSel.GetStart() = rCursor;
aSel.GetStart().GetIndex()++; // hinter das Zeichen
aSel.GetEnd() = TextPaM( nPara, nCur );
}
}
}
}
return aSel;
}
BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward )
{
TextSelection aSel( rSel );
aSel.Justify();
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
TextPaM aStartPaM( aSel.GetEnd() );
if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) )
{
aStartPaM = aSel.GetStart();
}
BOOL bFound = FALSE;
ULONG nStartNode, nEndNode;
if ( bSearchInSelection )
nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara();
else
nEndNode = bForward ? (GetParagraphCount()-1) : 0;
nStartNode = aStartPaM.GetPara();
util::SearchOptions aOptions( rSearchOptions );
aOptions.Locale = Application::GetSettings().GetLocale();
utl::TextSearch aSearcher( rSearchOptions );
// ueber die Absaetze iterieren...
for ( ULONG nNode = nStartNode;
bForward ? ( nNode <= nEndNode) : ( nNode >= nEndNode );
bForward ? nNode++ : nNode-- )
{
String aText = GetText( nNode );
USHORT nStartPos = 0;
USHORT nEndPos = aText.Len();
if ( nNode == nStartNode )
{
if ( bForward )
nStartPos = aStartPaM.GetIndex();
else
nEndPos = aStartPaM.GetIndex();
}
if ( ( nNode == nEndNode ) && bSearchInSelection )
{
if ( bForward )
nEndPos = aSel.GetEnd().GetIndex();
else
nStartPos = aSel.GetStart().GetIndex();
}
if ( bForward )
bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos );
else
bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos );
if ( bFound )
{
rSel.GetStart().GetPara() = nNode;
rSel.GetStart().GetIndex() = nStartPos;
rSel.GetEnd().GetPara() = nNode;
rSel.GetEnd().GetIndex() = nEndPos;
// Ueber den Absatz selektieren?
// Select over the paragraph?
// FIXME This should be max long...
if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 !
{
if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() )
{
rSel.GetEnd().GetPara()++;
rSel.GetEnd().GetIndex() = 0;
}
else
{
rSel.GetEnd().GetIndex() = nStartPos;
bFound = FALSE;
}
}
break;
}
if ( !bForward && !nNode ) // Bei rueckwaertsuche, wenn nEndNode = 0:
break;
}
return bFound;
}
// -------------------------------------------------------------------------
// class ExtTextView
// -------------------------------------------------------------------------
ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow )
: TextView( pEng, pWindow )
{
}
ExtTextView::~ExtTextView()
{
}
BOOL ExtTextView::MatchGroup()
{
TextSelection aTmpSel( GetSelection() );
aTmpSel.Justify();
if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) ||
( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) )
{
return FALSE;
}
TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() );
if ( aMatchSel.HasRange() )
SetSelection( aMatchSel );
return aMatchSel.HasRange() ? TRUE : FALSE;
}
BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward )
{
BOOL bFound = FALSE;
TextSelection aSel( GetSelection() );
if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) )
{
bFound = TRUE;
// Erstmal den Anfang des Wortes als Selektion einstellen,
// damit das ganze Wort in den sichtbaren Bereich kommt.
SetSelection( aSel.GetStart() );
ShowCursor( TRUE, FALSE );
}
else
{
aSel = GetSelection().GetEnd();
}
SetSelection( aSel );
ShowCursor();
return bFound;
}
USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward )
{
USHORT nFound = 0;
if ( !bAll )
{
if ( GetSelection().HasRange() )
{
InsertText( rSearchOptions.replaceString );
nFound = 1;
Search( rSearchOptions, bForward ); // gleich zum naechsten
}
else
{
if( Search( rSearchOptions, bForward ) )
nFound = 1;
}
}
else
{
// Der Writer ersetzt alle, vom Anfang bis Ende...
ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine();
// HideSelection();
TextSelection aSel;
BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) );
if ( bSearchInSelection )
{
aSel = GetSelection();
aSel.Justify();
}
TextSelection aSearchSel( aSel );
BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
if ( bFound )
pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL );
while ( bFound )
{
nFound++;
TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString );
aSel = aSearchSel;
aSel.GetStart() = aNewStart;
bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE );
}
if ( nFound )
{
SetSelection( aSel.GetStart() );
pTextEngine->FormatAndUpdate( this );
pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL );
}
}
return nFound;
}
BOOL ExtTextView::ImpIndentBlock( BOOL bRight )
{
BOOL bDone = FALSE;
TextSelection aSel = GetSelection();
aSel.Justify();
HideSelection();
GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
ULONG nStartPara = aSel.GetStart().GetPara();
ULONG nEndPara = aSel.GetEnd().GetPara();
if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() )
{
nEndPara--; // den dann nicht einruecken...
}
for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ )
{
if ( bRight )
{
// Tabs hinzufuegen
GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' );
bDone = TRUE;
}
else
{
// Tabs/Blanks entfernen
String aText = GetTextEngine()->GetText( nPara );
if ( aText.Len() && (
( aText.GetChar( 0 ) == '\t' ) ||
( aText.GetChar( 0 ) == ' ' ) ) )
{
GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) );
bDone = TRUE;
}
}
}
GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK );
BOOL bRange = aSel.HasRange();
if ( bRight )
{
aSel.GetStart().GetIndex()++;
if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) )
aSel.GetEnd().GetIndex()++;
}
else
{
if ( aSel.GetStart().GetIndex() )
aSel.GetStart().GetIndex()--;
if ( bRange && aSel.GetEnd().GetIndex() )
aSel.GetEnd().GetIndex()--;
}
ImpSetSelection( aSel );
GetTextEngine()->FormatAndUpdate( this );
return bDone;
}
BOOL ExtTextView::IndentBlock()
{
return ImpIndentBlock( TRUE );
}
BOOL ExtTextView::UnindentBlock()
{
return ImpIndentBlock( FALSE );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rngitem.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 15:01:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef NUMTYPE
#if SUPD<355
DBG_NAME(SfxRangeItem);
#endif
#define NUMTYPE USHORT
#define SfxXRangeItem SfxRangeItem
#define SfxXRangesItem SfxUShortRangesItem
#include "rngitem.hxx"
#include "rngitem.cxx"
#define NUMTYPE sal_uInt32
#define SfxXRangeItem SfxULongRangeItem
#define SfxXRangesItem SfxULongRangesItem
#include "rngitem.hxx"
#include "rngitem.cxx"
#else
static inline NUMTYPE Count_Impl(const NUMTYPE * pRanges)
{
NUMTYPE nCount = 0;
for (; *pRanges; pRanges += 2) nCount += 2;
return nCount;
}
// -----------------------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SfxXRangeItem, SfxPoolItem);
TYPEINIT1_AUTOFACTORY(SfxXRangesItem, SfxPoolItem);
NUMTYPE Count_Impl( const NUMTYPE *pRanges );
// -----------------------------------------------------------------------
SfxXRangeItem::SfxXRangeItem()
{
nFrom = 0;
nTo = 0;
}
// -----------------------------------------------------------------------
SfxXRangeItem::SfxXRangeItem( USHORT which, NUMTYPE from, NUMTYPE to ):
SfxPoolItem( which ),
nFrom( from ),
nTo( to )
{
}
// -----------------------------------------------------------------------
SfxXRangeItem::SfxXRangeItem( USHORT nW, SvStream &rStream ) :
SfxPoolItem( nW )
{
rStream >> nFrom;
rStream >> nTo;
}
// -----------------------------------------------------------------------
SfxXRangeItem::SfxXRangeItem( const SfxXRangeItem& rItem ) :
SfxPoolItem( rItem )
{
nFrom = rItem.nFrom;
nTo = rItem.nTo;
}
// -----------------------------------------------------------------------
SfxItemPresentation SfxXRangeItem::GetPresentation
(
SfxItemPresentation /*ePresentation*/,
SfxMapUnit /*eCoreMetric*/,
SfxMapUnit /*ePresentationMetric*/,
XubString& rText,
const IntlWrapper *
) const
{
rText = UniString::CreateFromInt64(nFrom);
rText += ':';
rText += UniString::CreateFromInt64(nTo);
return SFX_ITEM_PRESENTATION_NAMELESS;
}
// -----------------------------------------------------------------------
int SfxXRangeItem::operator==( const SfxPoolItem& rItem ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
SfxXRangeItem* pT = (SfxXRangeItem*)&rItem;
if( nFrom==pT->nFrom && nTo==pT->nTo )
return 1;
return 0;
}
// -----------------------------------------------------------------------
SfxPoolItem* SfxXRangeItem::Clone(SfxItemPool *) const
{
return new SfxXRangeItem( Which(), nFrom, nTo );
}
// -----------------------------------------------------------------------
SfxPoolItem* SfxXRangeItem::Create(SvStream &rStream, USHORT) const
{
NUMTYPE nVon, nBis;
rStream >> nVon;
rStream >> nBis;
return new SfxXRangeItem( Which(), nVon, nBis );
}
// -----------------------------------------------------------------------
SvStream& SfxXRangeItem::Store(SvStream &rStream, USHORT) const
{
rStream << nFrom;
rStream << nTo;
return rStream;
}
//=========================================================================
SfxXRangesItem::SfxXRangesItem()
: _pRanges(0)
{
}
//-------------------------------------------------------------------------
SfxXRangesItem::SfxXRangesItem( USHORT nWID, const NUMTYPE *pRanges )
: SfxPoolItem( nWID )
{
NUMTYPE nCount = Count_Impl(pRanges) + 1;
_pRanges = new NUMTYPE[nCount];
memcpy( _pRanges, pRanges, sizeof(NUMTYPE) * nCount );
}
//-------------------------------------------------------------------------
SfxXRangesItem::SfxXRangesItem( USHORT nWID, SvStream &rStream )
: SfxPoolItem( nWID )
{
NUMTYPE nCount;
rStream >> nCount;
_pRanges = new NUMTYPE[nCount + 1];
for ( NUMTYPE n = 0; n < nCount; ++n )
rStream >> _pRanges[n];
_pRanges[nCount] = 0;
}
//-------------------------------------------------------------------------
SfxXRangesItem::SfxXRangesItem( const SfxXRangesItem& rItem )
: SfxPoolItem( rItem )
{
NUMTYPE nCount = Count_Impl(rItem._pRanges) + 1;
_pRanges = new NUMTYPE[nCount];
memcpy( _pRanges, rItem._pRanges, sizeof(NUMTYPE) * nCount );
}
//-------------------------------------------------------------------------
SfxXRangesItem::~SfxXRangesItem()
{
delete _pRanges;
}
//-------------------------------------------------------------------------
int SfxXRangesItem::operator==( const SfxPoolItem &rItem ) const
{
const SfxXRangesItem &rOther = (const SfxXRangesItem&) rItem;
if ( !_pRanges && !rOther._pRanges )
return TRUE;
if ( _pRanges || rOther._pRanges )
return FALSE;
NUMTYPE n;
for ( n = 0; _pRanges[n] && rOther._pRanges[n]; ++n )
if ( *_pRanges != rOther._pRanges[n] )
return 0;
return !_pRanges[n] && !rOther._pRanges[n];
}
//-------------------------------------------------------------------------
SfxItemPresentation SfxXRangesItem::GetPresentation( SfxItemPresentation /*ePres*/,
SfxMapUnit /*eCoreMetric*/,
SfxMapUnit /*ePresMetric*/,
XubString &/*rText*/,
const IntlWrapper * ) const
{
HACK(n. i.)
return SFX_ITEM_PRESENTATION_NONE;
}
//-------------------------------------------------------------------------
SfxPoolItem* SfxXRangesItem::Clone( SfxItemPool * ) const
{
return new SfxXRangesItem( *this );
}
//-------------------------------------------------------------------------
SfxPoolItem* SfxXRangesItem::Create( SvStream &rStream, USHORT ) const
{
return new SfxXRangesItem( Which(), rStream );
}
//-------------------------------------------------------------------------
SvStream& SfxXRangesItem::Store( SvStream &rStream, USHORT ) const
{
NUMTYPE nCount = Count_Impl( _pRanges );
rStream >> nCount;
for ( NUMTYPE n = 0; _pRanges[n]; ++n )
rStream >> _pRanges[n];
return rStream;
}
#undef NUMTYPE
#undef SfxXRangeItem
#undef SfxXRangesItem
#endif
<commit_msg>INTEGRATION: CWS pchfix04 (1.9.70); FILE MERGED 2007/03/02 15:58:00 hjs 1.9.70.3: #i71519# re-insert comment 2006/12/12 17:21:06 kaib 1.9.70.2: #i71519# fixing pch in svtools for msc 2006/11/17 11:45:06 mkretzschmar 1.9.70.1: #i71619# Don't include pch in cxx files that are included in other cxx files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rngitem.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2007-05-10 16:37:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef NUMTYPE
#define NUMTYPE USHORT
#define SfxXRangeItem SfxRangeItem
#define SfxXRangesItem SfxUShortRangesItem
#include "rngitem.hxx"
#include "rngitem_inc.cxx"
#define NUMTYPE sal_uInt32
#define SfxXRangeItem SfxULongRangeItem
#define SfxXRangesItem SfxULongRangesItem
#include "rngitem.hxx"
#include "rngitem_inc.cxx"
#else
// We leave this condition just in case NUMTYPE has been defined externally to this
// file and we are supposed to define the SfxXRangeItem based on that.
#include "rngitem_inc.cxx"
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtoolsclient.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2006-03-31 12:10:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SVX_DBTOOLSCLIENT_HXX
#define SVX_DBTOOLSCLIENT_HXX
#ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX
#include <connectivity/virtualdbtools.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef UNOTOOLS_INC_SHAREDUNOCOMPONENT_HXX
#include <unotools/sharedunocomponent.hxx>
#endif
//........................................................................
namespace svxform
{
//........................................................................
typedef ::utl::SharedUNOComponent< ::com::sun::star::sdbc::XConnection > SharedConnection;
//====================================================================
//= ODbtoolsClient
//====================================================================
/** base class for classes which want to use dbtools features with load-on-call
of the dbtools lib.
*/
class ODbtoolsClient
{
private:
static ::osl::Mutex s_aMutex;
static sal_Int32 s_nClients;
static oslModule s_hDbtoolsModule;
static ::connectivity::simple::createDataAccessToolsFactoryFunction
s_pFactoryCreationFunc;
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
mutable BOOL m_bCreateAlready;
private:
mutable ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory;
protected:
const ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory >&
getFactory() const { return m_xDataAccessFactory; }
protected:
ODbtoolsClient();
~ODbtoolsClient();
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void create() const;
private:
static void registerClient();
static void revokeClient();
};
//====================================================================
//= OStaticDataAccessTools
//====================================================================
class OStaticDataAccessTools : public ODbtoolsClient
{
protected:
mutable ::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools;
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void create() const;
void checkIfLoaded() const;
public:
OStaticDataAccessTools();
const ::rtl::Reference< ::connectivity::simple::IDataAccessTools >& getDataAccessTools() const { return m_xDataAccessTools; }
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> getNumberFormats(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConn,
sal_Bool _bAllowDefault
) const;
// ------------------------------------------------
sal_Int32 getDefaultNumberFormat(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xColumn,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatTypes >& _xTypes,
const ::com::sun::star::lang::Locale& _rLocale );
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection_withFeedback(
const ::rtl::OUString& _rDataSourceName,
const ::rtl::OUString& _rUser,
const ::rtl::OUString& _rPwd,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory
) const SAL_THROW ( (::com::sun::star::sdbc::SQLException) );
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> connectRowset(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory,
sal_Bool _bSetAsActiveConnection
) const SAL_THROW ( ( ::com::sun::star::sdbc::SQLException
, ::com::sun::star::lang::WrappedTargetException
, ::com::sun::star::uno::RuntimeException) );
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getRowSetConnection(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet)
const SAL_THROW ( (::com::sun::star::uno::RuntimeException) );
// ------------------------------------------------
void TransferFormComponentProperties(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxOld,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxNew,
const ::com::sun::star::lang::Locale& _rLocale
) const;
// ------------------------------------------------
::rtl::OUString quoteName(
const ::rtl::OUString& _rQuote,
const ::rtl::OUString& _rName
) const;
// ------------------------------------------------
::rtl::OUString quoteTableName(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta,
const ::rtl::OUString& _rName
,sal_Bool _bUseCatalogInSelect = sal_True
,sal_Bool _bUseSchemaInSelect = sal_True
) const;
// ------------------------------------------------
::com::sun::star::sdb::SQLContext prependContextInfo(
::com::sun::star::sdbc::SQLException& _rException,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
const ::rtl::OUString& _rContextDescription,
const ::rtl::OUString& _rContextDetails
) const;
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource(
const ::rtl::OUString& _rsRegisteredName,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory
) const;
// ------------------------------------------------
/** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::INSERT
@param _rxCursorSet the property set
*/
sal_Bool canInsert(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const;
// ------------------------------------------------
/** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::UPDATE
@param _rxCursorSet the property set
*/
sal_Bool canUpdate(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const;
// ------------------------------------------------
/** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::DELETE
@param _rxCursorSet the property set
*/
sal_Bool canDelete(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const;
// ------------------------------------------------
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >
getFieldsByCommandDescriptor(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxKeepFieldsAlive,
::dbtools::SQLExceptionInfo* _pErrorInfo = NULL
) SAL_THROW( ( ) );
// ------------------------------------------------
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
getFieldNamesByCommandDescriptor(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand,
::dbtools::SQLExceptionInfo* _pErrorInfo = NULL
) SAL_THROW( ( ) );
// ------------------------------------------------
virtual sal_Bool isDataSourcePropertyEnabled(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _xProp
,const ::rtl::OUString& _sProperty,
sal_Bool _bDefault = sal_False) const;
// ------------------------------------------------
bool isEmbeddedInDatabase(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxActualConnection
);
// ------------------------------------------------
bool isEmbeddedInDatabase(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent
);
};
//........................................................................
} // namespace svxform
//........................................................................
#endif // SVX_DBTOOLSCLIENT_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.11.196); FILE MERGED 2006/05/23 18:35:16 sb 1.11.196.2: RESYNC: (1.11-1.12); FILE MERGED 2006/01/05 12:02:27 fs 1.11.196.1: #i55991# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbtoolsclient.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:04:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SVX_DBTOOLSCLIENT_HXX
#define SVX_DBTOOLSCLIENT_HXX
#ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX
#include <connectivity/virtualdbtools.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef UNOTOOLS_INC_SHAREDUNOCOMPONENT_HXX
#include <unotools/sharedunocomponent.hxx>
#endif
//........................................................................
namespace svxform
{
//........................................................................
typedef ::utl::SharedUNOComponent< ::com::sun::star::sdbc::XConnection > SharedConnection;
//====================================================================
//= ODbtoolsClient
//====================================================================
/** base class for classes which want to use dbtools features with load-on-call
of the dbtools lib.
*/
class ODbtoolsClient
{
private:
static ::osl::Mutex s_aMutex;
static sal_Int32 s_nClients;
static oslModule s_hDbtoolsModule;
static ::connectivity::simple::createDataAccessToolsFactoryFunction
s_pFactoryCreationFunc;
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
mutable BOOL m_bCreateAlready;
private:
mutable ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory;
protected:
const ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory >&
getFactory() const { return m_xDataAccessFactory; }
protected:
ODbtoolsClient();
~ODbtoolsClient();
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void create() const;
private:
static void registerClient();
static void revokeClient();
};
//====================================================================
//= OStaticDataAccessTools
//====================================================================
class OStaticDataAccessTools : public ODbtoolsClient
{
protected:
mutable ::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools;
//add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time)
void create() const;
void checkIfLoaded() const;
public:
OStaticDataAccessTools();
const ::rtl::Reference< ::connectivity::simple::IDataAccessTools >& getDataAccessTools() const { return m_xDataAccessTools; }
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> getNumberFormats(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConn,
sal_Bool _bAllowDefault
) const;
// ------------------------------------------------
sal_Int32 getDefaultNumberFormat(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xColumn,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatTypes >& _xTypes,
const ::com::sun::star::lang::Locale& _rLocale );
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection_withFeedback(
const ::rtl::OUString& _rDataSourceName,
const ::rtl::OUString& _rUser,
const ::rtl::OUString& _rPwd,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory
) const SAL_THROW ( (::com::sun::star::sdbc::SQLException) );
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> connectRowset(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory,
sal_Bool _bSetAsActiveConnection
) const SAL_THROW ( ( ::com::sun::star::sdbc::SQLException
, ::com::sun::star::lang::WrappedTargetException
, ::com::sun::star::uno::RuntimeException) );
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getRowSetConnection(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet)
const SAL_THROW ( (::com::sun::star::uno::RuntimeException) );
// ------------------------------------------------
void TransferFormComponentProperties(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxOld,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxNew,
const ::com::sun::star::lang::Locale& _rLocale
) const;
// ------------------------------------------------
::rtl::OUString quoteName(
const ::rtl::OUString& _rQuote,
const ::rtl::OUString& _rName
) const;
// ------------------------------------------------
::rtl::OUString quoteTableName(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta,
const ::rtl::OUString& _rName
,sal_Bool _bUseCatalogInSelect = sal_True
,sal_Bool _bUseSchemaInSelect = sal_True
) const;
// ------------------------------------------------
::com::sun::star::sdb::SQLContext prependContextInfo(
::com::sun::star::sdbc::SQLException& _rException,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext,
const ::rtl::OUString& _rContextDescription,
const ::rtl::OUString& _rContextDetails
) const;
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource(
const ::rtl::OUString& _rsRegisteredName,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory
) const;
// ------------------------------------------------
/** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::INSERT
@param _rxCursorSet the property set
*/
sal_Bool canInsert(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const;
// ------------------------------------------------
/** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::UPDATE
@param _rxCursorSet the property set
*/
sal_Bool canUpdate(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const;
// ------------------------------------------------
/** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::DELETE
@param _rxCursorSet the property set
*/
sal_Bool canDelete(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const;
// ------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >
getFieldsByCommandDescriptor(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxKeepFieldsAlive,
::dbtools::SQLExceptionInfo* _pErrorInfo = NULL
) SAL_THROW( ( ) );
// ------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString >
getFieldNamesByCommandDescriptor(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const sal_Int32 _nCommandType,
const ::rtl::OUString& _rCommand,
::dbtools::SQLExceptionInfo* _pErrorInfo = NULL
) SAL_THROW( ( ) );
// ------------------------------------------------
sal_Bool isDataSourcePropertyEnabled(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _xProp
,const ::rtl::OUString& _sProperty,
sal_Bool _bDefault = sal_False) const;
// ------------------------------------------------
bool isEmbeddedInDatabase(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent,
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxActualConnection
);
// ------------------------------------------------
bool isEmbeddedInDatabase(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent
);
};
//........................................................................
} // namespace svxform
//........................................................................
#endif // SVX_DBTOOLSCLIENT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: outleeng.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 17:01:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <outl_pch.hxx>
#pragma hdrstop
#define _OUTLINER_CXX
#include <outliner.hxx>
#include <outleeng.hxx>
#include <paralist.hxx>
#include <outliner.hrc>
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _EEITEM_HXX //autogen
#include <eeitem.hxx>
#endif
OutlinerEditEng::OutlinerEditEng( Outliner* pEngOwner, SfxItemPool* pPool )
: EditEngine( pPool )
{
pOwner = pEngOwner;
}
OutlinerEditEng::~OutlinerEditEng()
{
}
void OutlinerEditEng::PaintingFirstLine( USHORT nPara, const Point& rStartPos, long nBaseLineY, const Point& rOrigin, short nOrientation, OutputDevice* pOutDev )
{
pOwner->PaintBullet( nPara, rStartPos, rOrigin, nOrientation, pOutDev );
}
Rectangle OutlinerEditEng::GetBulletArea( USHORT nPara )
{
Rectangle aBulletArea = Rectangle( Point(), Point() );
if ( nPara < pOwner->pParaList->GetParagraphCount() )
{
if ( pOwner->ImplHasBullet( nPara ) )
aBulletArea = pOwner->ImpCalcBulletArea( nPara, FALSE );
}
return aBulletArea;
}
void OutlinerEditEng::ParagraphInserted( USHORT nNewParagraph )
{
pOwner->ParagraphInserted( nNewParagraph );
}
void OutlinerEditEng::ParagraphDeleted( USHORT nDeletedParagraph )
{
pOwner->ParagraphDeleted( nDeletedParagraph );
}
void OutlinerEditEng::StyleSheetChanged( SfxStyleSheet* pStyle )
{
pOwner->StyleSheetChanged( pStyle );
}
void OutlinerEditEng::ParaAttribsChanged( USHORT nPara )
{
pOwner->ParaAttribsChanged( nPara );
}
void OutlinerEditEng::ParagraphHeightChanged( USHORT nPara )
{
pOwner->ParagraphHeightChanged( nPara );
}
BOOL OutlinerEditEng::SpellNextDocument()
{
return pOwner->SpellNextDocument();
}
XubString OutlinerEditEng::GetUndoComment( USHORT nUndoId ) const
{
#ifndef SVX_LIGHT
switch( nUndoId )
{
case OLUNDO_DEPTH:
return XubString( EditResId( RID_OUTLUNDO_DEPTH ));
case OLUNDO_HEIGHT:
return XubString( EditResId(RID_OUTLUNDO_HEIGHT ));
case OLUNDO_EXPAND:
return XubString( EditResId( RID_OUTLUNDO_EXPAND ));
case OLUNDO_COLLAPSE:
return XubString( EditResId( RID_OUTLUNDO_COLLAPSE ));
case OLUNDO_ATTR:
return XubString( EditResId( RID_OUTLUNDO_ATTR ));
case OLUNDO_INSERT:
return XubString( EditResId( RID_OUTLUNDO_INSERT ));
default:
return EditEngine::GetUndoComment( nUndoId );
}
#else // SVX_LIGHT
XubString aString;
return aString;
#endif
}
void OutlinerEditEng::DrawingText( const Point& rStartPos, const XubString& rText, const long* pDXArray, const SvxFont& rFont, USHORT nPara, USHORT nIndex )
{
if ( nIndex == 0 )
{
// Dann das Bullet 'malen', dort wird bStrippingPortions ausgewertet
// und Outliner::DrawingText gerufen
// DrawingText liefert die BaseLine, DrawBullet braucht Top().
Point aCorrectedPos( rStartPos );
aCorrectedPos.Y() = GetDocPosTopLeft( nPara ).Y();
aCorrectedPos.Y() += GetFirstLineOffset( nPara );
pOwner->PaintBullet( nPara, aCorrectedPos, Point(), 0, GetRefDevice() );
}
pOwner->DrawingText(rStartPos,rText,pDXArray,rFont,nPara,nIndex );
}
void OutlinerEditEng::FieldClicked( const SvxFieldItem& rField, USHORT nPara, USHORT nPos )
{
EditEngine::FieldClicked( rField, nPara, nPos ); // Falls URL
pOwner->FieldClicked( rField, nPara, nPos );
}
void OutlinerEditEng::FieldSelected( const SvxFieldItem& rField, USHORT nPara, USHORT nPos )
{
pOwner->FieldSelected( rField, nPara, nPos );
}
XubString OutlinerEditEng::CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor )
{
return pOwner->CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor );
}
<commit_msg>#90984# Outliner-D&D and MoveParagraphs done from EditEngine, removed old Uno-Ids and resources<commit_after>/*************************************************************************
*
* $RCSfile: outleeng.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mt $ $Date: 2001-08-17 11:31:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <outl_pch.hxx>
#pragma hdrstop
#define _OUTLINER_CXX
#include <outliner.hxx>
#include <outleeng.hxx>
#include <paralist.hxx>
#include <outliner.hrc>
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _EEITEM_HXX //autogen
#include <eeitem.hxx>
#endif
OutlinerEditEng::OutlinerEditEng( Outliner* pEngOwner, SfxItemPool* pPool )
: EditEngine( pPool )
{
pOwner = pEngOwner;
}
OutlinerEditEng::~OutlinerEditEng()
{
}
void OutlinerEditEng::PaintingFirstLine( USHORT nPara, const Point& rStartPos, long nBaseLineY, const Point& rOrigin, short nOrientation, OutputDevice* pOutDev )
{
pOwner->PaintBullet( nPara, rStartPos, rOrigin, nOrientation, pOutDev );
}
Rectangle OutlinerEditEng::GetBulletArea( USHORT nPara )
{
Rectangle aBulletArea = Rectangle( Point(), Point() );
if ( nPara < pOwner->pParaList->GetParagraphCount() )
{
if ( pOwner->ImplHasBullet( nPara ) )
aBulletArea = pOwner->ImpCalcBulletArea( nPara, FALSE );
}
return aBulletArea;
}
void OutlinerEditEng::ParagraphInserted( USHORT nNewParagraph )
{
pOwner->ParagraphInserted( nNewParagraph );
}
void OutlinerEditEng::ParagraphDeleted( USHORT nDeletedParagraph )
{
pOwner->ParagraphDeleted( nDeletedParagraph );
}
void OutlinerEditEng::StyleSheetChanged( SfxStyleSheet* pStyle )
{
pOwner->StyleSheetChanged( pStyle );
}
void OutlinerEditEng::ParaAttribsChanged( USHORT nPara )
{
pOwner->ParaAttribsChanged( nPara );
}
void OutlinerEditEng::ParagraphHeightChanged( USHORT nPara )
{
pOwner->ParagraphHeightChanged( nPara );
}
BOOL OutlinerEditEng::SpellNextDocument()
{
return pOwner->SpellNextDocument();
}
XubString OutlinerEditEng::GetUndoComment( USHORT nUndoId ) const
{
#ifndef SVX_LIGHT
switch( nUndoId )
{
case OLUNDO_DEPTH:
return XubString( EditResId( RID_OUTLUNDO_DEPTH ));
case OLUNDO_EXPAND:
return XubString( EditResId( RID_OUTLUNDO_EXPAND ));
case OLUNDO_COLLAPSE:
return XubString( EditResId( RID_OUTLUNDO_COLLAPSE ));
case OLUNDO_ATTR:
return XubString( EditResId( RID_OUTLUNDO_ATTR ));
case OLUNDO_INSERT:
return XubString( EditResId( RID_OUTLUNDO_INSERT ));
default:
return EditEngine::GetUndoComment( nUndoId );
}
#else // SVX_LIGHT
XubString aString;
return aString;
#endif
}
void OutlinerEditEng::DrawingText( const Point& rStartPos, const XubString& rText, const long* pDXArray, const SvxFont& rFont, USHORT nPara, USHORT nIndex )
{
if ( nIndex == 0 )
{
// Dann das Bullet 'malen', dort wird bStrippingPortions ausgewertet
// und Outliner::DrawingText gerufen
// DrawingText liefert die BaseLine, DrawBullet braucht Top().
Point aCorrectedPos( rStartPos );
aCorrectedPos.Y() = GetDocPosTopLeft( nPara ).Y();
aCorrectedPos.Y() += GetFirstLineOffset( nPara );
pOwner->PaintBullet( nPara, aCorrectedPos, Point(), 0, GetRefDevice() );
}
pOwner->DrawingText(rStartPos,rText,pDXArray,rFont,nPara,nIndex );
}
void OutlinerEditEng::FieldClicked( const SvxFieldItem& rField, USHORT nPara, USHORT nPos )
{
EditEngine::FieldClicked( rField, nPara, nPos ); // Falls URL
pOwner->FieldClicked( rField, nPara, nPos );
}
void OutlinerEditEng::FieldSelected( const SvxFieldItem& rField, USHORT nPara, USHORT nPos )
{
pOwner->FieldSelected( rField, nPara, nPos );
}
XubString OutlinerEditEng::CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor )
{
return pOwner->CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor );
}
<|endoftext|> |
<commit_before><commit_msg>´Color´ : ambiguous symbol<commit_after><|endoftext|> |
<commit_before>#include "logwindow.h"
LogWindow::LogWindow(QWidget *parent, Qt::WindowFlags f) :
QDialog(parent, f)
{
QSize windowSizes(400, 400);
resize(windowSizes);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_textWidget = new QTextEdit(this);
QGridLayout *layout = new QGridLayout(this);
layout->addWidget(m_textWidget);
setWindowTitle(tr("Aequatio Debug Log"));
}
LogWindow::~LogWindow()
{
}
void LogWindow::setData(QString logContents)
{
m_textWidget->setPlainText(logContents);
}
<commit_msg>Changed size of log window<commit_after>#include "logwindow.h"
LogWindow::LogWindow(QWidget *parent, Qt::WindowFlags f) :
QDialog(parent, f)
{
QSize windowSizes(500, 300);
resize(windowSizes);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_textWidget = new QTextEdit(this);
QGridLayout *layout = new QGridLayout(this);
layout->addWidget(m_textWidget);
setWindowTitle(tr("Aequatio Debug Log"));
}
LogWindow::~LogWindow()
{
}
void LogWindow::setData(QString logContents)
{
m_textWidget->setPlainText(logContents);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fedesc.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-16 21:13:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _FESH_HXX
#include <fesh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _PAGEFRM_HXX
#include <pagefrm.hxx>
#endif
#ifndef _ROOTFRM_HXX
#include <rootfrm.hxx>
#endif
#ifndef _CNTFRM_HXX
#include <cntfrm.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _FMTPDSC_HXX //autogen
#include <fmtpdsc.hxx>
#endif
#ifndef _PAGEDESC_HXX
#include <pagedesc.hxx>
#endif
#ifndef _TABFRM_HXX
#include <tabfrm.hxx>
#endif
#ifndef _EDIMP_HXX
#include <edimp.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
/*************************************************************************
|*
|* SwFEShell::GetPageDescCnt()
|*
|* Ersterstellung MA 25. Jan. 93
|* Letzte Aenderung MA 25. Jan. 93
|*
|*************************************************************************/
USHORT SwFEShell::GetPageDescCnt() const
{
return GetDoc()->GetPageDescCnt();
}
/*************************************************************************
|*
|* SwFEShell::ChgCurPageDesc()
|*
|* Ersterstellung ST ??
|* Letzte Aenderung MA 01. Aug. 94
|*
|*************************************************************************/
void SwFEShell::ChgCurPageDesc( const SwPageDesc& rDesc )
{
#ifndef PRODUCT
//Die SS veraendert keinen PageDesc, sondern setzt nur das Attribut.
//Der Pagedesc muss im Dokument vorhanden sein!
BOOL bFound = FALSE;
for ( USHORT nTst = 0; nTst < GetPageDescCnt(); ++nTst )
if ( &rDesc == &GetPageDesc( nTst ) )
bFound = TRUE;
ASSERT( bFound, "ChgCurPageDesc mit ungueltigem Descriptor." );
#endif
StartAllAction();
SwPageFrm *pPage = GetCurrFrm()->FindPageFrm();
const SwFrm *pFlow;
USHORT nPageNmOffset = 0;
ASSERT( !GetCrsr()->HasMark(), "ChgCurPageDesc nur ohne Selektion!");
SET_CURR_SHELL( this );
while ( pPage )
{
pFlow = pPage->FindFirstBodyCntnt();
if ( pFlow )
{
if ( pFlow->IsInTab() )
pFlow = pFlow->FindTabFrm();
const SwFmtPageDesc& rPgDesc = pFlow->GetAttrSet()->GetPageDesc();
if( rPgDesc.GetPageDesc() )
{
// wir haben ihn den Schlingel
nPageNmOffset = rPgDesc.GetNumOffset();
break;
}
}
pPage = (SwPageFrm*) pPage->GetPrev();
}
if ( !pPage )
{
pPage = (SwPageFrm*) (GetLayout()->Lower());
pFlow = pPage->FindFirstBodyCntnt();
if ( !pFlow )
{
pPage = (SwPageFrm*)pPage->GetNext();
pFlow = pPage->FindFirstBodyCntnt();
ASSERT( pFlow, "Dokuemnt ohne Inhalt?!?" );
}
}
// Seitennummer mitnehmen
SwFmtPageDesc aNew( &rDesc );
aNew.SetNumOffset( nPageNmOffset );
if ( pFlow->IsInTab() )
GetDoc()->SetAttr( aNew, *(SwFmt*)pFlow->FindTabFrm()->GetFmt() );
else
{
SwPaM aPaM( *((SwCntntFrm*)pFlow)->GetNode() );
GetDoc()->Insert( aPaM, aNew, 0 );
}
EndAllActionAndCall();
}
/*************************************************************************
|*
|* SwFEShell::ChgPageDesc()
|*
|* Ersterstellung MA 25. Jan. 93
|* Letzte Aenderung MA 24. Jan. 95
|*
|*************************************************************************/
void SwFEShell::ChgPageDesc( USHORT i, const SwPageDesc &rChged )
{
StartAllAction();
SET_CURR_SHELL( this );
//Fix i64842: because Undo has a very special way to handle header/footer content
// we have to copy the page descriptor before calling ChgPageDesc.
const sal_Bool bDoesUndo( GetDoc()->DoesUndo() );
SwPageDesc aDesc( rChged );
GetDoc()->DoUndo( sal_False );
GetDoc()->CopyPageDesc(rChged, aDesc);
GetDoc()->DoUndo( bDoesUndo );
GetDoc()->ChgPageDesc( i, aDesc );
EndAllActionAndCall();
}
/*************************************************************************
|*
|* SwFEShell::GetPageDesc(), GetCurPageDesc()
|*
|* Ersterstellung MA 25. Jan. 93
|* Letzte Aenderung MA 23. Apr. 93
|
|*************************************************************************/
const SwPageDesc& SwFEShell::GetPageDesc( USHORT i ) const
{
return const_cast<const SwDoc *>(GetDoc())->GetPageDesc( i );
}
SwPageDesc* SwFEShell::FindPageDescByName( const String& rName,
BOOL bGetFromPool,
USHORT* pPos )
{
SwPageDesc* pDesc = GetDoc()->FindPageDescByName( rName, pPos );
if( !pDesc && bGetFromPool )
{
USHORT nPoolId = SwStyleNameMapper::GetPoolIdFromUIName( rName, GET_POOLID_PAGEDESC );
if( USHRT_MAX != nPoolId &&
0 != (pDesc = GetDoc()->GetPageDescFromPool( nPoolId ))
&& pPos )
// werden immer hinten angehaengt
*pPos = GetDoc()->GetPageDescCnt() - 1 ;
}
return pDesc;
}
USHORT SwFEShell::GetMousePageDesc( const Point &rPt ) const
{
if( GetLayout() )
{
const SwPageFrm* pPage =
static_cast<const SwPageFrm*>( GetLayout()->Lower() );
if( pPage )
{
while( pPage->GetNext() && rPt.Y() > pPage->Frm().Bottom() )
pPage = static_cast<const SwPageFrm*>( pPage->GetNext() );
SwDoc *pDoc = GetDoc();
for ( USHORT i = 0; i < GetDoc()->GetPageDescCnt(); ++i )
{
if ( pPage->GetPageDesc() == &const_cast<const SwDoc *>(pDoc)
->GetPageDesc(i) )
return i;
}
}
}
return 0;
}
USHORT SwFEShell::GetCurPageDesc( const BOOL bCalcFrm ) const
{
const SwFrm *pFrm = GetCurrFrm( bCalcFrm );
if ( pFrm )
{
const SwPageFrm *pPage = pFrm->FindPageFrm();
if ( pPage )
{
SwDoc *pDoc = GetDoc();
for ( USHORT i = 0; i < GetDoc()->GetPageDescCnt(); ++i )
{
if ( pPage->GetPageDesc() == &const_cast<const SwDoc *>(pDoc)
->GetPageDesc(i) )
return i;
}
}
}
return 0;
}
// if inside all selection only one PageDesc, return this.
// Otherwise return 0 pointer
const SwPageDesc* SwFEShell::GetSelectedPageDescs() const
{
const SwCntntNode* pCNd;
const SwFrm* pMkFrm, *pPtFrm;
const SwPageDesc* pFnd, *pRetDesc = (SwPageDesc*)0xffffffff;
const Point aNulPt;
FOREACHPAM_START(this)
if( 0 != (pCNd = PCURCRSR->GetCntntNode() ) &&
0 != ( pPtFrm = pCNd->GetFrm( &aNulPt, 0, FALSE )) )
pPtFrm = pPtFrm->FindPageFrm();
else
pPtFrm = 0;
if( PCURCRSR->HasMark() &&
0 != (pCNd = PCURCRSR->GetCntntNode( FALSE ) ) &&
0 != ( pMkFrm = pCNd->GetFrm( &aNulPt, 0, FALSE )) )
pMkFrm = pMkFrm->FindPageFrm();
else
pMkFrm = pPtFrm;
if( !pMkFrm || !pPtFrm )
pFnd = 0;
else if( pMkFrm == pPtFrm )
pFnd = ((SwPageFrm*)pMkFrm)->GetPageDesc();
else
{
// swap pointer if PtFrm before MkFrm
if( ((SwPageFrm*)pMkFrm)->GetPhyPageNum() >
((SwPageFrm*)pPtFrm)->GetPhyPageNum() )
{
const SwFrm* pTmp = pMkFrm; pMkFrm = pPtFrm; pPtFrm = pTmp;
}
// now check from MkFrm to PtFrm for equal PageDescs
pFnd = ((SwPageFrm*)pMkFrm)->GetPageDesc();
while( pFnd && pMkFrm != pPtFrm )
{
pMkFrm = pMkFrm->GetNext();
if( !pMkFrm || pFnd != ((SwPageFrm*)pMkFrm)->GetPageDesc() )
pFnd = 0;
}
}
if( (SwPageDesc*)0xffffffff == pRetDesc )
pRetDesc = pFnd;
else if( pFnd != pRetDesc )
{
pRetDesc = 0;
break;
}
FOREACHPAM_END()
return pRetDesc;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.9.222); FILE MERGED 2007/04/03 12:59:52 tl 1.9.222.3: #i69287# warning-free code 2007/03/09 13:24:41 ama 1.9.222.2: #i69287#: warning free code 2007/03/09 11:23:39 fme 1.9.222.1: #i69287# Warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fedesc.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:51:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _FESH_HXX
#include <fesh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _PAGEFRM_HXX
#include <pagefrm.hxx>
#endif
#ifndef _ROOTFRM_HXX
#include <rootfrm.hxx>
#endif
#ifndef _CNTFRM_HXX
#include <cntfrm.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _FMTPDSC_HXX //autogen
#include <fmtpdsc.hxx>
#endif
#ifndef _PAGEDESC_HXX
#include <pagedesc.hxx>
#endif
#ifndef _TABFRM_HXX
#include <tabfrm.hxx>
#endif
#ifndef _EDIMP_HXX
#include <edimp.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
/*************************************************************************
|*
|* SwFEShell::GetPageDescCnt()
|*
|* Ersterstellung MA 25. Jan. 93
|* Letzte Aenderung MA 25. Jan. 93
|*
|*************************************************************************/
USHORT SwFEShell::GetPageDescCnt() const
{
return GetDoc()->GetPageDescCnt();
}
/*************************************************************************
|*
|* SwFEShell::ChgCurPageDesc()
|*
|* Ersterstellung ST ??
|* Letzte Aenderung MA 01. Aug. 94
|*
|*************************************************************************/
void SwFEShell::ChgCurPageDesc( const SwPageDesc& rDesc )
{
#ifndef PRODUCT
//Die SS veraendert keinen PageDesc, sondern setzt nur das Attribut.
//Der Pagedesc muss im Dokument vorhanden sein!
BOOL bFound = FALSE;
for ( USHORT nTst = 0; nTst < GetPageDescCnt(); ++nTst )
if ( &rDesc == &GetPageDesc( nTst ) )
bFound = TRUE;
ASSERT( bFound, "ChgCurPageDesc mit ungueltigem Descriptor." );
#endif
StartAllAction();
SwPageFrm *pPage = GetCurrFrm()->FindPageFrm();
const SwFrm *pFlow = 0;
USHORT nPageNmOffset = 0;
ASSERT( !GetCrsr()->HasMark(), "ChgCurPageDesc nur ohne Selektion!");
SET_CURR_SHELL( this );
while ( pPage )
{
pFlow = pPage->FindFirstBodyCntnt();
if ( pFlow )
{
if ( pFlow->IsInTab() )
pFlow = pFlow->FindTabFrm();
const SwFmtPageDesc& rPgDesc = pFlow->GetAttrSet()->GetPageDesc();
if( rPgDesc.GetPageDesc() )
{
// wir haben ihn den Schlingel
nPageNmOffset = rPgDesc.GetNumOffset();
break;
}
}
pPage = (SwPageFrm*) pPage->GetPrev();
}
if ( !pPage )
{
pPage = (SwPageFrm*) (GetLayout()->Lower());
pFlow = pPage->FindFirstBodyCntnt();
if ( !pFlow )
{
pPage = (SwPageFrm*)pPage->GetNext();
pFlow = pPage->FindFirstBodyCntnt();
ASSERT( pFlow, "Dokuemnt ohne Inhalt?!?" );
}
}
// Seitennummer mitnehmen
SwFmtPageDesc aNew( &rDesc );
aNew.SetNumOffset( nPageNmOffset );
if ( pFlow->IsInTab() )
GetDoc()->SetAttr( aNew, *(SwFmt*)pFlow->FindTabFrm()->GetFmt() );
else
{
SwPaM aPaM( *((SwCntntFrm*)pFlow)->GetNode() );
GetDoc()->Insert( aPaM, aNew, 0 );
}
EndAllActionAndCall();
}
/*************************************************************************
|*
|* SwFEShell::ChgPageDesc()
|*
|* Ersterstellung MA 25. Jan. 93
|* Letzte Aenderung MA 24. Jan. 95
|*
|*************************************************************************/
void SwFEShell::ChgPageDesc( USHORT i, const SwPageDesc &rChged )
{
StartAllAction();
SET_CURR_SHELL( this );
//Fix i64842: because Undo has a very special way to handle header/footer content
// we have to copy the page descriptor before calling ChgPageDesc.
const sal_Bool bDoesUndo( GetDoc()->DoesUndo() );
SwPageDesc aDesc( rChged );
GetDoc()->DoUndo( sal_False );
GetDoc()->CopyPageDesc(rChged, aDesc);
GetDoc()->DoUndo( bDoesUndo );
GetDoc()->ChgPageDesc( i, aDesc );
EndAllActionAndCall();
}
/*************************************************************************
|*
|* SwFEShell::GetPageDesc(), GetCurPageDesc()
|*
|* Ersterstellung MA 25. Jan. 93
|* Letzte Aenderung MA 23. Apr. 93
|
|*************************************************************************/
const SwPageDesc& SwFEShell::GetPageDesc( USHORT i ) const
{
return const_cast<const SwDoc *>(GetDoc())->GetPageDesc( i );
}
SwPageDesc* SwFEShell::FindPageDescByName( const String& rName,
BOOL bGetFromPool,
USHORT* pPos )
{
SwPageDesc* pDesc = GetDoc()->FindPageDescByName( rName, pPos );
if( !pDesc && bGetFromPool )
{
USHORT nPoolId = SwStyleNameMapper::GetPoolIdFromUIName( rName, nsSwGetPoolIdFromName::GET_POOLID_PAGEDESC );
if( USHRT_MAX != nPoolId &&
0 != (pDesc = GetDoc()->GetPageDescFromPool( nPoolId ))
&& pPos )
// werden immer hinten angehaengt
*pPos = GetDoc()->GetPageDescCnt() - 1 ;
}
return pDesc;
}
USHORT SwFEShell::GetMousePageDesc( const Point &rPt ) const
{
if( GetLayout() )
{
const SwPageFrm* pPage =
static_cast<const SwPageFrm*>( GetLayout()->Lower() );
if( pPage )
{
while( pPage->GetNext() && rPt.Y() > pPage->Frm().Bottom() )
pPage = static_cast<const SwPageFrm*>( pPage->GetNext() );
SwDoc *pMyDoc = GetDoc();
for ( USHORT i = 0; i < GetDoc()->GetPageDescCnt(); ++i )
{
if ( pPage->GetPageDesc() == &const_cast<const SwDoc *>(pMyDoc)
->GetPageDesc(i) )
return i;
}
}
}
return 0;
}
USHORT SwFEShell::GetCurPageDesc( const BOOL bCalcFrm ) const
{
const SwFrm *pFrm = GetCurrFrm( bCalcFrm );
if ( pFrm )
{
const SwPageFrm *pPage = pFrm->FindPageFrm();
if ( pPage )
{
SwDoc *pMyDoc = GetDoc();
for ( USHORT i = 0; i < GetDoc()->GetPageDescCnt(); ++i )
{
if ( pPage->GetPageDesc() == &const_cast<const SwDoc *>(pMyDoc)
->GetPageDesc(i) )
return i;
}
}
}
return 0;
}
// if inside all selection only one PageDesc, return this.
// Otherwise return 0 pointer
const SwPageDesc* SwFEShell::GetSelectedPageDescs() const
{
const SwCntntNode* pCNd;
const SwFrm* pMkFrm, *pPtFrm;
const SwPageDesc* pFnd, *pRetDesc = (SwPageDesc*)0xffffffff;
const Point aNulPt;
FOREACHPAM_START(this)
if( 0 != (pCNd = PCURCRSR->GetCntntNode() ) &&
0 != ( pPtFrm = pCNd->GetFrm( &aNulPt, 0, FALSE )) )
pPtFrm = pPtFrm->FindPageFrm();
else
pPtFrm = 0;
if( PCURCRSR->HasMark() &&
0 != (pCNd = PCURCRSR->GetCntntNode( FALSE ) ) &&
0 != ( pMkFrm = pCNd->GetFrm( &aNulPt, 0, FALSE )) )
pMkFrm = pMkFrm->FindPageFrm();
else
pMkFrm = pPtFrm;
if( !pMkFrm || !pPtFrm )
pFnd = 0;
else if( pMkFrm == pPtFrm )
pFnd = ((SwPageFrm*)pMkFrm)->GetPageDesc();
else
{
// swap pointer if PtFrm before MkFrm
if( ((SwPageFrm*)pMkFrm)->GetPhyPageNum() >
((SwPageFrm*)pPtFrm)->GetPhyPageNum() )
{
const SwFrm* pTmp = pMkFrm; pMkFrm = pPtFrm; pPtFrm = pTmp;
}
// now check from MkFrm to PtFrm for equal PageDescs
pFnd = ((SwPageFrm*)pMkFrm)->GetPageDesc();
while( pFnd && pMkFrm != pPtFrm )
{
pMkFrm = pMkFrm->GetNext();
if( !pMkFrm || pFnd != ((SwPageFrm*)pMkFrm)->GetPageDesc() )
pFnd = 0;
}
}
if( (SwPageDesc*)0xffffffff == pRetDesc )
pRetDesc = pFnd;
else if( pFnd != pRetDesc )
{
pRetDesc = 0;
break;
}
FOREACHPAM_END()
return pRetDesc;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ww8glsy.cxx,v $
*
* $Revision: 1.28 $
*
* last change: $Author: rt $ $Date: 2007-07-26 08:22:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h>
#endif
#ifndef _NDTXT
#include <ndtxt.hxx>
#endif
#include <pam.hxx>
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen wg. SwFmtAnchor
#include <fmtanchr.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen wg. SwFrmFmt
#include <frmfmt.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX //autogen wg. SwDoc
#include <docary.hxx>
#endif
#ifndef _WW8GLSY_HXX
#include "ww8glsy.hxx"
#endif
#ifndef _WW8PAR_HXX
#include "ww8par.hxx"
#endif
WW8Glossary::WW8Glossary(SvStorageStreamRef &refStrm, BYTE nVersion,
SvStorage *pStg)
: pGlossary(0), rStrm(refStrm), xStg(pStg), nStrings(0)
{
refStrm->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
WW8Fib aWwFib(*refStrm, nVersion);
if (aWwFib.nFibBack >= 0x6A) //Word97
{
xTableStream = pStg->OpenSotStream(String::CreateFromAscii(
aWwFib.fWhichTblStm ? SL::a1Table : SL::a0Table), STREAM_STD_READ);
if (xTableStream.Is() && SVSTREAM_OK == xTableStream->GetError())
{
xTableStream->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
pGlossary =
new WW8GlossaryFib(*refStrm, nVersion, *xTableStream, aWwFib);
}
}
}
bool WW8Glossary::HasBareGraphicEnd(SwDoc *pDoc,SwNodeIndex &rIdx)
{
bool bRet=false;
for( USHORT nCnt = pDoc->GetSpzFrmFmts()->Count(); nCnt; )
{
SwFrmFmt* pFrmFmt = (*pDoc->GetSpzFrmFmts())[ --nCnt ];
if ( RES_FLYFRMFMT != pFrmFmt->Which() &&
RES_DRAWFRMFMT != pFrmFmt->Which() )
continue;
const SwFmtAnchor& rAnchor = pFrmFmt->GetAnchor();
const SwPosition* pAPos;
if( ( FLY_AT_CNTNT == rAnchor.GetAnchorId() ||
FLY_AUTO_CNTNT == rAnchor.GetAnchorId() ) &&
0 != ( pAPos = rAnchor.GetCntntAnchor()) &&
rIdx == pAPos->nNode.GetIndex() )
{
bRet=true;
break;
}
}
return bRet;
}
bool WW8Glossary::MakeEntries(SwDoc *pD, SwTextBlocks &rBlocks,
bool bSaveRelFile, const std::vector<String>& rStrings,
const std::vector<ww::bytes>& rExtra)
{
// this code will be called after reading all text into the
// empty sections
const String aOldURL( rBlocks.GetBaseURL() );
bool bRet=false;
if( bSaveRelFile )
{
rBlocks.SetBaseURL(
URIHelper::SmartRel2Abs(
INetURLObject(), rBlocks.GetFileName(),
URIHelper::GetMaybeFileHdl()));
}
else
rBlocks.SetBaseURL( aEmptyStr );
SwNodeIndex aDocEnd( pD->GetNodes().GetEndOfContent() );
SwNodeIndex aStart( *aDocEnd.GetNode().StartOfSectionNode(), 1 );
// search the first NormalStartNode
while( !( aStart.GetNode().IsStartNode() && SwNormalStartNode ==
aStart.GetNode().GetStartNode()->GetStartNodeType()) &&
aStart < aDocEnd )
aStart++;
if( aStart < aDocEnd )
{
SwTxtFmtColl* pColl = pD->GetTxtCollFromPool
(RES_POOLCOLL_STANDARD, false);
USHORT nGlosEntry = 0;
SwCntntNode* pCNd = 0;
do {
SwPaM aPam( aStart );
{
SwNodeIndex& rIdx = aPam.GetPoint()->nNode;
rIdx++;
if( 0 == ( pCNd = rIdx.GetNode().GetTxtNode() ) )
{
pCNd = pD->GetNodes().MakeTxtNode( rIdx, pColl );
rIdx = *pCNd;
}
}
aPam.GetPoint()->nContent.Assign( pCNd, 0 );
aPam.SetMark();
{
SwNodeIndex& rIdx = aPam.GetPoint()->nNode;
rIdx = aStart.GetNode().EndOfSectionIndex() - 1;
if(( 0 == ( pCNd = rIdx.GetNode().GetCntntNode() ) )
|| HasBareGraphicEnd(pD,rIdx))
{
rIdx++;
pCNd = pD->GetNodes().MakeTxtNode( rIdx, pColl );
rIdx = *pCNd;
}
}
aPam.GetPoint()->nContent.Assign( pCNd, pCNd->Len() );
// now we have the right selection for one entry. Copy this to
// the definied TextBlock, but only if it is not an autocorrection
// entry (== -1) otherwise the group indicates the group in the
// sttbfglsystyle list that this entry belongs to. Unused at the
// moment
const ww::bytes &rData = rExtra[nGlosEntry];
USHORT n = SVBT16ToShort( &(rData[2]) );
if(n != 0xFFFF)
{
rBlocks.ClearDoc();
const String &rLNm = rStrings[nGlosEntry];
String sShortcut = rLNm;
// Need to check make sure the shortcut is not already being used
xub_StrLen nStart = 0;
USHORT nCurPos = rBlocks.GetIndex( sShortcut );
xub_StrLen nLen = sShortcut.Len();
while( (USHORT)-1 != nCurPos )
{
sShortcut.Erase( nLen ) +=
String::CreateFromInt32( ++nStart ); // add an Number to it
nCurPos = rBlocks.GetIndex( sShortcut );
}
if( rBlocks.BeginPutDoc( sShortcut, sShortcut )) // Make the shortcut and the name the same
{
SwDoc* pGlDoc = rBlocks.GetDoc();
SwNodeIndex aIdx( pGlDoc->GetNodes().GetEndOfContent(),
-1 );
pCNd = aIdx.GetNode().GetCntntNode();
SwPosition aPos( aIdx, SwIndex( pCNd, pCNd->Len() ));
pD->Copy( aPam, aPos );
rBlocks.PutDoc();
}
}
aStart = aStart.GetNode().EndOfSectionIndex() + 1;
++nGlosEntry;
} while( aStart.GetNode().IsStartNode() &&
SwNormalStartNode == aStart.GetNode().
GetStartNode()->GetStartNodeType());
bRet=true;
}
// this code will be called after reading all text into the empty sections
rBlocks.SetBaseURL( aOldURL );
return bRet;
}
bool WW8Glossary::Load( SwTextBlocks &rBlocks, bool bSaveRelFile )
{
bool bRet=false;
if (pGlossary && pGlossary->IsGlossaryFib() && rBlocks.StartPutMuchBlockEntries())
{
//read the names of the autotext entries
std::vector<String> aStrings;
std::vector<ww::bytes> aData;
rtl_TextEncoding eStructCharSet =
WW8Fib::GetFIBCharset(pGlossary->chseTables);
WW8ReadSTTBF(true, *xTableStream, pGlossary->fcSttbfglsy,
pGlossary->lcbSttbfglsy, 0, eStructCharSet, aStrings, &aData );
rStrm->Seek(0);
if ((nStrings = aStrings.size()))
{
SfxObjectShellRef xDocSh(new SwDocShell(SFX_CREATE_MODE_INTERNAL));
if (xDocSh->DoInitNew(0))
{
SwDoc *pD = ((SwDocShell*)(&xDocSh))->GetDoc();
SwWW8ImplReader* pRdr = new SwWW8ImplReader(pGlossary->nVersion,
xStg, &rStrm, *pD, rBlocks.GetBaseURL(), true);
SwNodeIndex aIdx(
*pD->GetNodes().GetEndOfContent().StartOfSectionNode(), 1);
if( !aIdx.GetNode().IsTxtNode() )
{
ASSERT( !this, "wo ist der TextNode?" );
pD->GetNodes().GoNext( &aIdx );
}
SwPaM aPamo( aIdx );
aPamo.GetPoint()->nContent.Assign(aIdx.GetNode().GetCntntNode(),
0);
pRdr->LoadDoc(aPamo,this);
bRet = MakeEntries(pD, rBlocks, bSaveRelFile, aStrings, aData);
delete pRdr;
}
xDocSh->DoClose();
rBlocks.EndPutMuchBlockEntries();
}
}
return bRet;
}
bool WW8GlossaryFib::IsGlossaryFib()
{
if (!nFibError)
{
INT16 nFibMin;
INT16 nFibMax;
switch(nVersion)
{
case 6:
nFibMin = 0x0065; // von 101 WinWord 6.0
// 102 "
// und 103 WinWord 6.0 fuer Macintosh
// 104 "
nFibMax = 0x0069; // bis 105 WinWord 95
break;
case 7:
nFibMin = 0x0069; // von 105 WinWord 95
nFibMax = 0x0069; // bis 105 WinWord 95
break;
case 8:
nFibMin = 0x006A; // von 106 WinWord 97
nFibMax = 0x00c2; // bis 194 WinWord 2000
break;
default:
nFibMin = 0; // Programm-Fehler!
nFibMax = 0;
nFib = nFibBack = 1;
break;
}
if ( (nFibBack < nFibMin) || (nFibBack > nFibMax) )
nFibError = ERR_SWG_READ_ERROR; // Error melden
}
return !nFibError;
}
UINT32 WW8GlossaryFib::FindGlossaryFibOffset(SvStream &rTableStrm,
SvStream &rStrm, const WW8Fib &rFib)
{
WW8PLCF aPlc( &rTableStrm, rFib.fcPlcfsed, rFib.lcbPlcfsed, 12 );
WW8_CP start,ende;
void *pData;
aPlc.Get(start,ende,pData);
UINT32 nPo = SVBT32ToUInt32((BYTE *)pData+2);
//*pOut << hex << "Offset of last SEPX is " << nPo << endl;
UINT16 nLen;
if (nPo != 0xFFFFFFFF)
{
rStrm.Seek(nPo);
rStrm >> nLen;
}
else
{
nPo=0;
nLen=0;
}
// *pOut << hex << "Ends at " << nPo+len << endl;
nPo+=nLen;
UINT32 nEndLastPage;
if (nPo%512)
{
nEndLastPage = (nPo)/512;
nEndLastPage = (nEndLastPage+1)*512;
}
else
nEndLastPage = nPo;
//*pOut << hex << "SECOND FIB SHOULD BE FOUND at " << k << endl;
WW8PLCF xcPLCF( &rTableStrm, rFib.fcPlcfbteChpx,
rFib.lcbPlcfbteChpx, (8 > rFib.nVersion) ? 2 : 4);
xcPLCF.Get(start,ende,pData);
nPo = SVBT32ToUInt32((BYTE *)pData);
//*pOut << hex << "Offset of last CHPX is " << (nPo+1) *512<< endl;
if (((nPo+1)*512) > nEndLastPage) nEndLastPage = (nPo+1)*512;
WW8PLCF xpPLCF( &rTableStrm, rFib.fcPlcfbtePapx,
rFib.lcbPlcfbtePapx, (8 > rFib.nVersion) ? 2 : 4);
xpPLCF.Get(start,ende,pData);
nPo = SVBT32ToUInt32((BYTE *)pData);
//*pOut << hex << "Offset of last PAPX is " << nPo *512 << endl;
if (((nPo+1)*512) > nEndLastPage) nEndLastPage = (nPo+1)*512;
//*pOut << hex << "SECOND FIB SHOULD BE FOUND at " << nEndLastPage << endl;
return nEndLastPage;
}
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS swwarnings (1.27.222); FILE MERGED 2007/08/20 15:47:29 tl 1.27.222.2: RESYNC: (1.27-1.28); FILE MERGED 2007/04/03 13:00:52 tl 1.27.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ww8glsy.cxx,v $
*
* $Revision: 1.29 $
*
* last change: $Author: hr $ $Date: 2007-09-27 10:03:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h>
#endif
#ifndef _NDTXT
#include <ndtxt.hxx>
#endif
#include <pam.hxx>
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen wg. SwFmtAnchor
#include <fmtanchr.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen wg. SwFrmFmt
#include <frmfmt.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX //autogen wg. SwDoc
#include <docary.hxx>
#endif
#ifndef _WW8GLSY_HXX
#include "ww8glsy.hxx"
#endif
#ifndef _WW8PAR_HXX
#include "ww8par.hxx"
#endif
WW8Glossary::WW8Glossary(SvStorageStreamRef &refStrm, BYTE nVersion,
SvStorage *pStg)
: pGlossary(0), rStrm(refStrm), xStg(pStg), nStrings(0)
{
refStrm->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
WW8Fib aWwFib(*refStrm, nVersion);
if (aWwFib.nFibBack >= 0x6A) //Word97
{
xTableStream = pStg->OpenSotStream(String::CreateFromAscii(
aWwFib.fWhichTblStm ? SL::a1Table : SL::a0Table), STREAM_STD_READ);
if (xTableStream.Is() && SVSTREAM_OK == xTableStream->GetError())
{
xTableStream->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
pGlossary =
new WW8GlossaryFib(*refStrm, nVersion, *xTableStream, aWwFib);
}
}
}
bool WW8Glossary::HasBareGraphicEnd(SwDoc *pDoc,SwNodeIndex &rIdx)
{
bool bRet=false;
for( USHORT nCnt = pDoc->GetSpzFrmFmts()->Count(); nCnt; )
{
SwFrmFmt* pFrmFmt = (*pDoc->GetSpzFrmFmts())[ --nCnt ];
if ( RES_FLYFRMFMT != pFrmFmt->Which() &&
RES_DRAWFRMFMT != pFrmFmt->Which() )
continue;
const SwFmtAnchor& rAnchor = pFrmFmt->GetAnchor();
const SwPosition* pAPos;
if( ( FLY_AT_CNTNT == rAnchor.GetAnchorId() ||
FLY_AUTO_CNTNT == rAnchor.GetAnchorId() ) &&
0 != ( pAPos = rAnchor.GetCntntAnchor()) &&
rIdx == pAPos->nNode.GetIndex() )
{
bRet=true;
break;
}
}
return bRet;
}
bool WW8Glossary::MakeEntries(SwDoc *pD, SwTextBlocks &rBlocks,
bool bSaveRelFile, const std::vector<String>& rStrings,
const std::vector<ww::bytes>& rExtra)
{
// this code will be called after reading all text into the
// empty sections
const String aOldURL( rBlocks.GetBaseURL() );
bool bRet=false;
if( bSaveRelFile )
{
rBlocks.SetBaseURL(
URIHelper::SmartRel2Abs(
INetURLObject(), rBlocks.GetFileName(),
URIHelper::GetMaybeFileHdl()));
}
else
rBlocks.SetBaseURL( aEmptyStr );
SwNodeIndex aDocEnd( pD->GetNodes().GetEndOfContent() );
SwNodeIndex aStart( *aDocEnd.GetNode().StartOfSectionNode(), 1 );
// search the first NormalStartNode
while( !( aStart.GetNode().IsStartNode() && SwNormalStartNode ==
aStart.GetNode().GetStartNode()->GetStartNodeType()) &&
aStart < aDocEnd )
aStart++;
if( aStart < aDocEnd )
{
SwTxtFmtColl* pColl = pD->GetTxtCollFromPool
(RES_POOLCOLL_STANDARD, false);
USHORT nGlosEntry = 0;
SwCntntNode* pCNd = 0;
do {
SwPaM aPam( aStart );
{
SwNodeIndex& rIdx = aPam.GetPoint()->nNode;
rIdx++;
if( 0 == ( pCNd = rIdx.GetNode().GetTxtNode() ) )
{
pCNd = pD->GetNodes().MakeTxtNode( rIdx, pColl );
rIdx = *pCNd;
}
}
aPam.GetPoint()->nContent.Assign( pCNd, 0 );
aPam.SetMark();
{
SwNodeIndex& rIdx = aPam.GetPoint()->nNode;
rIdx = aStart.GetNode().EndOfSectionIndex() - 1;
if(( 0 == ( pCNd = rIdx.GetNode().GetCntntNode() ) )
|| HasBareGraphicEnd(pD,rIdx))
{
rIdx++;
pCNd = pD->GetNodes().MakeTxtNode( rIdx, pColl );
rIdx = *pCNd;
}
}
aPam.GetPoint()->nContent.Assign( pCNd, pCNd->Len() );
// now we have the right selection for one entry. Copy this to
// the definied TextBlock, but only if it is not an autocorrection
// entry (== -1) otherwise the group indicates the group in the
// sttbfglsystyle list that this entry belongs to. Unused at the
// moment
const ww::bytes &rData = rExtra[nGlosEntry];
USHORT n = SVBT16ToShort( &(rData[2]) );
if(n != 0xFFFF)
{
rBlocks.ClearDoc();
const String &rLNm = rStrings[nGlosEntry];
String sShortcut = rLNm;
// Need to check make sure the shortcut is not already being used
xub_StrLen nStart = 0;
USHORT nCurPos = rBlocks.GetIndex( sShortcut );
xub_StrLen nLen = sShortcut.Len();
while( (USHORT)-1 != nCurPos )
{
sShortcut.Erase( nLen ) +=
String::CreateFromInt32( ++nStart ); // add an Number to it
nCurPos = rBlocks.GetIndex( sShortcut );
}
if( rBlocks.BeginPutDoc( sShortcut, sShortcut )) // Make the shortcut and the name the same
{
SwDoc* pGlDoc = rBlocks.GetDoc();
SwNodeIndex aIdx( pGlDoc->GetNodes().GetEndOfContent(),
-1 );
pCNd = aIdx.GetNode().GetCntntNode();
SwPosition aPos( aIdx, SwIndex( pCNd, pCNd->Len() ));
pD->Copy( aPam, aPos );
rBlocks.PutDoc();
}
}
aStart = aStart.GetNode().EndOfSectionIndex() + 1;
++nGlosEntry;
} while( aStart.GetNode().IsStartNode() &&
SwNormalStartNode == aStart.GetNode().
GetStartNode()->GetStartNodeType());
bRet=true;
}
// this code will be called after reading all text into the empty sections
rBlocks.SetBaseURL( aOldURL );
return bRet;
}
bool WW8Glossary::Load( SwTextBlocks &rBlocks, bool bSaveRelFile )
{
bool bRet=false;
if (pGlossary && pGlossary->IsGlossaryFib() && rBlocks.StartPutMuchBlockEntries())
{
//read the names of the autotext entries
std::vector<String> aStrings;
std::vector<ww::bytes> aData;
rtl_TextEncoding eStructCharSet =
WW8Fib::GetFIBCharset(pGlossary->chseTables);
WW8ReadSTTBF(true, *xTableStream, pGlossary->fcSttbfglsy,
pGlossary->lcbSttbfglsy, 0, eStructCharSet, aStrings, &aData );
rStrm->Seek(0);
if ( 0 != (nStrings = static_cast< USHORT >(aStrings.size())))
{
SfxObjectShellRef xDocSh(new SwDocShell(SFX_CREATE_MODE_INTERNAL));
if (xDocSh->DoInitNew(0))
{
SwDoc *pD = ((SwDocShell*)(&xDocSh))->GetDoc();
SwWW8ImplReader* pRdr = new SwWW8ImplReader(pGlossary->nVersion,
xStg, &rStrm, *pD, rBlocks.GetBaseURL(), true);
SwNodeIndex aIdx(
*pD->GetNodes().GetEndOfContent().StartOfSectionNode(), 1);
if( !aIdx.GetNode().IsTxtNode() )
{
ASSERT( !this, "wo ist der TextNode?" );
pD->GetNodes().GoNext( &aIdx );
}
SwPaM aPamo( aIdx );
aPamo.GetPoint()->nContent.Assign(aIdx.GetNode().GetCntntNode(),
0);
pRdr->LoadDoc(aPamo,this);
bRet = MakeEntries(pD, rBlocks, bSaveRelFile, aStrings, aData);
delete pRdr;
}
xDocSh->DoClose();
rBlocks.EndPutMuchBlockEntries();
}
}
return bRet;
}
bool WW8GlossaryFib::IsGlossaryFib()
{
if (!nFibError)
{
INT16 nFibMin;
INT16 nFibMax;
switch(nVersion)
{
case 6:
nFibMin = 0x0065; // von 101 WinWord 6.0
// 102 "
// und 103 WinWord 6.0 fuer Macintosh
// 104 "
nFibMax = 0x0069; // bis 105 WinWord 95
break;
case 7:
nFibMin = 0x0069; // von 105 WinWord 95
nFibMax = 0x0069; // bis 105 WinWord 95
break;
case 8:
nFibMin = 0x006A; // von 106 WinWord 97
nFibMax = 0x00c2; // bis 194 WinWord 2000
break;
default:
nFibMin = 0; // Programm-Fehler!
nFibMax = 0;
nFib = nFibBack = 1;
break;
}
if ( (nFibBack < nFibMin) || (nFibBack > nFibMax) )
nFibError = ERR_SWG_READ_ERROR; // Error melden
}
return !nFibError;
}
UINT32 WW8GlossaryFib::FindGlossaryFibOffset(SvStream &rTableStrm,
SvStream &rStrm, const WW8Fib &rFib)
{
WW8PLCF aPlc( &rTableStrm, rFib.fcPlcfsed, rFib.lcbPlcfsed, 12 );
WW8_CP start,ende;
void *pData;
aPlc.Get(start,ende,pData);
UINT32 nPo = SVBT32ToUInt32((BYTE *)pData+2);
//*pOut << hex << "Offset of last SEPX is " << nPo << endl;
UINT16 nLen;
if (nPo != 0xFFFFFFFF)
{
rStrm.Seek(nPo);
rStrm >> nLen;
}
else
{
nPo=0;
nLen=0;
}
// *pOut << hex << "Ends at " << nPo+len << endl;
nPo+=nLen;
UINT32 nEndLastPage;
if (nPo%512)
{
nEndLastPage = (nPo)/512;
nEndLastPage = (nEndLastPage+1)*512;
}
else
nEndLastPage = nPo;
//*pOut << hex << "SECOND FIB SHOULD BE FOUND at " << k << endl;
WW8PLCF xcPLCF( &rTableStrm, rFib.fcPlcfbteChpx,
rFib.lcbPlcfbteChpx, (8 > rFib.nVersion) ? 2 : 4);
xcPLCF.Get(start,ende,pData);
nPo = SVBT32ToUInt32((BYTE *)pData);
//*pOut << hex << "Offset of last CHPX is " << (nPo+1) *512<< endl;
if (((nPo+1)*512) > nEndLastPage) nEndLastPage = (nPo+1)*512;
WW8PLCF xpPLCF( &rTableStrm, rFib.fcPlcfbtePapx,
rFib.lcbPlcfbtePapx, (8 > rFib.nVersion) ? 2 : 4);
xpPLCF.Get(start,ende,pData);
nPo = SVBT32ToUInt32((BYTE *)pData);
//*pOut << hex << "Offset of last PAPX is " << nPo *512 << endl;
if (((nPo+1)*512) > nEndLastPage) nEndLastPage = (nPo+1)*512;
//*pOut << hex << "SECOND FIB SHOULD BE FOUND at " << nEndLastPage << endl;
return nEndLastPage;
}
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|> |
<commit_before>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
// Boost (Extended STL)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/program_options.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
// DSIM
#include <dsim/DSIM_Service.hpp>
#include <dsim/config/dsim-paths.hpp>
// //////// Type definitions ///////
typedef std::vector<std::string> WordList_T;
// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_DSIM_DEFAULT_LOG_FILENAME ("simulate.log");
/** Default name and location for the (CSV) demand input file. */
const std::string K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME ("../../test/samples/demand01.csv");
/** Default name and location for the (CSV) schedule input file. */
const std::string K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME ("../../test/samples/schedule01.csv");
/** Default query string. */
const std::string K_DSIM_DEFAULT_QUERY_STRING ("my good old query");
/** Default name and location for the Xapian database. */
const std::string K_DSIM_DEFAULT_DB_USER ("dsim");
const std::string K_DSIM_DEFAULT_DB_PASSWD ("dsim");
const std::string K_DSIM_DEFAULT_DB_DBNAME ("dsim");
const std::string K_DSIM_DEFAULT_DB_HOST ("localhost");
const std::string K_DSIM_DEFAULT_DB_PORT ("3306");
// //////////////////////////////////////////////////////////////////////
void tokeniseStringIntoWordList (const std::string& iPhrase,
WordList_T& ioWordList) {
// Empty the word list
ioWordList.clear();
// Boost Tokeniser
typedef boost::tokenizer<boost::char_separator<char> > Tokeniser_T;
// Define the separators
const boost::char_separator<char> lSepatorList(" .,;:|+-*/_=!@#$%`~^&(){}[]?'<>\"");
// Initialise the phrase to be tokenised
Tokeniser_T lTokens (iPhrase, lSepatorList);
for (Tokeniser_T::const_iterator tok_iter = lTokens.begin();
tok_iter != lTokens.end(); ++tok_iter) {
const std::string& lTerm = *tok_iter;
ioWordList.push_back (lTerm);
}
}
// //////////////////////////////////////////////////////////////////////
std::string createStringFromWordList (const WordList_T& iWordList) {
std::ostringstream oStr;
unsigned short idx = iWordList.size();
for (WordList_T::const_iterator itWord = iWordList.begin();
itWord != iWordList.end(); ++itWord, --idx) {
const std::string& lWord = *itWord;
oStr << lWord;
if (idx > 1) {
oStr << " ";
}
}
return oStr.str();
}
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_DSIM_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
std::string& ioQueryString,
stdair::Filename_T& ioScheduleInputFilename,
stdair::Filename_T& ioDemandInputFilename,
std::string& ioLogFilename,
std::string& ioDBUser, std::string& ioDBPasswd,
std::string& ioDBHost, std::string& ioDBPort,
std::string& ioDBDBName) {
// Initialise the travel query string, if that one is empty
if (ioQueryString.empty() == true) {
ioQueryString = K_DSIM_DEFAULT_QUERY_STRING;
}
// Transform the query string into a list of words (STL strings)
WordList_T lWordList;
tokeniseStringIntoWordList (ioQueryString, lWordList);
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("demand,d",
boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME),
"(CVS) input file for the demand distributions")
("schedule,s",
boost::program_options::value< std::string >(&ioDemandInputFilename)->default_value(K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME),
"(CVS) input file for the schedules")
("log,l",
boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_DSIM_DEFAULT_LOG_FILENAME),
"Filepath for the logs")
("user,u",
boost::program_options::value< std::string >(&ioDBUser)->default_value(K_DSIM_DEFAULT_DB_USER),
"SQL database hostname (e.g., dsim)")
("passwd,p",
boost::program_options::value< std::string >(&ioDBPasswd)->default_value(K_DSIM_DEFAULT_DB_PASSWD),
"SQL database hostname (e.g., dsim)")
("host,H",
boost::program_options::value< std::string >(&ioDBHost)->default_value(K_DSIM_DEFAULT_DB_HOST),
"SQL database hostname (e.g., localhost)")
("port,P",
boost::program_options::value< std::string >(&ioDBPort)->default_value(K_DSIM_DEFAULT_DB_PORT),
"SQL database port (e.g., 3306)")
("dbname,m",
boost::program_options::value< std::string >(&ioDBDBName)->default_value(K_DSIM_DEFAULT_DB_DBNAME),
"SQL database name (e.g., dsim)")
("query,q",
boost::program_options::value< WordList_T >(&lWordList)->multitoken(),
"Query word list")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("simulate.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("schedule")) {
ioScheduleInputFilename = vm["schedule"].as< std::string >();
std::cout << "Schedule input filename is: " << ioScheduleInputFilename
<< std::endl;
}
if (vm.count ("demand")) {
ioDemandInputFilename = vm["demand"].as< std::string >();
std::cout << "Demand input filename is: " << ioDemandInputFilename
<< std::endl;
}
if (vm.count ("log")) {
ioLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << ioLogFilename << std::endl;
}
if (vm.count ("user")) {
ioDBUser = vm["user"].as< std::string >();
std::cout << "SQL database user name is: " << ioDBUser << std::endl;
}
if (vm.count ("passwd")) {
ioDBPasswd = vm["passwd"].as< std::string >();
//std::cout << "SQL database user password is: " << ioDBPasswd << std::endl;
}
if (vm.count ("host")) {
ioDBHost = vm["host"].as< std::string >();
std::cout << "SQL database host name is: " << ioDBHost << std::endl;
}
if (vm.count ("port")) {
ioDBPort = vm["port"].as< std::string >();
std::cout << "SQL database port number is: " << ioDBPort << std::endl;
}
if (vm.count ("dbname")) {
ioDBDBName = vm["dbname"].as< std::string >();
std::cout << "SQL database name is: " << ioDBDBName << std::endl;
}
ioQueryString = createStringFromWordList (lWordList);
std::cout << "The query string is: " << ioQueryString << std::endl;
return 0;
}
// ///////// M A I N ////////////
int main (int argc, char* argv[]) {
try {
// Query
std::string lQuery;
// Schedule input file name
stdair::Filename_T lScheduleInputFilename;
// Demand input file name
stdair::Filename_T lDemandInputFilename;
// Output log File
std::string lLogFilename;
// SQL database parameters
std::string lDBUser;
std::string lDBPasswd;
std::string lDBHost;
std::string lDBPort;
std::string lDBDBName;
// Airline code
stdair::AirlineCode_T lAirlineCode ("BA");
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lQuery, lScheduleInputFilename,
lDemandInputFilename, lLogFilename,
lDBUser, lDBPasswd, lDBHost, lDBPort, lDBDBName);
if (lOptionParserStatus == K_DSIM_EARLY_RETURN_STATUS) {
return 0;
}
// Set the database parameters
stdair::BasDBParams lDBParams (lDBUser, lDBPasswd, lDBHost, lDBPort,
lDBDBName);
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the simulation context
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
DSIM::DSIM_Service dsimService (lLogParams, lDBParams,
lScheduleInputFilename,
lDemandInputFilename);
// Perform a simulation
dsimService.simulate();
// DEBUG
// Display the airlines stored in the database
dsimService.displayAirlineListFromDB();
} CATCH_ALL_EXCEPTIONS
return 0;
}
<commit_msg>[Dev] Added missing input files as option of the batch.<commit_after>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
// Boost (Extended STL)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/program_options.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
// DSIM
#include <dsim/DSIM_Service.hpp>
#include <dsim/config/dsim-paths.hpp>
// //////// Type definitions ///////
typedef std::vector<std::string> WordList_T;
// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_DSIM_DEFAULT_LOG_FILENAME ("simulate.log");
/** Default name and location for the (CSV) demand input file. */
const std::string K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME ("../../test/samples/demand01.csv");
/** Default name and location for the (CSV) schedule input file. */
const std::string K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME ("../../test/samples/schedule01.csv");
/** Default name and location for the (CSV) O&D input file. */
const std::string K_DSIM_DEFAULT_OND_INPUT_FILENAME ("../../test/samples/ond01.csv");
/** Default name and location for the (CSV) fare input file. */
const std::string K_DSIM_DEFAULT_FARE_INPUT_FILENAME ("../../test/samples/fare01.csv");
/** Default query string. */
const std::string K_DSIM_DEFAULT_QUERY_STRING ("my good old query");
/** Default name and location for the Xapian database. */
const std::string K_DSIM_DEFAULT_DB_USER ("dsim");
const std::string K_DSIM_DEFAULT_DB_PASSWD ("dsim");
const std::string K_DSIM_DEFAULT_DB_DBNAME ("dsim");
const std::string K_DSIM_DEFAULT_DB_HOST ("localhost");
const std::string K_DSIM_DEFAULT_DB_PORT ("3306");
// //////////////////////////////////////////////////////////////////////
void tokeniseStringIntoWordList (const std::string& iPhrase,
WordList_T& ioWordList) {
// Empty the word list
ioWordList.clear();
// Boost Tokeniser
typedef boost::tokenizer<boost::char_separator<char> > Tokeniser_T;
// Define the separators
const boost::char_separator<char> lSepatorList(" .,;:|+-*/_=!@#$%`~^&(){}[]?'<>\"");
// Initialise the phrase to be tokenised
Tokeniser_T lTokens (iPhrase, lSepatorList);
for (Tokeniser_T::const_iterator tok_iter = lTokens.begin();
tok_iter != lTokens.end(); ++tok_iter) {
const std::string& lTerm = *tok_iter;
ioWordList.push_back (lTerm);
}
}
// //////////////////////////////////////////////////////////////////////
std::string createStringFromWordList (const WordList_T& iWordList) {
std::ostringstream oStr;
unsigned short idx = iWordList.size();
for (WordList_T::const_iterator itWord = iWordList.begin();
itWord != iWordList.end(); ++itWord, --idx) {
const std::string& lWord = *itWord;
oStr << lWord;
if (idx > 1) {
oStr << " ";
}
}
return oStr.str();
}
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_DSIM_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
std::string& ioQueryString,
stdair::Filename_T& ioDemandInputFilename,
stdair::Filename_T& ioScheduleInputFilename,
stdair::Filename_T& ioOnDInputFilename,
stdair::Filename_T& ioFareInputFilename,
std::string& ioLogFilename,
std::string& ioDBUser, std::string& ioDBPasswd,
std::string& ioDBHost, std::string& ioDBPort,
std::string& ioDBDBName) {
// Initialise the travel query string, if that one is empty
if (ioQueryString.empty() == true) {
ioQueryString = K_DSIM_DEFAULT_QUERY_STRING;
}
// Transform the query string into a list of words (STL strings)
WordList_T lWordList;
tokeniseStringIntoWordList (ioQueryString, lWordList);
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("demand,d",
boost::program_options::value< std::string >(&ioDemandInputFilename)->default_value(K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME),
"(CVS) input file for the demand distributions")
("schedule,s",
boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME),
"(CVS) input file for the schedules")
("ond,o",
boost::program_options::value< std::string >(&ioOnDInputFilename)->default_value(K_DSIM_DEFAULT_OND_INPUT_FILENAME),
"(CVS) input file for the O&D definitions")
("fare,f",
boost::program_options::value< std::string >(&ioFareInputFilename)->default_value(K_DSIM_DEFAULT_FARE_INPUT_FILENAME),
"(CVS) input file for the fares")
("log,l",
boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_DSIM_DEFAULT_LOG_FILENAME),
"Filepath for the logs")
("user,u",
boost::program_options::value< std::string >(&ioDBUser)->default_value(K_DSIM_DEFAULT_DB_USER),
"SQL database hostname (e.g., dsim)")
("passwd,p",
boost::program_options::value< std::string >(&ioDBPasswd)->default_value(K_DSIM_DEFAULT_DB_PASSWD),
"SQL database hostname (e.g., dsim)")
("host,H",
boost::program_options::value< std::string >(&ioDBHost)->default_value(K_DSIM_DEFAULT_DB_HOST),
"SQL database hostname (e.g., localhost)")
("port,P",
boost::program_options::value< std::string >(&ioDBPort)->default_value(K_DSIM_DEFAULT_DB_PORT),
"SQL database port (e.g., 3306)")
("dbname,m",
boost::program_options::value< std::string >(&ioDBDBName)->default_value(K_DSIM_DEFAULT_DB_DBNAME),
"SQL database name (e.g., dsim)")
("query,q",
boost::program_options::value< WordList_T >(&lWordList)->multitoken(),
"Query word list")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("simulate.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("demand")) {
ioDemandInputFilename = vm["demand"].as< std::string >();
std::cout << "Demand input filename is: " << ioDemandInputFilename
<< std::endl;
}
if (vm.count ("ond")) {
ioOnDInputFilename = vm["ond"].as< std::string >();
std::cout << "O&D input filename is: " << ioOnDInputFilename << std::endl;
}
if (vm.count ("fare")) {
ioFareInputFilename = vm["fare"].as< std::string >();
std::cout << "Fare input filename is: " << ioFareInputFilename << std::endl;
}
if (vm.count ("schedule")) {
ioScheduleInputFilename = vm["schedule"].as< std::string >();
std::cout << "Schedule input filename is: " << ioScheduleInputFilename
<< std::endl;
}
if (vm.count ("log")) {
ioLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << ioLogFilename << std::endl;
}
if (vm.count ("user")) {
ioDBUser = vm["user"].as< std::string >();
std::cout << "SQL database user name is: " << ioDBUser << std::endl;
}
if (vm.count ("passwd")) {
ioDBPasswd = vm["passwd"].as< std::string >();
//std::cout << "SQL database user password is: " << ioDBPasswd << std::endl;
}
if (vm.count ("host")) {
ioDBHost = vm["host"].as< std::string >();
std::cout << "SQL database host name is: " << ioDBHost << std::endl;
}
if (vm.count ("port")) {
ioDBPort = vm["port"].as< std::string >();
std::cout << "SQL database port number is: " << ioDBPort << std::endl;
}
if (vm.count ("dbname")) {
ioDBDBName = vm["dbname"].as< std::string >();
std::cout << "SQL database name is: " << ioDBDBName << std::endl;
}
ioQueryString = createStringFromWordList (lWordList);
std::cout << "The query string is: " << ioQueryString << std::endl;
return 0;
}
// ///////// M A I N ////////////
int main (int argc, char* argv[]) {
try {
// Query
std::string lQuery;
// Demand input file name
stdair::Filename_T lDemandInputFilename;
// Schedule input file name
stdair::Filename_T lScheduleInputFilename;
// O&D input filename
std::string lOnDInputFilename;
// Fare input filename
std::string lFareInputFilename;
// Output log File
std::string lLogFilename;
// SQL database parameters
std::string lDBUser;
std::string lDBPasswd;
std::string lDBHost;
std::string lDBPort;
std::string lDBDBName;
// Airline code
stdair::AirlineCode_T lAirlineCode ("BA");
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lQuery, lDemandInputFilename,
lScheduleInputFilename, lOnDInputFilename,
lFareInputFilename, lLogFilename,
lDBUser, lDBPasswd, lDBHost, lDBPort, lDBDBName);
if (lOptionParserStatus == K_DSIM_EARLY_RETURN_STATUS) {
return 0;
}
// Set the database parameters
stdair::BasDBParams lDBParams (lDBUser, lDBPasswd, lDBHost, lDBPort,
lDBDBName);
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the simulation context
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
DSIM::DSIM_Service dsimService (lLogParams, lDBParams,
lScheduleInputFilename, lOnDInputFilename,
lFareInputFilename, lDemandInputFilename);
// Perform a simulation
dsimService.simulate();
// DEBUG
// Display the airlines stored in the database
dsimService.displayAirlineListFromDB();
} CATCH_ALL_EXCEPTIONS
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: labelcfg.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: os $ $Date: 2001-09-21 14:20:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _LABELCFG_HXX
#include <labelcfg.hxx>
#endif
#ifndef _LABIMP_HXX
#include <labimp.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED
#include <unotools/configpathes.hxx>
#endif
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
#define C2U(cChar) OUString::createFromAscii(cChar)
/* -----------------------------15.01.01 11:17--------------------------------
---------------------------------------------------------------------------*/
SwLabelConfig::SwLabelConfig() :
ConfigItem(C2U("Office.Labels/Manufacturer"))
{
aNodeNames = GetNodeNames(OUString());
}
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwLabelConfig::~SwLabelConfig()
{
}
/* -----------------------------06.09.00 16:43--------------------------------
---------------------------------------------------------------------------*/
void SwLabelConfig::Commit()
{
// the config item is not writable yet
}
/* -----------------------------15.01.01 11:42--------------------------------
---------------------------------------------------------------------------*/
Sequence<OUString> lcl_CreatePropertyNames(const OUString& rPrefix)
{
Sequence<OUString> aProperties(2);
OUString* pProperties = aProperties.getArray();
for(sal_Int32 nProp = 0; nProp < 2; nProp++)
pProperties[nProp] = rPrefix;
pProperties[ 0] += C2U("Name");
pProperties[ 1] += C2U("Measure");
return aProperties;
}
//-----------------------------------------------------------------------------
SwLabRec* lcl_CreateSwLabRec(Sequence<Any>& rValues, const OUString& rManufacturer)
{
SwLabRec* pNewRec = new SwLabRec;
const Any* pValues = rValues.getConstArray();
OUString sTmp;
pNewRec->aMake = rManufacturer;
for(sal_Int32 nProp = 0; nProp < rValues.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case 0: pValues[nProp] >>= sTmp; pNewRec->aType = sTmp; break;
case 1:
{
//all values are contained as colon-separated 1/100 mm values except for the
//continuous flag ('C'/'S')
pValues[nProp] >>= sTmp;
String sMeasure(sTmp);
USHORT nTokenCount = sMeasure.GetTokenCount(';');
xub_StrLen nIdx = 0;
for(USHORT i = 0; i < nTokenCount; i++)
{
String sToken(sMeasure.GetToken(i, ';' ));
int nVal = sToken.ToInt32();
switch(i)
{
case 0 : pNewRec->bCont = sToken.GetChar(0) == 'C'; break;
case 1 : pNewRec->lHDist = MM100_TO_TWIP(nVal);break;
case 2 : pNewRec->lVDist = MM100_TO_TWIP(nVal);break;
case 3 : pNewRec->lWidth = MM100_TO_TWIP(nVal);break;
case 4 : pNewRec->lHeight = MM100_TO_TWIP(nVal); break;
case 5 : pNewRec->lLeft = MM100_TO_TWIP(nVal);break;
case 6 : pNewRec->lUpper = MM100_TO_TWIP(nVal);break;
case 7 : pNewRec->nCols = nVal; break;
case 8 : pNewRec->nRows = nVal; break;
}
}
}
break;
}
}
}
return pNewRec;
}
//-----------------------------------------------------------------------------
Sequence<PropertyValue> lcl_CreateProperties(
Sequence<OUString>& rPropNames, const SwLabRec& rRec)
{
const OUString* pNames = rPropNames.getConstArray();
Sequence<PropertyValue> aRet(rPropNames.getLength());
PropertyValue* pValues = aRet.getArray();
OUString sColon(C2U(";"));
for(sal_Int32 nProp = 0; nProp < rPropNames.getLength(); nProp++)
{
pValues[nProp].Name = pNames[nProp];
switch(nProp)
{
case 0: pValues[nProp].Value <<= OUString(rRec.aType); break;
case 1:
{
OUString sTmp;
sTmp += C2U( rRec.bCont ? "C" : "S"); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHDist) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lVDist)); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lWidth) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHeight) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lLeft) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lUpper) ); sTmp += sColon;
sTmp += OUString::valueOf(rRec.nCols );sTmp += sColon;
sTmp += OUString::valueOf(rRec.nRows );
pValues[nProp].Value <<= sTmp;
}
break;
}
}
return aRet;
}
//-----------------------------------------------------------------------------
void SwLabelConfig::FillLabels(const OUString& rManufacturer, SwLabRecs& rLabArr)
{
OUString sManufacturer(wrapConfigurationElementName(rManufacturer));
const Sequence<OUString> aLabels = GetNodeNames(sManufacturer);
const OUString* pLabels = aLabels.getConstArray();
for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++)
{
OUString sPrefix(sManufacturer);
sPrefix += C2U("/");
sPrefix += pLabels[nLabel];
sPrefix += C2U("/");
Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix);
Sequence<Any> aValues = GetProperties(aPropNames);
SwLabRec* pNewRec = lcl_CreateSwLabRec(aValues, rManufacturer);
rLabArr.C40_INSERT( SwLabRec, pNewRec, rLabArr.Count() );
}
}
/* -----------------------------23.01.01 11:36--------------------------------
---------------------------------------------------------------------------*/
sal_Bool SwLabelConfig::HasLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType)
{
const OUString* pNode = aNodeNames.getConstArray();
sal_Bool bFound = sal_False;
for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++)
{
if(pNode[nNode] == rManufacturer)
bFound = sal_True;
}
if(bFound)
{
OUString sManufacturer(wrapConfigurationElementName(rManufacturer));
const Sequence<OUString> aLabels = GetNodeNames(sManufacturer);
const OUString* pLabels = aLabels.getConstArray();
for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++)
{
OUString sPrefix(sManufacturer);
sPrefix += C2U("/");
sPrefix += pLabels[nLabel];
sPrefix += C2U("/");
Sequence<OUString> aProperties(1);
aProperties.getArray()[0] = sPrefix;
aProperties.getArray()[0] += C2U("Name");
Sequence<Any> aValues = GetProperties(aProperties);
const Any* pValues = aValues.getConstArray();
if(pValues[0].hasValue())
{
OUString sTmp;
pValues[0] >>= sTmp;
if(rType == sTmp)
return sal_True;
}
}
}
return sal_False;
}
/* -----------------------------23.01.01 11:36--------------------------------
---------------------------------------------------------------------------*/
sal_Bool lcl_Exists(const OUString& rNode, const Sequence<OUString>& rLabels)
{
const OUString* pLabels = rLabels.getConstArray();
for(sal_Int32 i = 0; i < rLabels.getLength(); i++)
if(pLabels[i] == rNode)
return sal_True;
return sal_False;
}
//-----------------------------------------------------------------------------
void SwLabelConfig::SaveLabel( const rtl::OUString& rManufacturer,
const rtl::OUString& rType, const SwLabRec& rRec)
{
const OUString* pNode = aNodeNames.getConstArray();
sal_Bool bFound = sal_False;
for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++)
{
if(pNode[nNode] == rManufacturer)
bFound = sal_True;
}
if(!bFound)
{
if(!AddNode(OUString(), rManufacturer))
{
DBG_ERROR("New configuration node could not be created")
return ;
}
else
{
aNodeNames = GetNodeNames(OUString());
}
}
OUString sManufacturer(wrapConfigurationElementName(rManufacturer));
const Sequence<OUString> aLabels = GetNodeNames(sManufacturer);
const OUString* pLabels = aLabels.getConstArray();
OUString sFoundNode;
for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++)
{
OUString sPrefix(sManufacturer);
sPrefix += C2U("/");
sPrefix += pLabels[nLabel];
sPrefix += C2U("/");
Sequence<OUString> aProperties(1);
aProperties.getArray()[0] = sPrefix;
aProperties.getArray()[0] += C2U("Name");
Sequence<Any> aValues = GetProperties(aProperties);
const Any* pValues = aValues.getConstArray();
if(pValues[0].hasValue())
{
OUString sTmp;
pValues[0] >>= sTmp;
if(rType == sTmp)
{
sFoundNode = pLabels[nLabel];
break;
}
}
}
// if not found - generate a unique node name
if(!sFoundNode.getLength())
{
sal_Int32 nIndex = aLabels.getLength();
OUString sPrefix(C2U("Label"));
sFoundNode = sPrefix;
sFoundNode += OUString::valueOf(nIndex);
while(lcl_Exists(sFoundNode, aLabels))
{
sFoundNode = sPrefix;
sFoundNode += OUString::valueOf(nIndex++);
}
}
OUString sPrefix(rManufacturer);
sPrefix += C2U("/");
sPrefix += sFoundNode;
sPrefix += C2U("/");
Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix);
Sequence<PropertyValue> aPropValues = lcl_CreateProperties(aPropNames, rRec);
SetSetProperties(rManufacturer, aPropValues);
}
<commit_msg>#102186#<commit_after>/*************************************************************************
*
* $RCSfile: labelcfg.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: iha $ $Date: 2002-08-09 08:26:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _LABELCFG_HXX
#include <labelcfg.hxx>
#endif
#ifndef _LABIMP_HXX
#include <labimp.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED
#include <unotools/configpathes.hxx>
#endif
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
#define C2U(cChar) OUString::createFromAscii(cChar)
/* -----------------------------15.01.01 11:17--------------------------------
---------------------------------------------------------------------------*/
SwLabelConfig::SwLabelConfig() :
ConfigItem(C2U("Office.Labels/Manufacturer"))
{
aNodeNames = GetNodeNames(OUString());
}
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwLabelConfig::~SwLabelConfig()
{
}
/* -----------------------------06.09.00 16:43--------------------------------
---------------------------------------------------------------------------*/
void SwLabelConfig::Commit()
{
// the config item is not writable yet
}
/* -----------------------------15.01.01 11:42--------------------------------
---------------------------------------------------------------------------*/
Sequence<OUString> lcl_CreatePropertyNames(const OUString& rPrefix)
{
Sequence<OUString> aProperties(2);
OUString* pProperties = aProperties.getArray();
for(sal_Int32 nProp = 0; nProp < 2; nProp++)
pProperties[nProp] = rPrefix;
pProperties[ 0] += C2U("Name");
pProperties[ 1] += C2U("Measure");
return aProperties;
}
//-----------------------------------------------------------------------------
SwLabRec* lcl_CreateSwLabRec(Sequence<Any>& rValues, const OUString& rManufacturer)
{
SwLabRec* pNewRec = new SwLabRec;
const Any* pValues = rValues.getConstArray();
OUString sTmp;
pNewRec->aMake = rManufacturer;
for(sal_Int32 nProp = 0; nProp < rValues.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case 0: pValues[nProp] >>= sTmp; pNewRec->aType = sTmp; break;
case 1:
{
//all values are contained as colon-separated 1/100 mm values except for the
//continuous flag ('C'/'S')
pValues[nProp] >>= sTmp;
String sMeasure(sTmp);
USHORT nTokenCount = sMeasure.GetTokenCount(';');
xub_StrLen nIdx = 0;
for(USHORT i = 0; i < nTokenCount; i++)
{
String sToken(sMeasure.GetToken(i, ';' ));
int nVal = sToken.ToInt32();
switch(i)
{
case 0 : pNewRec->bCont = sToken.GetChar(0) == 'C'; break;
case 1 : pNewRec->lHDist = MM100_TO_TWIP(nVal);break;
case 2 : pNewRec->lVDist = MM100_TO_TWIP(nVal);break;
case 3 : pNewRec->lWidth = MM100_TO_TWIP(nVal);break;
case 4 : pNewRec->lHeight = MM100_TO_TWIP(nVal); break;
case 5 : pNewRec->lLeft = MM100_TO_TWIP(nVal);break;
case 6 : pNewRec->lUpper = MM100_TO_TWIP(nVal);break;
case 7 : pNewRec->nCols = nVal; break;
case 8 : pNewRec->nRows = nVal; break;
}
}
}
break;
}
}
}
return pNewRec;
}
//-----------------------------------------------------------------------------
Sequence<PropertyValue> lcl_CreateProperties(
Sequence<OUString>& rPropNames, const SwLabRec& rRec)
{
const OUString* pNames = rPropNames.getConstArray();
Sequence<PropertyValue> aRet(rPropNames.getLength());
PropertyValue* pValues = aRet.getArray();
OUString sColon(C2U(";"));
for(sal_Int32 nProp = 0; nProp < rPropNames.getLength(); nProp++)
{
pValues[nProp].Name = pNames[nProp];
switch(nProp)
{
case 0: pValues[nProp].Value <<= OUString(rRec.aType); break;
case 1:
{
OUString sTmp;
sTmp += C2U( rRec.bCont ? "C" : "S"); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHDist) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lVDist)); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lWidth) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHeight) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lLeft) ); sTmp += sColon;
sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lUpper) ); sTmp += sColon;
sTmp += OUString::valueOf(rRec.nCols );sTmp += sColon;
sTmp += OUString::valueOf(rRec.nRows );
pValues[nProp].Value <<= sTmp;
}
break;
}
}
return aRet;
}
//-----------------------------------------------------------------------------
void SwLabelConfig::FillLabels(const OUString& rManufacturer, SwLabRecs& rLabArr)
{
OUString sManufacturer(wrapConfigurationElementName(rManufacturer));
const Sequence<OUString> aLabels = GetNodeNames(sManufacturer);
const OUString* pLabels = aLabels.getConstArray();
for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++)
{
OUString sPrefix(sManufacturer);
sPrefix += C2U("/");
sPrefix += pLabels[nLabel];
sPrefix += C2U("/");
Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix);
Sequence<Any> aValues = GetProperties(aPropNames);
SwLabRec* pNewRec = lcl_CreateSwLabRec(aValues, rManufacturer);
rLabArr.C40_INSERT( SwLabRec, pNewRec, rLabArr.Count() );
}
}
/* -----------------------------23.01.01 11:36--------------------------------
---------------------------------------------------------------------------*/
sal_Bool SwLabelConfig::HasLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType)
{
const OUString* pNode = aNodeNames.getConstArray();
sal_Bool bFound = sal_False;
for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++)
{
if(pNode[nNode] == rManufacturer)
bFound = sal_True;
}
if(bFound)
{
OUString sManufacturer(wrapConfigurationElementName(rManufacturer));
const Sequence<OUString> aLabels = GetNodeNames(sManufacturer);
const OUString* pLabels = aLabels.getConstArray();
for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++)
{
OUString sPrefix(sManufacturer);
sPrefix += C2U("/");
sPrefix += pLabels[nLabel];
sPrefix += C2U("/");
Sequence<OUString> aProperties(1);
aProperties.getArray()[0] = sPrefix;
aProperties.getArray()[0] += C2U("Name");
Sequence<Any> aValues = GetProperties(aProperties);
const Any* pValues = aValues.getConstArray();
if(pValues[0].hasValue())
{
OUString sTmp;
pValues[0] >>= sTmp;
if(rType == sTmp)
return sal_True;
}
}
}
return sal_False;
}
/* -----------------------------23.01.01 11:36--------------------------------
---------------------------------------------------------------------------*/
sal_Bool lcl_Exists(const OUString& rNode, const Sequence<OUString>& rLabels)
{
const OUString* pLabels = rLabels.getConstArray();
for(sal_Int32 i = 0; i < rLabels.getLength(); i++)
if(pLabels[i] == rNode)
return sal_True;
return sal_False;
}
//-----------------------------------------------------------------------------
void SwLabelConfig::SaveLabel( const rtl::OUString& rManufacturer,
const rtl::OUString& rType, const SwLabRec& rRec)
{
const OUString* pNode = aNodeNames.getConstArray();
sal_Bool bFound = sal_False;
for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++)
{
if(pNode[nNode] == rManufacturer)
bFound = sal_True;
}
if(!bFound)
{
if(!AddNode(OUString(), rManufacturer))
{
DBG_ERROR("New configuration node could not be created")
return ;
}
else
{
aNodeNames = GetNodeNames(OUString());
}
}
OUString sManufacturer(wrapConfigurationElementName(rManufacturer));
const Sequence<OUString> aLabels = GetNodeNames(sManufacturer);
const OUString* pLabels = aLabels.getConstArray();
OUString sFoundNode;
for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++)
{
OUString sPrefix(sManufacturer);
sPrefix += C2U("/");
sPrefix += pLabels[nLabel];
sPrefix += C2U("/");
Sequence<OUString> aProperties(1);
aProperties.getArray()[0] = sPrefix;
aProperties.getArray()[0] += C2U("Name");
Sequence<Any> aValues = GetProperties(aProperties);
const Any* pValues = aValues.getConstArray();
if(pValues[0].hasValue())
{
OUString sTmp;
pValues[0] >>= sTmp;
if(rType == sTmp)
{
sFoundNode = pLabels[nLabel];
break;
}
}
}
// if not found - generate a unique node name
if(!sFoundNode.getLength())
{
sal_Int32 nIndex = aLabels.getLength();
OUString sPrefix(C2U("Label"));
sFoundNode = sPrefix;
sFoundNode += OUString::valueOf(nIndex);
while(lcl_Exists(sFoundNode, aLabels))
{
sFoundNode = sPrefix;
sFoundNode += OUString::valueOf(nIndex++);
}
}
OUString sPrefix(wrapConfigurationElementName(rManufacturer));
sPrefix += C2U("/");
sPrefix += sFoundNode;
sPrefix += C2U("/");
Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix);
Sequence<PropertyValue> aPropValues = lcl_CreateProperties(aPropNames, rRec);
SetSetProperties(wrapConfigurationElementName(rManufacturer), aPropValues);
}
<|endoftext|> |
<commit_before>#include "worldNode.hh"
#include "../logger.hh"
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include <sstream>
#include <atomic>
using namespace std;
// Static counter for the id, matters only on server
static std::atomic<unsigned int> nodeIdCounter;
// Bundling few flags to clean a bit the creation of stringstreams:
#define SS_RW_BIN std::stringstream::in | std::stringstream::out | std::stringstream::binary
WorldNode::WorldNode()
{
id = ++nodeIdCounter;
parent = 0;
position = glm::vec3( 0 );
position.y = 5;
position.z = -5;
rotation = glm::quat();
scale = glm::vec3( 1.f );
}
WorldNode::~WorldNode()
{
}
string WorldNode::Serialize( vector<string> vars )
{
// If we didn't receive any vars, serialize everything:
if( (vars.end() - vars.begin()) <= 0 )
{
vars.push_back( "id" );
vars.push_back( "position" );
vars.push_back( "rotation" );
vars.push_back( "scale" );
}
// Stream for the serialized data
stringstream dataStream( SS_RW_BIN );
// Total count of fields / member variables
unsigned char fieldCount = 0;
// For every var
for( auto e = vars.begin(); e != vars.end(); e++ )
{
if( SerializeField( *e, dataStream ) )
{
fieldCount++;
}
}
// Create the header; it's just the count of fields
stringstream headerStream( SS_RW_BIN );
SerializeUint8( headerStream, fieldCount );
// Join header and the fields and return the result
string serialized = headerStream.str();
serialized += dataStream.str();
return serialized;
}
bool WorldNode::Unserialize( string data )
{
stringstream dataStream( SS_RW_BIN );
dataStream << data;
// Field count:
uint8_t fieldCount = UnserializeUint8( dataStream );
for( int i=0; i < fieldCount; i++ )
{
// Read the byte count for this field
uint8_t fieldLength = UnserializeUint8( dataStream );
// Fetch the field name
string fieldName;
string fieldData;
if( !getline( dataStream, fieldName, ':' ) )
{
LOG_ERROR( "Error: WorldNode::Unserialize() failed to find field name!" );
break;
}
// Calculate the amount of data and allocate the buffer:
uint8_t fieldDataLength = fieldLength - fieldName.length() - 1;
assert( fieldDataLength > 0 );
char *buffer = new char[fieldLength];
// Copy the field data to other stream
stringstream fieldDataStream( SS_RW_BIN );
dataStream.read( buffer, fieldDataLength );
fieldDataStream.write( buffer, fieldDataLength );
// Free the memory for buffer
delete[] buffer;
// Unserialize and handle the field:
if( !UnserializeField( fieldName, fieldDataStream ) )
{
return false;
}
}
return false;
}
bool WorldNode::SerializeField( std::string &fieldName, std::stringstream &stream )
{
stringstream fieldStream = stringstream( SS_RW_BIN );
unsigned char fieldDataLength = 0;
string fieldDataString;
// ID
if( !fieldName.compare( "id" ) )
{
fieldStream << "id:";
SerializeUint32( fieldStream, id );
}
// POSITION
else if( !fieldName.compare( "position" ) )
{
fieldStream << "position:";
SerializeFloat( fieldStream, position.x );
SerializeFloat( fieldStream, position.y );
SerializeFloat( fieldStream, position.z );
}
// ROTATION
else if( !fieldName.compare( "rotation" ) )
{
fieldStream << "rotation:";
SerializeFloat( fieldStream, rotation.x );
SerializeFloat( fieldStream, rotation.y );
SerializeFloat( fieldStream, rotation.z );
SerializeFloat( fieldStream, rotation.w );
}
// SCALE
else if( !fieldName.compare( "scale" ) )
{
fieldStream << "scale:";
SerializeFloat( fieldStream, scale.x );
SerializeFloat( fieldStream, scale.y );
SerializeFloat( fieldStream, scale.z );
}
// No fitting field found?
else
{
LOG_ERROR( ToString(
"SerializeField failed because '" << fieldName <<
"' is not a field that it knows how to handle!"
) );
return false;
}
// Handle the fieldStream to get the
// data as a string and the length of it.
fieldDataString = fieldStream.str();
fieldDataLength = fieldDataString.length();
// Do we have anything to serialize?
assert( fieldDataLength > 0 );
// Write the header / amount of data:
SerializeUint8( stream, fieldDataLength );
// Write the data:
stream << fieldDataString;
return true;
}
bool WorldNode::UnserializeField( std::string &fieldName, std::stringstream &stream )
{
// Calculate the length
stream.seekp( 0, ios::end );
size_t streamLength = static_cast<size_t>( stream.tellp() );
stream.seekp( 0, ios::beg );
assert( streamLength > 0 );
LOG( ToString( "Got field " << fieldName << "(" << (int)streamLength << ") with value '" \
<< stream.str() << "'" ) );
// ID
if( !fieldName.compare( "id" ) )
{
if( streamLength != (size_t)(sizeof( unsigned int ) ) )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( unsigned int ) <<
" instead of " << streamLength << "!"
) );
return false;
}
id = UnserializeUint32( stream );
LOG( ToString( "Result: id = " << id << endl ) );
}
// POSITION
else if( !fieldName.compare( "position" ) )
{
if( streamLength != (size_t)(sizeof( position.x ) * 3) )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( position.x ) * 3 <<
" instead of " << streamLength << "!"
) );
return false;
}
position.x = UnserializeFloat( stream );
position.y = UnserializeFloat( stream );
position.z = UnserializeFloat( stream );
LOG( ToString(
"Result: position = <" <<
position.x << "," <<
position.y << "," <<
position.z << ">" <<
endl
) );
}
// ROTATION
else if( !fieldName.compare( "rotation" ) )
{
if( streamLength != sizeof( rotation.x ) * 4 )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( position.x ) * 4 <<
" instead of " << streamLength << "!"
) );
return false;
}
rotation.x = UnserializeFloat( stream );
rotation.y = UnserializeFloat( stream );
rotation.z = UnserializeFloat( stream );
rotation.w = UnserializeFloat( stream );
LOG( ToString(
"Result: rotation = <" <<
rotation.x << "," <<
rotation.y << "," <<
rotation.z << "," <<
rotation.w << ">" <<
endl
) );
}
// SCALE
else if( !fieldName.compare( "scale" ) )
{
if( streamLength != sizeof( scale.x ) * 3 )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( position.x ) * 3 <<
" instead of " << streamLength << "!"
) );
return false;
}
scale.x = UnserializeFloat( stream );
scale.y = UnserializeFloat( stream );
scale.z = UnserializeFloat( stream );
LOG( ToString(
"Result: scale = <" <<
scale.x << "," <<
scale.y << "," <<
scale.z << ">" <<
endl
) );
}
// No such field was found
else
{
LOG_ERROR( ToString(
"UnserializeField failed because field '" << fieldName << "' is not known!"
) );
return false;
}
return true;
}
glm::mat4 WorldNode::GetModelMatrix()
{
return modelMatrix;
}
void WorldNode::UpdateModelMatrix( WorldNode *parentPtr=nullptr )
{
// Generate the local matrix
modelMatrix = glm::translate( position ) *
glm::toMat4( rotation ) *
glm::scale( scale );
// If we have parent, take it into account
if( parentPtr )
{
modelMatrix = modelMatrix * parentPtr->GetModelMatrix();
}
// If a pointer wasn't provided, but we have an ID for the parent
else if( parent )
{
// TODO: Find the parent and apply the model matrix to it's.
}
// Update the children
std::for_each( children.begin(),
children.end(),
[this]( unsigned int &childId )
{
// Find the child
// child->UpdateModelMatrix( this );
} );
}
<commit_msg>Apparently the cast removals didn't go trough...<commit_after>#include "worldNode.hh"
#include "../logger.hh"
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include <sstream>
#include <atomic>
using namespace std;
// Static counter for the id, matters only on server
static std::atomic<unsigned int> nodeIdCounter;
// Bundling few flags to clean a bit the creation of stringstreams:
#define SS_RW_BIN std::stringstream::in | std::stringstream::out | std::stringstream::binary
WorldNode::WorldNode()
{
id = ++nodeIdCounter;
parent = 0;
position = glm::vec3( 0 );
position.y = 5;
position.z = -5;
rotation = glm::quat();
scale = glm::vec3( 1.f );
}
WorldNode::~WorldNode()
{
}
string WorldNode::Serialize( vector<string> vars )
{
// If we didn't receive any vars, serialize everything:
if( (vars.end() - vars.begin()) <= 0 )
{
vars.push_back( "id" );
vars.push_back( "position" );
vars.push_back( "rotation" );
vars.push_back( "scale" );
}
// Stream for the serialized data
stringstream dataStream( SS_RW_BIN );
// Total count of fields / member variables
unsigned char fieldCount = 0;
// For every var
for( auto e = vars.begin(); e != vars.end(); e++ )
{
if( SerializeField( *e, dataStream ) )
{
fieldCount++;
}
}
// Create the header; it's just the count of fields
stringstream headerStream( SS_RW_BIN );
SerializeUint8( headerStream, fieldCount );
// Join header and the fields and return the result
string serialized = headerStream.str();
serialized += dataStream.str();
return serialized;
}
bool WorldNode::Unserialize( string data )
{
stringstream dataStream( SS_RW_BIN );
dataStream << data;
// Field count:
uint8_t fieldCount = UnserializeUint8( dataStream );
for( int i=0; i < fieldCount; i++ )
{
// Read the byte count for this field
uint8_t fieldLength = UnserializeUint8( dataStream );
// Fetch the field name
string fieldName;
string fieldData;
if( !getline( dataStream, fieldName, ':' ) )
{
LOG_ERROR( "Error: WorldNode::Unserialize() failed to find field name!" );
break;
}
// Calculate the amount of data and allocate the buffer:
uint8_t fieldDataLength = fieldLength - fieldName.length() - 1;
assert( fieldDataLength > 0 );
char *buffer = new char[fieldLength];
// Copy the field data to other stream
stringstream fieldDataStream( SS_RW_BIN );
dataStream.read( buffer, fieldDataLength );
fieldDataStream.write( buffer, fieldDataLength );
// Free the memory for buffer
delete[] buffer;
// Unserialize and handle the field:
if( !UnserializeField( fieldName, fieldDataStream ) )
{
return false;
}
}
return false;
}
bool WorldNode::SerializeField( std::string &fieldName, std::stringstream &stream )
{
stringstream fieldStream = stringstream( SS_RW_BIN );
unsigned char fieldDataLength = 0;
string fieldDataString;
// ID
if( !fieldName.compare( "id" ) )
{
fieldStream << "id:";
SerializeUint32( fieldStream, id );
}
// POSITION
else if( !fieldName.compare( "position" ) )
{
fieldStream << "position:";
SerializeFloat( fieldStream, position.x );
SerializeFloat( fieldStream, position.y );
SerializeFloat( fieldStream, position.z );
}
// ROTATION
else if( !fieldName.compare( "rotation" ) )
{
fieldStream << "rotation:";
SerializeFloat( fieldStream, rotation.x );
SerializeFloat( fieldStream, rotation.y );
SerializeFloat( fieldStream, rotation.z );
SerializeFloat( fieldStream, rotation.w );
}
// SCALE
else if( !fieldName.compare( "scale" ) )
{
fieldStream << "scale:";
SerializeFloat( fieldStream, scale.x );
SerializeFloat( fieldStream, scale.y );
SerializeFloat( fieldStream, scale.z );
}
// No fitting field found?
else
{
LOG_ERROR( ToString(
"SerializeField failed because '" << fieldName <<
"' is not a field that it knows how to handle!"
) );
return false;
}
// Handle the fieldStream to get the
// data as a string and the length of it.
fieldDataString = fieldStream.str();
fieldDataLength = fieldDataString.length();
// Do we have anything to serialize?
assert( fieldDataLength > 0 );
// Write the header / amount of data:
SerializeUint8( stream, fieldDataLength );
// Write the data:
stream << fieldDataString;
return true;
}
bool WorldNode::UnserializeField( std::string &fieldName, std::stringstream &stream )
{
// Calculate the length
stream.seekp( 0, ios::end );
size_t streamLength = static_cast<size_t>( stream.tellp() );
stream.seekp( 0, ios::beg );
assert( streamLength > 0 );
LOG( ToString( "Got field " << fieldName << "(" << (int)streamLength << ") with value '" \
<< stream.str() << "'" ) );
// ID
if( !fieldName.compare( "id" ) )
{
if( streamLength != sizeof( unsigned int ) )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( unsigned int ) <<
" instead of " << streamLength << "!"
) );
return false;
}
id = UnserializeUint32( stream );
LOG( ToString( "Result: id = " << id << endl ) );
}
// POSITION
else if( !fieldName.compare( "position" ) )
{
if( streamLength != sizeof( position.x ) * 3 )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( position.x ) * 3 <<
" instead of " << streamLength << "!"
) );
return false;
}
position.x = UnserializeFloat( stream );
position.y = UnserializeFloat( stream );
position.z = UnserializeFloat( stream );
LOG( ToString(
"Result: position = <" <<
position.x << "," <<
position.y << "," <<
position.z << ">" <<
endl
) );
}
// ROTATION
else if( !fieldName.compare( "rotation" ) )
{
if( streamLength != sizeof( rotation.x ) * 4 )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( position.x ) * 4 <<
" instead of " << streamLength << "!"
) );
return false;
}
rotation.x = UnserializeFloat( stream );
rotation.y = UnserializeFloat( stream );
rotation.z = UnserializeFloat( stream );
rotation.w = UnserializeFloat( stream );
LOG( ToString(
"Result: rotation = <" <<
rotation.x << "," <<
rotation.y << "," <<
rotation.z << "," <<
rotation.w << ">" <<
endl
) );
}
// SCALE
else if( !fieldName.compare( "scale" ) )
{
if( streamLength != sizeof( scale.x ) * 3 )
{
LOG_ERROR( ToString(
"UnserializeField failed for " << fieldName <<
", expected data to have length " << sizeof( position.x ) * 3 <<
" instead of " << streamLength << "!"
) );
return false;
}
scale.x = UnserializeFloat( stream );
scale.y = UnserializeFloat( stream );
scale.z = UnserializeFloat( stream );
LOG( ToString(
"Result: scale = <" <<
scale.x << "," <<
scale.y << "," <<
scale.z << ">" <<
endl
) );
}
// No such field was found
else
{
LOG_ERROR( ToString(
"UnserializeField failed because field '" << fieldName << "' is not known!"
) );
return false;
}
return true;
}
glm::mat4 WorldNode::GetModelMatrix()
{
return modelMatrix;
}
void WorldNode::UpdateModelMatrix( WorldNode *parentPtr=nullptr )
{
// Generate the local matrix
modelMatrix = glm::translate( position ) *
glm::toMat4( rotation ) *
glm::scale( scale );
// If we have parent, take it into account
if( parentPtr )
{
modelMatrix = modelMatrix * parentPtr->GetModelMatrix();
}
// If a pointer wasn't provided, but we have an ID for the parent
else if( parent )
{
// TODO: Find the parent and apply the model matrix to it's.
}
// Update the children
std::for_each( children.begin(),
children.end(),
[this]( unsigned int &childId )
{
// Find the child
// child->UpdateModelMatrix( this );
} );
}
<|endoftext|> |
<commit_before>/*
* Stats.cpp
*
*/
#include <sstream>
#include "Stats.h"
#include "WebRtcConnection.h"
namespace erizo {
DEFINE_LOGGER(Stats, "Stats");
Stats::Stats(){
ELOG_DEBUG("Constructor Stats");
theListener_ = NULL;
rtpBytesReceived_ = 0;
gettimeofday(&bitRateCalculationStart_, NULL);
}
Stats::~Stats(){
ELOG_DEBUG("Destructor Stats");
}
uint32_t Stats::processRtpPacket(char* buf, int len){
rtpBytesReceived_+=len;
struct timeval now;
gettimeofday(&now, NULL);
uint64_t nowms = (now.tv_sec * 1000) + (now.tv_usec / 1000);
uint64_t start = (bitRateCalculationStart_.tv_sec * 1000) + (bitRateCalculationStart_.tv_usec / 1000);
uint64_t delay = nowms - start;
if (delay > 2000){
uint32_t receivedRtpBitrate_ = (8*rtpBytesReceived_*1000)/delay; // in kbps
rtpBytesReceived_ = 0;
gettimeofday(&bitRateCalculationStart_, NULL);
return receivedRtpBitrate_; // in bps
}
return 0;
}
void Stats::processRtcpPacket(char* buf, int length) {
boost::recursive_mutex::scoped_lock lock(mapMutex_);
char* movingBuf = buf;
int rtcpLength = 0;
int totalLength = 0;
do{
movingBuf+=rtcpLength;
RtcpHeader *chead= reinterpret_cast<RtcpHeader*>(movingBuf);
rtcpLength= (ntohs(chead->length)+1)*4;
totalLength+= rtcpLength;
this->processRtcpPacket(chead);
} while(totalLength<length);
sendStats();
}
void Stats::processRtcpPacket(RtcpHeader* chead) {
unsigned int ssrc = chead->getSSRC();
ELOG_DEBUG("RTCP SubPacket: PT %d, SSRC %u, block count %d ",chead->packettype,chead->getSSRC(), chead->getBlockCount());
switch(chead->packettype){
case RTCP_SDES_PT:
ELOG_DEBUG("SDES");
break;
case RTCP_Receiver_PT:
setFractionLost (chead->getFractionLost(), ssrc);
setPacketsLost (chead->getLostPackets(), ssrc);
setJitter (chead->getJitter(), ssrc);
setSourceSSRC(chead->getSourceSSRC(), ssrc);
break;
case RTCP_Sender_PT:
setRtcpPacketSent(chead->getPacketsSent(), ssrc);
setRtcpBytesSent(chead->getOctetsSent(), ssrc);
break;
case RTCP_RTP_Feedback_PT:
ELOG_DEBUG("RTP FB: Usually NACKs: %u", chead->getBlockCount());
ELOG_DEBUG("PID %u BLP %u", chead->getNackPid(), chead->getNackBlp());
accountNACKMessage(ssrc);
break;
case RTCP_PS_Feedback_PT:
ELOG_DEBUG("RTCP PS FB TYPE: %u", chead->getBlockCount() );
switch(chead->getBlockCount()){
case RTCP_PLI_FMT:
ELOG_DEBUG("PLI Message");
accountPLIMessage(ssrc);
break;
case RTCP_SLI_FMT:
ELOG_DEBUG("SLI Message");
accountSLIMessage(ssrc);
break;
case RTCP_FIR_FMT:
ELOG_DEBUG("FIR Message");
accountFIRMessage(ssrc);
break;
case RTCP_AFB:
{
char *uniqueId = (char*)&chead->report.rembPacket.uniqueid;
if (!strncmp(uniqueId,"REMB", 4)){
uint64_t bitrate = chead->getBrMantis() << chead->getBrExp();
// ELOG_DEBUG("REMB Packet numSSRC %u mantissa %u exp %u, tot %lu bps", chead->getREMBNumSSRC(), chead->getBrMantis(), chead->getBrExp(), bitrate);
setBandwidth(bitrate, ssrc);
}
else{
ELOG_DEBUG("Unsupported AFB Packet not REMB")
}
break;
}
default:
ELOG_WARN("Unsupported RTCP_PS FB TYPE %u",chead->getBlockCount());
break;
}
break;
default:
ELOG_DEBUG("Unknown RTCP Packet, %d", chead->packettype);
break;
}
}
std::string Stats::getStats() {
boost::recursive_mutex::scoped_lock lock(mapMutex_);
std::ostringstream theString;
theString << "[";
for (fullStatsMap_t::iterator itssrc=statsPacket_.begin(); itssrc!=statsPacket_.end();){
unsigned long int currentSSRC = itssrc->first;
theString << "{\"ssrc\":\"" << currentSSRC << "\",\n";
if (currentSSRC == videoSSRC_){
theString << "\"type\":\"" << "video\",\n";
}else if (currentSSRC == audioSSRC_){
theString << "\"type\":\"" << "audio\",\n";
}
for (singleSSRCstatsMap_t::iterator it=statsPacket_[currentSSRC].begin(); it!=statsPacket_[currentSSRC].end();){
theString << "\"" << it->first << "\":\"" << it->second << "\"";
if (++it != statsPacket_[currentSSRC].end()){
theString << ",\n";
}
}
theString << "}";
if (++itssrc != statsPacket_.end()){
theString << ",";
}
}
theString << "]";
return theString.str();
}
void Stats::sendStats() {
if(theListener_!=NULL)
theListener_->notifyStats(this->getStats());
}
}
<commit_msg>Added BYE RTCP Packet to Stats<commit_after>/*
* Stats.cpp
*
*/
#include <sstream>
#include "Stats.h"
#include "WebRtcConnection.h"
namespace erizo {
DEFINE_LOGGER(Stats, "Stats");
Stats::Stats(){
ELOG_DEBUG("Constructor Stats");
theListener_ = NULL;
rtpBytesReceived_ = 0;
gettimeofday(&bitRateCalculationStart_, NULL);
}
Stats::~Stats(){
ELOG_DEBUG("Destructor Stats");
}
uint32_t Stats::processRtpPacket(char* buf, int len){
rtpBytesReceived_+=len;
struct timeval now;
gettimeofday(&now, NULL);
uint64_t nowms = (now.tv_sec * 1000) + (now.tv_usec / 1000);
uint64_t start = (bitRateCalculationStart_.tv_sec * 1000) + (bitRateCalculationStart_.tv_usec / 1000);
uint64_t delay = nowms - start;
if (delay > 2000){
uint32_t receivedRtpBitrate_ = (8*rtpBytesReceived_*1000)/delay; // in kbps
rtpBytesReceived_ = 0;
gettimeofday(&bitRateCalculationStart_, NULL);
return receivedRtpBitrate_; // in bps
}
return 0;
}
void Stats::processRtcpPacket(char* buf, int length) {
boost::recursive_mutex::scoped_lock lock(mapMutex_);
char* movingBuf = buf;
int rtcpLength = 0;
int totalLength = 0;
do{
movingBuf+=rtcpLength;
RtcpHeader *chead= reinterpret_cast<RtcpHeader*>(movingBuf);
rtcpLength= (ntohs(chead->length)+1)*4;
totalLength+= rtcpLength;
this->processRtcpPacket(chead);
} while(totalLength<length);
sendStats();
}
void Stats::processRtcpPacket(RtcpHeader* chead) {
unsigned int ssrc = chead->getSSRC();
ELOG_DEBUG("RTCP SubPacket: PT %d, SSRC %u, block count %d ",chead->packettype,chead->getSSRC(), chead->getBlockCount());
switch(chead->packettype){
case RTCP_SDES_PT:
ELOG_DEBUG("SDES");
break;
case RTCP_BYE:
ELOG_DEBUG("RTCP BYE");
break;
case RTCP_Receiver_PT:
setFractionLost (chead->getFractionLost(), ssrc);
setPacketsLost (chead->getLostPackets(), ssrc);
setJitter (chead->getJitter(), ssrc);
setSourceSSRC(chead->getSourceSSRC(), ssrc);
break;
case RTCP_Sender_PT:
setRtcpPacketSent(chead->getPacketsSent(), ssrc);
setRtcpBytesSent(chead->getOctetsSent(), ssrc);
break;
case RTCP_RTP_Feedback_PT:
ELOG_DEBUG("RTP FB: Usually NACKs: %u", chead->getBlockCount());
ELOG_DEBUG("PID %u BLP %u", chead->getNackPid(), chead->getNackBlp());
accountNACKMessage(ssrc);
break;
case RTCP_PS_Feedback_PT:
ELOG_DEBUG("RTCP PS FB TYPE: %u", chead->getBlockCount() );
switch(chead->getBlockCount()){
case RTCP_PLI_FMT:
ELOG_DEBUG("PLI Message");
accountPLIMessage(ssrc);
break;
case RTCP_SLI_FMT:
ELOG_DEBUG("SLI Message");
accountSLIMessage(ssrc);
break;
case RTCP_FIR_FMT:
ELOG_DEBUG("FIR Message");
accountFIRMessage(ssrc);
break;
case RTCP_AFB:
{
char *uniqueId = (char*)&chead->report.rembPacket.uniqueid;
if (!strncmp(uniqueId,"REMB", 4)){
uint64_t bitrate = chead->getBrMantis() << chead->getBrExp();
// ELOG_DEBUG("REMB Packet numSSRC %u mantissa %u exp %u, tot %lu bps", chead->getREMBNumSSRC(), chead->getBrMantis(), chead->getBrExp(), bitrate);
setBandwidth(bitrate, ssrc);
}
else{
ELOG_DEBUG("Unsupported AFB Packet not REMB")
}
break;
}
default:
ELOG_WARN("Unsupported RTCP_PS FB TYPE %u",chead->getBlockCount());
break;
}
break;
default:
ELOG_DEBUG("Unknown RTCP Packet, %d", chead->packettype);
break;
}
}
std::string Stats::getStats() {
boost::recursive_mutex::scoped_lock lock(mapMutex_);
std::ostringstream theString;
theString << "[";
for (fullStatsMap_t::iterator itssrc=statsPacket_.begin(); itssrc!=statsPacket_.end();){
unsigned long int currentSSRC = itssrc->first;
theString << "{\"ssrc\":\"" << currentSSRC << "\",\n";
if (currentSSRC == videoSSRC_){
theString << "\"type\":\"" << "video\",\n";
}else if (currentSSRC == audioSSRC_){
theString << "\"type\":\"" << "audio\",\n";
}
for (singleSSRCstatsMap_t::iterator it=statsPacket_[currentSSRC].begin(); it!=statsPacket_[currentSSRC].end();){
theString << "\"" << it->first << "\":\"" << it->second << "\"";
if (++it != statsPacket_[currentSSRC].end()){
theString << ",\n";
}
}
theString << "}";
if (++itssrc != statsPacket_.end()){
theString << ",";
}
}
theString << "]";
return theString.str();
}
void Stats::sendStats() {
if(theListener_!=NULL)
theListener_->notifyStats(this->getStats());
}
}
<|endoftext|> |
<commit_before>#define CDM_CONFIGURE_NAMESPACE a0038876
#include "../../cdm/application/using_boost/cdm.hpp"
#include "log.hpp"
#include "boost_root.hpp"
#include <boost/test/unit_test.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <silicium/file_operations.hpp>
#include <cdm/locate_cache.hpp>
namespace
{
Si::absolute_path const this_file = *Si::absolute_path::create(__FILE__);
Si::absolute_path const test = *Si::parent(this_file);
Si::absolute_path const repository = *Si::parent(test);
}
BOOST_AUTO_TEST_CASE(test_using_boost)
{
Si::absolute_path const app_source = repository / Si::relative_path("application/using_boost");
Si::absolute_path const tmp = Si::temporary_directory(Si::throw_) / *Si::path_segment::create("cdm_b");
Si::recreate_directories(tmp, Si::throw_);
Si::absolute_path const module_temporaries = tmp / *Si::path_segment::create("build");
Si::create_directories(module_temporaries, Si::throw_);
Si::absolute_path const application_build_dir = tmp / *Si::path_segment::create("app_build");
Si::create_directories(application_build_dir, Si::throw_);
auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(std::cerr));
cdm::configure_result const configured = CDM_CONFIGURE_NAMESPACE::configure(module_temporaries, cdm::locate_cache(), app_source, application_build_dir, cdm::get_boost_root_for_testing(), output);
{
std::vector<Si::os_string> arguments;
arguments.push_back(SILICIUM_SYSTEM_LITERAL("--build"));
arguments.push_back(SILICIUM_SYSTEM_LITERAL("."));
BOOST_REQUIRE_EQUAL(0, Si::run_process(Si::cmake_exe, arguments, application_build_dir, output));
}
{
std::vector<Si::os_string> arguments;
Si::relative_path const relative(
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL("Debug/")
#endif
SILICIUM_SYSTEM_LITERAL("using_boost")
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL(".exe")
#endif
);
std::vector<std::pair<Si::os_char const *, Si::os_char const *>> environment;
#ifndef _WIN32
Si::os_string library_paths;
for (Si::absolute_path const &path : configured.shared_library_directories)
{
if (!library_paths.empty())
{
library_paths += ";";
}
library_paths += path.c_str();
}
environment.emplace_back("LD_LIBRARY_PATH", library_paths.c_str());
#endif
BOOST_REQUIRE_EQUAL(0, Si::run_process(
application_build_dir / relative,
arguments,
application_build_dir,
output,
environment,
Si::environment_inheritance::inherit
));
}
}
<commit_msg>use colon as the correct separator for LD_LIBRARY_PATH<commit_after>#define CDM_CONFIGURE_NAMESPACE a0038876
#include "../../cdm/application/using_boost/cdm.hpp"
#include "log.hpp"
#include "boost_root.hpp"
#include <boost/test/unit_test.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <silicium/file_operations.hpp>
#include <cdm/locate_cache.hpp>
namespace
{
Si::absolute_path const this_file = *Si::absolute_path::create(__FILE__);
Si::absolute_path const test = *Si::parent(this_file);
Si::absolute_path const repository = *Si::parent(test);
}
BOOST_AUTO_TEST_CASE(test_using_boost)
{
Si::absolute_path const app_source = repository / Si::relative_path("application/using_boost");
Si::absolute_path const tmp = Si::temporary_directory(Si::throw_) / *Si::path_segment::create("cdm_b");
Si::recreate_directories(tmp, Si::throw_);
Si::absolute_path const module_temporaries = tmp / *Si::path_segment::create("build");
Si::create_directories(module_temporaries, Si::throw_);
Si::absolute_path const application_build_dir = tmp / *Si::path_segment::create("app_build");
Si::create_directories(application_build_dir, Si::throw_);
auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(std::cerr));
cdm::configure_result const configured = CDM_CONFIGURE_NAMESPACE::configure(module_temporaries, cdm::locate_cache(), app_source, application_build_dir, cdm::get_boost_root_for_testing(), output);
{
std::vector<Si::os_string> arguments;
arguments.push_back(SILICIUM_SYSTEM_LITERAL("--build"));
arguments.push_back(SILICIUM_SYSTEM_LITERAL("."));
BOOST_REQUIRE_EQUAL(0, Si::run_process(Si::cmake_exe, arguments, application_build_dir, output));
}
{
std::vector<Si::os_string> arguments;
Si::relative_path const relative(
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL("Debug/")
#endif
SILICIUM_SYSTEM_LITERAL("using_boost")
#ifdef _MSC_VER
SILICIUM_SYSTEM_LITERAL(".exe")
#endif
);
std::vector<std::pair<Si::os_char const *, Si::os_char const *>> environment;
#ifndef _WIN32
Si::os_string library_paths;
for (Si::absolute_path const &path : configured.shared_library_directories)
{
if (!library_paths.empty())
{
library_paths += ":";
}
library_paths += path.c_str();
}
environment.emplace_back("LD_LIBRARY_PATH", library_paths.c_str());
#endif
BOOST_REQUIRE_EQUAL(0, Si::run_process(
application_build_dir / relative,
arguments,
application_build_dir,
output,
environment,
Si::environment_inheritance::inherit
));
}
}
<|endoftext|> |
<commit_before>#include "fileinfo.hpp"
#include "fileinfo_service.hpp"
namespace x0 {
fileinfo::fileinfo(fileinfo_service& service, const std::string& filename) :
service_(service),
watcher_(service.loop_),
filename_(filename),
exists_(),
etag_(service_.make_etag(*this)),
mtime_(),
mimetype_(service_.get_mimetype(filename_))
{
watcher_.set<fileinfo, &fileinfo::callback>(this);
watcher_.set(filename_.c_str());
watcher_.start();
exists_ = watcher_.attr.st_nlink > 0;
}
void fileinfo::callback(ev::stat& w, int revents)
{
data_.clear();
etag_ = service_.make_etag(*this);
mimetype_ = service_.get_mimetype(filename_);
}
} // namespace x0
<commit_msg>fixed bug where mtime-cache did not get cleared/updated when file changed<commit_after>#include "fileinfo.hpp"
#include "fileinfo_service.hpp"
namespace x0 {
fileinfo::fileinfo(fileinfo_service& service, const std::string& filename) :
service_(service),
watcher_(service.loop_),
filename_(filename),
exists_(),
etag_(service_.make_etag(*this)),
mtime_(),
mimetype_(service_.get_mimetype(filename_))
{
watcher_.set<fileinfo, &fileinfo::callback>(this);
watcher_.set(filename_.c_str());
watcher_.start();
exists_ = watcher_.attr.st_nlink > 0;
}
void fileinfo::callback(ev::stat& w, int revents)
{
data_.clear();
etag_ = service_.make_etag(*this);
mtime_.clear(); // gets computed on-demand
mimetype_ = service_.get_mimetype(filename_);
}
} // namespace x0
<|endoftext|> |
<commit_before>// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <zippylog/client.hpp>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <zmq.hpp>
#include <iostream>
using namespace zippylog;
using ::zmq::context_t;
using namespace ::std;
int main(int argc, const char * const argv[])
{
context_t zctx(1);
//client::Client c(&zctx, "tcp://192.168.1.69:52483");
client::Client c(&zctx, "tcp://localhost:5000");
int i = 0;
::google::protobuf::TextFormat::Printer printer = ::google::protobuf::TextFormat::Printer();
::google::protobuf::io::FileOutputStream os(1, -1);
return 0;
}
<commit_msg>basic functionality implementation<commit_after>// Copyright 2010 Gregory Szorc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <zippylog/client.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using ::std::cout;
using ::std::endl;
using ::std::ostringstream;
using ::std::string;
using ::std::vector;
using ::zippylog::client::Client;
using ::zippylog::protocol::StoreInfo;
using ::zippylog::Exception;
class ZippylogclientParams {
public:
ZippylogclientParams() :
store_info(false)
{ }
bool store_info;
vector<string> servers;
};
static bool ParseCommandArguments(
vector<string> args,
ZippylogclientParams ¶ms,
string &error)
{
if (args.size() < 2) {
ostringstream usage;
usage
<< "zippylogclient - A client for zippylog servers" << endl
<< endl
<< "Usage: zippylogclient [options] server0 [server1 ... serverN]" << endl
<< endl
<< "The program is invoked with arguments pointing to 1 or more zippylog servers" << endl
<< "zippylog servers along with optional arguments that control behavior." << endl
<< endl
<< "SERVER ARGUMENTS" << endl
<< endl
<< "The server arguments are 0MQ endpoints/URIs of zippylog server agents." << endl
<< "e.g. tcp://myhost.mydomain:52483 or ipc:///tmp/zippylogd" << endl
<< endl
<< "PROGRAM OPTIONS" << endl
<< endl
<< "The following program options control behavior:" << endl
<< endl
<< " --storeinfo Obtain the store info and exit" << endl
;
error = usage.str();
return false;
}
// get rid of first element, the program name
args.erase(args.begin());
for (int i = 0; i < args.size(); i++) {
string arg = args[i];
if (arg == "--storeinfo") {
params.store_info = true;
}
else if (arg[0] != '-') {
params.servers.push_back(arg);
}
}
return true;
}
int ShowStoreInfo(vector<Client *> &clients)
{
for (vector<Client *>::iterator itor = clients.begin(); itor != clients.end(); itor++) {
StoreInfo si;
if ((*itor)->StoreInfo(si, 10000000)) {
cout << si.DebugString() << endl;
}
}
return 0;
}
int main(int argc, const char * const argv[])
{
try {
::zippylog::initialize_library();
vector<string> args;
for (int i = 0; i < argc; i++) {
args.push_back(argv[i]);
}
string error;
ZippylogclientParams params;
if (!ParseCommandArguments(args, params, error)) {
cout << error << endl;
return 1;
}
vector<Client *> clients;
::zmq::context_t ctx(2);
for (size_t i = 0; i < params.servers.size(); i++) {
clients.push_back(new Client(&ctx, params.servers[i]));
}
int result;
if (params.store_info) {
result = ShowStoreInfo(clients);
}
else {
cout << "Not sure what to do!" << endl;
return 1;
}
for (vector<Client *>::iterator itor = clients.begin(); itor != clients.end(); itor++) {
delete *itor;
}
clients.clear();
::zippylog::shutdown_library();
}
catch (Exception e) {
cout << "zippylog Exception:" << endl;
cout << e.what() << endl;
return 1;
}
catch (string s) {
cout << "Exception:" << endl;
cout << s;
return 1;
}
catch (char * s) {
cout << "Exception: " << s << endl;
return 1;
}
catch (...) {
cout << "received an exception" << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "SUIT_ViewManager.h"
#include "SUIT_Desktop.h"
#include "SUIT_ViewModel.h"
#include "SUIT_Study.h"
#include <qcursor.h>
#include <qmessagebox.h>
#ifdef WNT
#include <windows.h>
#endif
//***************************************************************
SUIT_ViewManager::SUIT_ViewManager( SUIT_Study* theStudy,
SUIT_Desktop* theDesktop,
SUIT_ViewModel* theViewModel )
: QObject( 0 ),
myDesktop( theDesktop ),
myTitle( "Default viewer" ),
myStudy( NULL )
{
myViewModel = 0;
myActiveView = 0;
setViewModel(theViewModel);
connect(theDesktop, SIGNAL(windowActivated(SUIT_ViewWindow*)),
this, SLOT(onWindowActivated(SUIT_ViewWindow*)));
myStudy = theStudy;
if( myStudy )
connect( myStudy, SIGNAL( destroyed() ), this, SLOT( onDeleteStudy() ) );
}
//***************************************************************
SUIT_ViewManager::~SUIT_ViewManager()
{
if (myViewModel) {
myViewModel->setViewManager(0);
delete myViewModel;
}
}
//***************************************************************
void SUIT_ViewManager::setViewModel(SUIT_ViewModel* theViewModel)
{
if (myViewModel && myViewModel != theViewModel) {
myViewModel->setViewManager(0);
delete myViewModel;
}
myViewModel = theViewModel;
if (myViewModel)
myViewModel->setViewManager(this);
}
//***************************************************************
void SUIT_ViewManager::setViewName(SUIT_ViewWindow* theView)
{
int aPos = myViews.find(theView);
theView->setCaption(myTitle + QString(":%1").arg(aPos+1));
}
//***************************************************************
SUIT_ViewWindow* SUIT_ViewManager::createViewWindow()
{
SUIT_ViewWindow* aView = myViewModel->createView(myDesktop);
if ( !insertView( aView ) )
delete aView;
setViewName( aView );
//myDesktop->addViewWindow( aView );
//it is done automatically during creation of view
aView->setViewManager(this);
emit viewCreated(aView);
return aView;
}
//***************************************************************
void SUIT_ViewManager::createView()
{
createViewWindow();
}
//***************************************************************
bool SUIT_ViewManager::insertView(SUIT_ViewWindow* theView)
{
unsigned int aSize = myViews.size();
unsigned int aNbItems = myViews.count()+1;
if (aNbItems > aSize) {
if (!myViews.resize(aNbItems)) {
QMessageBox::critical(myDesktop, tr("Critical error"), tr("There is no memory for the new view!!!"));
return false;
}
aSize = myViews.size();
}
connect(theView, SIGNAL(closing(SUIT_ViewWindow*)),
this, SLOT(onDeleteView(SUIT_ViewWindow*)));
connect(theView, SIGNAL(mousePressed(SUIT_ViewWindow*, QMouseEvent*)),
this, SLOT(onMousePressed(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(mouseReleased(SUIT_ViewWindow*, QMouseEvent*)),
this, SIGNAL(mouseRelease(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(mouseDoubleClicked(SUIT_ViewWindow*, QMouseEvent*)),
this, SIGNAL(mouseDoubleClick(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(mouseMoving(SUIT_ViewWindow*, QMouseEvent*)),
this, SIGNAL(mouseMove(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(wheeling(SUIT_ViewWindow*, QWheelEvent*)),
this, SIGNAL(wheel(SUIT_ViewWindow*, QWheelEvent*)));
connect(theView, SIGNAL(keyPressed(SUIT_ViewWindow*, QKeyEvent*)),
this, SIGNAL(keyPress(SUIT_ViewWindow*, QKeyEvent*)));
connect(theView, SIGNAL(keyReleased(SUIT_ViewWindow*, QKeyEvent*)),
this, SIGNAL(keyRelease(SUIT_ViewWindow*, QKeyEvent*)));
connect(theView, SIGNAL(contextMenuRequested( QContextMenuEvent * )),
this, SLOT (onContextMenuRequested( QContextMenuEvent * )));
for (uint i = 0; i < aSize; i++) {
if (myViews[i]==0) {
myViews.insert(i, theView);
return true;
}
}
return false;
}
//***************************************************************
void SUIT_ViewManager::onDeleteView(SUIT_ViewWindow* theView)
{
emit deleteView(theView);
removeView(theView);
}
//***************************************************************
void SUIT_ViewManager::removeView(SUIT_ViewWindow* theView)
{
theView->disconnect(this);
myViews.remove(myViews.find(theView));
if (myActiveView == theView)
myActiveView = 0;
int aNumItems = myViews.count();
if (aNumItems == 0)
emit lastViewClosed(this);
}
//***************************************************************
void SUIT_ViewManager::onMousePressed(SUIT_ViewWindow* theView, QMouseEvent* theEvent)
{
emit mousePress(theView, theEvent);
}
//***************************************************************
void SUIT_ViewManager::onWindowActivated(SUIT_ViewWindow* view)
{
if (view) {
unsigned int aSize = myViews.size();
for (uint i = 0; i < aSize; i++) {
if (myViews[i] && myViews[i] == view) {
myActiveView = view;
emit activated( this );
return;
}
}
}
}
//***************************************************************
void SUIT_ViewManager::closeAllViews()
{
unsigned int aSize = myViews.size();
for (uint i = 0; i < aSize; i++) {
if (myViews[i])
myViews[i]->close();
}
}
//***************************************************************
QString SUIT_ViewManager::getType() const
{
return (!myViewModel)? "": myViewModel->getType();
}
//***************************************************************
SUIT_Study* SUIT_ViewManager::study() const
{
return myStudy;
}
//***************************************************************
void SUIT_ViewManager::onDeleteStudy()
{
myStudy = NULL;
}
//***************************************************************
void SUIT_ViewManager::onContextMenuRequested( QContextMenuEvent* e )
{
// invoke method of SUIT_PopupClient, which notifies about popup
contextMenuRequest( e );
}
//***************************************************************
void SUIT_ViewManager::contextMenuPopup( QPopupMenu* popup )
{
SUIT_ViewModel* vm = getViewModel();
if ( vm )
vm->contextMenuPopup( popup );
}
<commit_msg>createView() improvement<commit_after>#include "SUIT_ViewManager.h"
#include "SUIT_Desktop.h"
#include "SUIT_ViewModel.h"
#include "SUIT_Study.h"
#include <qcursor.h>
#include <qmessagebox.h>
#ifdef WNT
#include <windows.h>
#endif
//***************************************************************
SUIT_ViewManager::SUIT_ViewManager( SUIT_Study* theStudy,
SUIT_Desktop* theDesktop,
SUIT_ViewModel* theViewModel )
: QObject( 0 ),
myDesktop( theDesktop ),
myTitle( "Default viewer" ),
myStudy( NULL )
{
myViewModel = 0;
myActiveView = 0;
setViewModel(theViewModel);
connect(theDesktop, SIGNAL(windowActivated(SUIT_ViewWindow*)),
this, SLOT(onWindowActivated(SUIT_ViewWindow*)));
myStudy = theStudy;
if( myStudy )
connect( myStudy, SIGNAL( destroyed() ), this, SLOT( onDeleteStudy() ) );
}
//***************************************************************
SUIT_ViewManager::~SUIT_ViewManager()
{
if (myViewModel) {
myViewModel->setViewManager(0);
delete myViewModel;
}
}
//***************************************************************
void SUIT_ViewManager::setViewModel(SUIT_ViewModel* theViewModel)
{
if (myViewModel && myViewModel != theViewModel) {
myViewModel->setViewManager(0);
delete myViewModel;
}
myViewModel = theViewModel;
if (myViewModel)
myViewModel->setViewManager(this);
}
//***************************************************************
void SUIT_ViewManager::setViewName(SUIT_ViewWindow* theView)
{
int aPos = myViews.find(theView);
theView->setCaption(myTitle + QString(":%1").arg(aPos+1));
}
//***************************************************************
SUIT_ViewWindow* SUIT_ViewManager::createViewWindow()
{
SUIT_ViewWindow* aView = myViewModel->createView(myDesktop);
if ( !insertView( aView ) ){
delete aView;
return 0;
}
setViewName( aView );
//myDesktop->addViewWindow( aView );
//it is done automatically during creation of view
aView->setViewManager(this);
emit viewCreated(aView);
// Special treatment for the case when <aView> is the first one in this view manager
// -> call onWindowActivated() directly, because somebody may always want
// to use getActiveView()
if ( !myActiveView )
onWindowActivated( aView );
return aView;
}
//***************************************************************
void SUIT_ViewManager::createView()
{
createViewWindow();
}
//***************************************************************
bool SUIT_ViewManager::insertView(SUIT_ViewWindow* theView)
{
unsigned int aSize = myViews.size();
unsigned int aNbItems = myViews.count()+1;
if (aNbItems > aSize) {
if (!myViews.resize(aNbItems)) {
QMessageBox::critical(myDesktop, tr("Critical error"), tr("There is no memory for the new view!!!"));
return false;
}
aSize = myViews.size();
}
connect(theView, SIGNAL(closing(SUIT_ViewWindow*)),
this, SLOT(onDeleteView(SUIT_ViewWindow*)));
connect(theView, SIGNAL(mousePressed(SUIT_ViewWindow*, QMouseEvent*)),
this, SLOT(onMousePressed(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(mouseReleased(SUIT_ViewWindow*, QMouseEvent*)),
this, SIGNAL(mouseRelease(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(mouseDoubleClicked(SUIT_ViewWindow*, QMouseEvent*)),
this, SIGNAL(mouseDoubleClick(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(mouseMoving(SUIT_ViewWindow*, QMouseEvent*)),
this, SIGNAL(mouseMove(SUIT_ViewWindow*, QMouseEvent*)));
connect(theView, SIGNAL(wheeling(SUIT_ViewWindow*, QWheelEvent*)),
this, SIGNAL(wheel(SUIT_ViewWindow*, QWheelEvent*)));
connect(theView, SIGNAL(keyPressed(SUIT_ViewWindow*, QKeyEvent*)),
this, SIGNAL(keyPress(SUIT_ViewWindow*, QKeyEvent*)));
connect(theView, SIGNAL(keyReleased(SUIT_ViewWindow*, QKeyEvent*)),
this, SIGNAL(keyRelease(SUIT_ViewWindow*, QKeyEvent*)));
connect(theView, SIGNAL(contextMenuRequested( QContextMenuEvent * )),
this, SLOT (onContextMenuRequested( QContextMenuEvent * )));
for (uint i = 0; i < aSize; i++) {
if (myViews[i]==0) {
myViews.insert(i, theView);
return true;
}
}
return false;
}
//***************************************************************
void SUIT_ViewManager::onDeleteView(SUIT_ViewWindow* theView)
{
emit deleteView(theView);
removeView(theView);
}
//***************************************************************
void SUIT_ViewManager::removeView(SUIT_ViewWindow* theView)
{
theView->disconnect(this);
myViews.remove(myViews.find(theView));
if (myActiveView == theView)
myActiveView = 0;
int aNumItems = myViews.count();
if (aNumItems == 0)
emit lastViewClosed(this);
}
//***************************************************************
void SUIT_ViewManager::onMousePressed(SUIT_ViewWindow* theView, QMouseEvent* theEvent)
{
emit mousePress(theView, theEvent);
}
//***************************************************************
void SUIT_ViewManager::onWindowActivated(SUIT_ViewWindow* view)
{
if (view && myActiveView != view) {
unsigned int aSize = myViews.size();
for (uint i = 0; i < aSize; i++) {
if (myViews[i] && myViews[i] == view) {
myActiveView = view;
emit activated( this );
return;
}
}
}
}
//***************************************************************
void SUIT_ViewManager::closeAllViews()
{
unsigned int aSize = myViews.size();
for (uint i = 0; i < aSize; i++) {
if (myViews[i])
myViews[i]->close();
}
}
//***************************************************************
QString SUIT_ViewManager::getType() const
{
return (!myViewModel)? "": myViewModel->getType();
}
//***************************************************************
SUIT_Study* SUIT_ViewManager::study() const
{
return myStudy;
}
//***************************************************************
void SUIT_ViewManager::onDeleteStudy()
{
myStudy = NULL;
}
//***************************************************************
void SUIT_ViewManager::onContextMenuRequested( QContextMenuEvent* e )
{
// invoke method of SUIT_PopupClient, which notifies about popup
contextMenuRequest( e );
}
//***************************************************************
void SUIT_ViewManager::contextMenuPopup( QPopupMenu* popup )
{
SUIT_ViewModel* vm = getViewModel();
if ( vm )
vm->contextMenuPopup( popup );
}
<|endoftext|> |
<commit_before>/*
* Super simple Spatialization object for Jamoma DSP
* Copyright © 2011 by Trond Lossius, Nils Peters, and Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "SpatLib.h"
#include "SpatThru.h"
TTErr SpatThru::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
int badSampleCount = 0;
TTAudioSignalArrayPtr input;
TTAudioSignalArrayPtr output;
int N = 32;
input->setMaxNumAudioSignals(4);
input->allocAllWithVectorSize(N);
// create single audio signal buffer
TTAudioSignalPtr buffer = NULL;
TTObjectInstantiate(kTTSym_audiosignal, &buffer, 1);
buffer->allocWithVectorSize(N);
// filling the channels with prime number values
// as this will quickly reveal if something is wrong
buffer->fill(2.0);
input->setSignal(0, buffer);
buffer->fill(-3.0);
input->setSignal(1, buffer);
buffer->fill(5.0);
input->setSignal(2, buffer);
buffer->fill(7.0);
input->setSignal(3, buffer);
// process
//this->processAudio(input, output);
// Wrap up the test results to pass back to whoever called this test
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<commit_msg>Adding test for thru. This is currently failing<commit_after>/*
* Super simple Spatialization object for Jamoma DSP
* Copyright © 2011 by Trond Lossius, Nils Peters, and Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "SpatLib.h"
#include "SpatThru.h"
TTErr SpatThru::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
TTAudioSignalPtr input = NULL;
TTAudioSignalPtr output = NULL;
// create four channel audio signals
TTObjectInstantiate(kTTSym_audiosignal, &input, 4);
TTObjectInstantiate(kTTSym_audiosignal, &output, 4);
input->allocWithVectorSize(64);
output->allocWithVectorSize(64);
// Fill signals on all four channels with noise
for (int i=0; i<64; i++) {
input->mSampleVectors[0][i] = TTRandom64();
input->mSampleVectors[1][i] = TTRandom64();
input->mSampleVectors[2][i] = TTRandom64();
input->mSampleVectors[3][i] = TTRandom64();
}
// process
this->process(input, output);
// check returned samples at all channels
int validSampleCount = 0;
for (int channel=0; channel<4; channel++) {
TTSampleValuePtr inSamples = input->mSampleVectors[channel];
TTSampleValuePtr outSamples = output->mSampleVectors[channel];
for (int i=0; i<64; i++) {
validSampleCount += TTTestFloatEquivalence(inSamples[i], outSamples[i]);
}
}
TTTestAssertion("input samples accurately copied to output samples",
validSampleCount == 256, // 64 * 4 channels
testAssertionCount,
errorCount);
TTTestLog("Number of bad samples: %i", 256-validSampleCount);
TTObjectRelease(&input);
TTObjectRelease(&output);
// Wrap up the test results to pass back to whoever called this test
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<|endoftext|> |
<commit_before>/*
* TangentRotationReader.cpp
*
* Created on: Feb 21, 2013
* Author: link
*/
#include "TangentRotationReader.hpp"
#include "ImageEdgeFilter.hpp"
#include "DrawingFunctions.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
TangentRotationReader::TangentRotationReader(
const FeatureTracker &tracker,
const FeatureExtractor &extractor,
const std::list<FeatureFilter*> &filters,
const unsigned int &maxFeatures, const double &focalLength,
const cv::Size& imageSize, const double &margin,
const std::vector<std::list<cv::Point2f> > &trackedFeatures) :
RotationReader(tracker, extractor, filters, maxFeatures,
trackedFeatures), _focalLength(focalLength), _imageSize(
imageSize) {
_filters.push_front(
new ImageEdgeFilter(cv::Mat::eye(cv::Size(3, 3), CV_32F),
_imageSize, margin));
}
TangentRotationReader::~TangentRotationReader() {
}
TangentRotationReader::TangentRotationReader(
const TangentRotationReader &toCopy) :
RotationReader(toCopy), _focalLength(toCopy._focalLength), _imageSize(
toCopy._imageSize) {
}
RotationReader *TangentRotationReader::constructCopy() const {
return new TangentRotationReader(*this);
}
float TangentRotationReader::readRotation(const cv::Mat &newFrame) {
float result = 0;
if (!_oldFrame.empty()) {
_extractor->refillFeatures(_oldFrame, _trackedFeatures,
_maxFeatures);
if (!_trackedFeatures.empty()) {
_tracker->trackFeatures(_oldFrame, newFrame,
_trackedFeatures);
if (!_trackedFeatures.empty()) {
for (std::list<FeatureFilter*>::iterator it =
_filters.begin(); it != _filters.end();
++it) {
_trackedFeatures = (*it)->filterFeatures(
_trackedFeatures);
}
// cv::Mat shown = newFrame.clone();
// drawFeatureHistory(shown, _trackedFeatures, 5);
// cv::imshow("tangent", shown);
// cv::waitKey(1);
if (!_trackedFeatures.empty()) {
std::vector<float> rotations =
computeRotationVectors();
int vectorHalf = rotations.size() / 2;
std::nth_element(rotations.begin(),
rotations.begin() + vectorHalf,
rotations.end());
result = rotations[vectorHalf];
}
}
}
}
_oldFrame = newFrame.clone();
return result;
}
std::vector<float> TangentRotationReader::computeRotationVectors() {
std::vector<cv::Point2f> oldFeatures(_trackedFeatures.size()),
newFeatures(_trackedFeatures.size());
std::vector<float> result(oldFeatures.size());
for (unsigned int i = 0; i < result.size(); ++i) {
std::list<cv::Point2f>::const_iterator it =
_trackedFeatures[i].begin();
if (_trackedFeatures[i].size() > 2) {
result[i] = atan2(it->x - _oldFrame.cols / 2,
_focalLength);
++it;
result[i] -= atan2(it->x - _oldFrame.cols / 2,
_focalLength);
}
}
return result;
}
<commit_msg>Clean up TangentRotationReader<commit_after>/*
* TangentRotationReader.cpp
*
* Created on: Feb 21, 2013
* Author: link
*/
#include "TangentRotationReader.hpp"
#include "ImageEdgeFilter.hpp"
TangentRotationReader::TangentRotationReader(
const FeatureTracker &tracker,
const FeatureExtractor &extractor,
const std::list<FeatureFilter*> &filters,
const unsigned int &maxFeatures, const double &focalLength,
const cv::Size& imageSize, const double &margin,
const std::vector<std::list<cv::Point2f> > &trackedFeatures) :
RotationReader(tracker, extractor, filters, maxFeatures,
trackedFeatures), _focalLength(focalLength), _imageSize(
imageSize) {
_filters.push_front(
new ImageEdgeFilter(cv::Mat::eye(cv::Size(3, 3), CV_32F),
_imageSize, margin));
}
TangentRotationReader::~TangentRotationReader() {
}
TangentRotationReader::TangentRotationReader(
const TangentRotationReader &toCopy) :
RotationReader(toCopy), _focalLength(toCopy._focalLength), _imageSize(
toCopy._imageSize) {
}
RotationReader *TangentRotationReader::constructCopy() const {
return new TangentRotationReader(*this);
}
float TangentRotationReader::readRotation(const cv::Mat &newFrame) {
float result = 0;
if (!_oldFrame.empty()) {
_extractor->refillFeatures(_oldFrame, _trackedFeatures,
_maxFeatures);
if (!_trackedFeatures.empty()) {
_tracker->trackFeatures(_oldFrame, newFrame,
_trackedFeatures);
if (!_trackedFeatures.empty()) {
for (std::list<FeatureFilter*>::iterator it =
_filters.begin(); it != _filters.end();
++it) {
_trackedFeatures = (*it)->filterFeatures(
_trackedFeatures);
}
if (!_trackedFeatures.empty()) {
std::vector<float> rotations =
computeRotationVectors();
int vectorHalf = rotations.size() / 2;
std::nth_element(rotations.begin(),
rotations.begin() + vectorHalf,
rotations.end());
result = rotations[vectorHalf];
}
}
}
}
_oldFrame = newFrame.clone();
return result;
}
std::vector<float> TangentRotationReader::computeRotationVectors() {
std::vector<cv::Point2f> oldFeatures(_trackedFeatures.size()),
newFeatures(_trackedFeatures.size());
std::vector<float> result(oldFeatures.size());
for (unsigned int i = 0; i < result.size(); ++i) {
std::list<cv::Point2f>::const_iterator it =
_trackedFeatures[i].begin();
if (_trackedFeatures[i].size() > 2) {
result[i] = atan2(it->x - _oldFrame.cols / 2,
_focalLength);
++it;
result[i] -= atan2(it->x - _oldFrame.cols / 2,
_focalLength);
}
}
return result;
}
<|endoftext|> |
<commit_before>#include "include/bp.h"
#include <cmath>
namespace ginf {
// Sum up messages sent to a node by its neighbours
template <typename T>
void bpCollect(Grid<T> *grid, Matrix<T> *msgs, Matrix<T> *from, int x, int y) {
// For each label
for (int i = 0; i < grid->getNumLabels(); i++) {
from->get(x, y, i) = 0;
// For each neighbour, add up the messages for this particular label
for (int d = 0; d < GINF_NUM_DIR; d++) {
from->get(x, y, i) += msgs->at(x + dirX[d], y + dirY[d], GINF_OPP_DIR(d), i);
}
}
}
// Send a message in a particular direction
template <typename T>
void bpSendMsg(Grid<T> *grid, Matrix<T> *msgs, Matrix<T> *from, Matrix<T> *dataCosts, T *out, int x, int y, int d) {
// Get the coordinate of the neighbour
int nx = x + dirX[d], ny = y + dirY[d];
if (grid->getSmModel() == GINF_SM_TRUNC_LINEAR) {
// We can apply an optimization to calculate the message in O(L), where L is the number of labels
T minh = out[0] = dataCosts->at(x, y, 0) + (from->at(x, y, 0) - msgs->at(nx, ny, GINF_OPP_DIR(d), 0));
for (int i = 1; i < grid->getNumLabels(); i++) {
out[i] = dataCosts->at(x, y, i) + (from->at(x, y, i) - msgs->at(nx, ny, GINF_OPP_DIR(d), i));
minh = GINF_MIN(minh, out[i]);
}
// Find the linear scaling constant
T scale = grid->getSmoothnessCost(0, 1);
for (int i = 1; i < grid->getNumLabels(); i++)
out[i] = GINF_MIN(out[i], out[i - 1] + scale);
for (int i = grid->getNumLabels() - 2; i >= 0; i--)
out[i] = GINF_MIN(out[i], out[i + 1] + scale);
// Truncate the messages using truncate constant
minh += GINF_MIN(grid->getSmoothnessCost(0, 1) * grid->getNumLabels(),
grid->getSmoothnessCost(0, grid->getNumLabels() - 1));
T val = 0;
for (int i = 0; i < grid->getNumLabels(); i++) {
out[i] = GINF_MIN(out[i], minh);
val += out[i];
}
// Normalize
val /= grid->getNumLabels();
for (int i = 0; i < grid->getNumLabels(); i++) {
out[i] -= val;
}
}
}
template <typename T>
int bpGetBelief(Grid<T> *grid, Matrix<T> *msgs, Matrix<T> *from, int x, int y) {
// Collect msgs from neighbours
bpCollect(grid, msgs, from, x, y);
// Pick the label that minimizes the cost
T minCost = grid->getDataCost(x, y, 0) + from->at(x, y, 0);
int minLabel = 0;
for (int i = 1; i < grid->getNumLabels(); i++) {
T cost = grid->getDataCost(x, y, i) + from->at(x, y, i);
if (cost < minCost) {
minCost = cost;
minLabel = i;
}
}
// Return the result
return minLabel;
}
template <typename T>
void decodeHbp(Grid<T> *grid, int numLevels, int numItersPerLevel, Matrix<int> *result) {
// Create matrices to store the messages for each level
Matrix<T> **msgs = new Matrix<T>* [numLevels];
Matrix<T> **from = new Matrix<T>* [numLevels];
// Create matrices to store data costs at each level
Matrix<T> **data = new Matrix<T>* [numLevels];
// At the finest level, the data costs correspond to the original problem
data[0] = new Matrix<T>(3, grid->getWidth(), grid->getHeight(), grid->getNumLabels());
data[0]->copyFrom(grid->getDataCosts());
// Calculate the data costs on the other levels
for (int t = 1; t < numLevels; t++) {
int w = (int)ceil(data[t - 1]->getSize(0) / 2.0),
h = (int)ceil(data[t - 1]->getSize(1) / 2.0);
// We gotta make sure that we don't get too 'coarse'
if (w < 1 || h < 1) return;
// The data cost of each node on the current level uses the sum of
// the data costs of four nodes below this level
data[t] = new Matrix<T>(3, w, h, grid->getNumLabels());
for (int y = 0; y < data[t - 1]->getSize(1); y++) {
for (int x = 0; x < data[t - 1]->getSize(0); x++) {
for (int i = 0; i < grid->getNumLabels(); i++) {
data[t]->get(x / 2, y / 2, i) += data[t - 1]->get(x, y, i);
}
}
}
}
// Use a temporary array to store message that is sent from one particular node to another
T *msgBuffer = new T[grid->getNumLabels()];
for (int t = numLevels - 1; t >= 0; t--) {
int w = data[t]->getSize(0), h = data[t]->getSize(1);
// Create the msg matrices for this particular level
msgs[t] = new Matrix<T>(4, w, h, GINF_NUM_DIR, grid->getNumLabels());
from[t] = new Matrix<T>(3, w, h, grid->getNumLabels());
// If we're not on the top level, the messages are initialized from the previous level
if (t != numLevels - 1) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
for (int d = 0; d < GINF_NUM_DIR; d++) {
for (int i = 0; i < grid->getNumLabels(); i++) {
// Initialize message with node on the above level
msgs[t]->get(x, y, d, i) = msgs[t + 1]->get(x / 2, y / 2, d, i);
}
}
}
}
// Free up memory
delete msgs[t + 1];
delete data[t + 1];
delete from[t + 1];
}
// For each level, perform belief propagation using checkerboard pattern
for (int i = 0; i < numItersPerLevel; i++) {
for (int y = 1; y < h - 1; y++) {
for (int x = ((y + i) & 1) + 1; x < w - 1; x += 2) {
// Collect msgs from neighbours
bpCollect(grid, msgs[t], from[t], x, y);
// Foreach direction, send message
for (int d = 0; d < GINF_NUM_DIR; d++) {
bpSendMsg(grid, msgs[t], from[t], data[t], msgBuffer, x, y, d);
// Copy the msgBuffer into the msgs array
for (int j = 0; j < grid->getNumLabels(); j++) {
msgs[t]->get(x, y, d, j) = msgBuffer[j];
}
}
}
}
}
}
// We won't need this anymore
delete[] msgBuffer;
// Finally, get the belief of every node
for (int y = 1; y < grid->getHeight() - 1; y++) {
for (int x = 1; x < grid->getWidth() - 1; x++) {
result->get(x, y) = bpGetBelief(grid, msgs[0], from[0], x, y);
}
}
}
template <typename T>
void decodeBpSync(Grid<T> *grid, int numIters, Matrix<int> *result) {
// Synchronous loopy belief propagation is equivalent to running
// hierarchical belief propagation for one level
decodeHbp(grid, 1, numIters, result);
}
// Instantiate templates
template void decodeHbp<float>(Grid<float>*, int, int, Matrix<int>*);
template void decodeHbp<int>(Grid<int>*, int, int, Matrix<int>*);
template void decodeBpSync<float>(Grid<float>*, int, Matrix<int>*);
template void decodeBpSync<int>(Grid<int>*, int, Matrix<int>*);
}
<commit_msg>Update belief propagation<commit_after>#include "include/bp.h"
#include <cmath>
namespace ginf {
// Sum up messages sent to a node by its neighbours
template <typename T>
void bpCollect(Grid<T> *grid, Matrix<T> *msgs, Matrix<T> *from, Matrix<T> *dataCosts, int x, int y) {
// For each label
for (int i = 0; i < grid->getNumLabels(); i++) {
from->get(x, y, i) = dataCosts->at(x, y, i);
// For each neighbour, add up the messages for this particular label
for (int d = 0; d < GINF_NUM_DIR; d++) {
from->get(x, y, i) += msgs->at(x + dirX[d], y + dirY[d], GINF_OPP_DIR(d), i);
}
}
}
// Send a message in a particular direction
template <typename T>
void bpSendMsg(Grid<T> *grid, Matrix<T> *msgs, Matrix<T> *from, T *out, int x, int y, int d) {
// Get the coordinate of the neighbour
int nx = x + dirX[d], ny = y + dirY[d];
if (grid->getSmModel() == GINF_SM_TRUNC_LINEAR || grid->getSmModel() == GINF_SM_POTTS) {
// We can apply an optimization to calculate the message in O(L), where L is the number of labels
T minh = out[0] = from->at(x, y, 0) - msgs->at(nx, ny, GINF_OPP_DIR(d), 0);
for (int i = 1; i < grid->getNumLabels(); i++) {
out[i] = from->at(x, y, i) - msgs->at(nx, ny, GINF_OPP_DIR(d), i);
minh = GINF_MIN(minh, out[i]);
}
// Find the linear scaling constant
T scale = grid->getSmoothnessCost(0, 1);
for (int i = 1; i < grid->getNumLabels(); i++)
out[i] = GINF_MIN(out[i], out[i - 1] + scale);
for (int i = grid->getNumLabels() - 2; i >= 0; i--)
out[i] = GINF_MIN(out[i], out[i + 1] + scale);
// Truncate the messages using truncate constant
minh += grid->getSmoothnessCost(0, grid->getNumLabels() - 1);
T val = 0;
for (int i = 0; i < grid->getNumLabels(); i++) {
out[i] = GINF_MIN(out[i], minh);
val += out[i];
}
// Normalize
val /= grid->getNumLabels();
for (int i = 0; i < grid->getNumLabels(); i++) {
out[i] -= val;
}
} else {
for (int i = 0; i < grid->getNumLabels(); i++) {
out[i] = grid->getSmoothnessCost(i, 0) + from->at(x, y, 0);
for (int j = 0; j < grid->getNumLabels(); j++) {
out[i] = GINF_MIN(out[i], grid->getSmoothnessCost(i, j) + from->at(x, y, j));
}
}
}
}
template <typename T>
int bpGetBelief(Grid<T> *grid, Matrix<T> *msgs, Matrix<T> *from, Matrix<T> *data, int x, int y) {
// Collect msgs from neighbours
bpCollect(grid, msgs, data, from, x, y);
// Pick the label that minimizes the cost
T minCost = from->at(x, y, 0);
int minLabel = 0;
for (int i = 1; i < grid->getNumLabels(); i++) {
T cost = from->at(x, y, i);
if (cost < minCost) {
minCost = cost;
minLabel = i;
}
}
// Return the result
return minLabel;
}
template <typename T>
void decodeHbp(Grid<T> *grid, int numLevels, int numItersPerLevel, Matrix<int> *result) {
// Create matrices to store the messages for each level
Matrix<T> **msgs = new Matrix<T>* [numLevels];
Matrix<T> **from = new Matrix<T>* [numLevels];
// Create matrices to store data costs at each level
Matrix<T> **data = new Matrix<T>* [numLevels];
// At the finest level, the data costs correspond to the original problem
data[0] = new Matrix<T>(3, grid->getWidth(), grid->getHeight(), grid->getNumLabels());
data[0]->copyFrom(grid->getDataCosts());
// Calculate the data costs on the other levels
for (int t = 1; t < numLevels; t++) {
int w = (int)ceil(data[t - 1]->getSize(0) / 2.0),
h = (int)ceil(data[t - 1]->getSize(1) / 2.0);
// We gotta make sure that we don't get too 'coarse'
if (w < 1 || h < 1) return;
// The data cost of each node on the current level uses the sum of
// the data costs of four nodes below this level
data[t] = new Matrix<T>(3, w, h, grid->getNumLabels());
for (int y = 0; y < data[t - 1]->getSize(1); y++) {
for (int x = 0; x < data[t - 1]->getSize(0); x++) {
for (int i = 0; i < grid->getNumLabels(); i++) {
data[t]->get(x / 2, y / 2, i) += data[t - 1]->get(x, y, i);
}
}
}
}
// Use a temporary array to store message that is sent from one particular node to another
T *msgBuffer = new T[grid->getNumLabels()];
for (int t = numLevels - 1; t >= 0; t--) {
int w = data[t]->getSize(0), h = data[t]->getSize(1);
// Create the msg matrices for this particular level
msgs[t] = new Matrix<T>(4, w, h, GINF_NUM_DIR, grid->getNumLabels());
from[t] = new Matrix<T>(3, w, h, grid->getNumLabels());
// If we're not on the top level, the messages are initialized from the previous level
if (t != numLevels - 1) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
for (int d = 0; d < GINF_NUM_DIR; d++) {
for (int i = 0; i < grid->getNumLabels(); i++) {
// Initialize message with node on the above level
msgs[t]->get(x, y, d, i) = msgs[t + 1]->get(x / 2, y / 2, d, i);
}
}
}
}
// Free up memory
delete msgs[t + 1];
delete data[t + 1];
delete from[t + 1];
}
// For each level, perform belief propagation using checkerboard pattern
for (int i = 0; i < numItersPerLevel; i++) {
for (int y = 1; y < h - 1; y++) {
for (int x = ((y + i) & 1) + 1; x < w - 1; x += 2) {
// Collect msgs from neighbours
bpCollect(grid, msgs[t], from[t], data[t], x, y);
// Foreach direction, send message
for (int d = 0; d < GINF_NUM_DIR; d++) {
bpSendMsg(grid, msgs[t], from[t], msgBuffer, x, y, d);
// Copy the msgBuffer into the msgs array
for (int j = 0; j < grid->getNumLabels(); j++) {
msgs[t]->get(x, y, d, j) = msgBuffer[j];
}
}
}
}
}
}
// We won't need this anymore
delete[] msgBuffer;
// Finally, get the belief of every node
for (int y = 1; y < grid->getHeight() - 1; y++) {
for (int x = 1; x < grid->getWidth() - 1; x++) {
result->get(x, y) = bpGetBelief(grid, msgs[0], from[0], data[0], x, y);
}
}
}
template <typename T>
void decodeBpSync(Grid<T> *grid, int numIters, Matrix<int> *result) {
// Synchronous loopy belief propagation is equivalent to running
// hierarchical belief propagation for one level
decodeHbp(grid, 1, numIters, result);
}
// Instantiate templates
template void decodeHbp<float>(Grid<float>*, int, int, Matrix<int>*);
template void decodeHbp<int>(Grid<int>*, int, int, Matrix<int>*);
template void decodeBpSync<float>(Grid<float>*, int, Matrix<int>*);
template void decodeBpSync<int>(Grid<int>*, int, Matrix<int>*);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 by KO Myung-Hun <komh@chollian.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the copyright holder nor the names
* of any other 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.
*/
#define INCL_WIN
#include <os2.h>
#include <sstream>
#include <KPMLib.h>
#include <libssh2.h>
#include "KSCPClient.h"
#include "kscp.h"
int KSCP::Run()
{
int rc;
rc = libssh2_init( 0 );
if( rc != 0 )
{
stringstream ssMsg;
ssMsg << "libssh2 initialization failed : rc = " << rc;
WinMessageBox( HWND_DESKTOP, HWND_DESKTOP,
ssMsg.str().c_str(), "KSCP", 0xFFFF,
MB_OK | MB_ERROR );
return 1;
}
KSCPClient kclient;
kclient.RegisterClass( _hab, WC_KSCP, CS_SIZEREDRAW, sizeof( PVOID ));
ULONG flFrameFlags;
flFrameFlags = FCF_SYSMENU | FCF_TITLEBAR | FCF_MINMAX | FCF_SIZEBORDER |
FCF_SHELLPOSITION | FCF_TASKLIST | FCF_MENU |
FCF_ACCELTABLE;
KFrameWindow kframe;
kframe.CreateStdWindow( KWND_DESKTOP, // parent window handle
WS_VISIBLE, // frame window style
&flFrameFlags, // window style
KSCP_TITLE, // window title
0, // default client style
0, // resource in exe file
ID_KSCP, // frame window id
kclient // client window handle
);
if( kframe.GetHWND())
{
bool fShow = false;
ULONG ulBufMax;
ulBufMax = sizeof( fShow );
PrfQueryProfileData( HINI_USERPROFILE, KSCP_PRF_APP,
KSCP_PRF_KEY_SHOW, &fShow, &ulBufMax );
if( fShow )
kclient.PostMsg( WM_COMMAND, MPFROMSHORT( IDM_FILE_ADDRBOOK ),
MPFROM2SHORT( CMDSRC_MENU, false ));
KPMApp::Run();
kframe.DestroyWindow();
}
libssh2_exit();
return 0;
}
int main( void )
{
KSCP kscp;
return kscp.Run();
}
<commit_msg>Use MessageBox() instead of WinMessageBox()<commit_after>/*
* Copyright (c) 2012 by KO Myung-Hun <komh@chollian.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the copyright holder nor the names
* of any other 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.
*/
#define INCL_WIN
#include <os2.h>
#include <sstream>
#include <KPMLib.h>
#include <libssh2.h>
#include "KSCPClient.h"
#include "kscp.h"
int KSCP::Run()
{
int rc;
rc = libssh2_init( 0 );
if( rc != 0 )
{
stringstream ssMsg;
ssMsg << "libssh2 initialization failed : rc = " << rc;
MessageBox( KWND_DESKTOP, ssMsg.str(), "KSCP", MB_OK | MB_ERROR );
return 1;
}
KSCPClient kclient;
kclient.RegisterClass( _hab, WC_KSCP, CS_SIZEREDRAW, sizeof( PVOID ));
ULONG flFrameFlags;
flFrameFlags = FCF_SYSMENU | FCF_TITLEBAR | FCF_MINMAX | FCF_SIZEBORDER |
FCF_SHELLPOSITION | FCF_TASKLIST | FCF_MENU |
FCF_ACCELTABLE;
KFrameWindow kframe;
kframe.CreateStdWindow( KWND_DESKTOP, // parent window handle
WS_VISIBLE, // frame window style
&flFrameFlags, // window style
KSCP_TITLE, // window title
0, // default client style
0, // resource in exe file
ID_KSCP, // frame window id
kclient // client window handle
);
if( kframe.GetHWND())
{
bool fShow = false;
ULONG ulBufMax;
ulBufMax = sizeof( fShow );
PrfQueryProfileData( HINI_USERPROFILE, KSCP_PRF_APP,
KSCP_PRF_KEY_SHOW, &fShow, &ulBufMax );
if( fShow )
kclient.PostMsg( WM_COMMAND, MPFROMSHORT( IDM_FILE_ADDRBOOK ),
MPFROM2SHORT( CMDSRC_MENU, false ));
KPMApp::Run();
kframe.DestroyWindow();
}
libssh2_exit();
return 0;
}
int main( void )
{
KSCP kscp;
return kscp.Run();
}
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_TESTS_UTILS_HPP__
#define __STOUT_TESTS_UTILS_HPP__
#include <string>
#include <gtest/gtest.h>
#include <stout/gtest.hpp>
#include <stout/try.hpp>
#include <stout/os/chdir.hpp>
#include <stout/os/getcwd.hpp>
#include <stout/os/mkdtemp.hpp>
#include <stout/os/rmdir.hpp>
#if __FreeBSD__
#include <stout/os/sysctl.hpp>
#endif
class TemporaryDirectoryTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
// Save the current working directory.
cwd = os::getcwd();
// Create a temporary directory for the test.
Try<std::string> directory = os::mkdtemp();
ASSERT_SOME(directory) << "Failed to mkdtemp";
sandbox = directory.get();
// Run the test out of the temporary directory we created.
ASSERT_SOME(os::chdir(sandbox.get()))
<< "Failed to chdir into '" << sandbox.get() << "'";
}
virtual void TearDown()
{
// Return to previous working directory and cleanup the sandbox.
ASSERT_SOME(os::chdir(cwd));
if (sandbox.isSome()) {
ASSERT_SOME(os::rmdir(sandbox.get()));
}
}
// A temporary directory for test purposes.
// Not to be confused with the "sandbox" that tasks are run in.
Option<std::string> sandbox;
private:
std::string cwd;
};
#ifdef __FreeBSD__
inline bool isJailed() {
int mib[4];
size_t len = 4;
::sysctlnametomib("security.jail.jailed", mib, &len);
Try<int> jailed = os::sysctl(mib[0], mib[1], mib[2]).integer();
if (jailed.isSome()) {
return jailed.get() == 1;
}
return false;
}
#endif
#endif // __STOUT_TESTS_UTILS_HPP__
<commit_msg>Resolved the `realpath` of the sandbox directory in tests.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_TESTS_UTILS_HPP__
#define __STOUT_TESTS_UTILS_HPP__
#include <string>
#include <gtest/gtest.h>
#include <stout/gtest.hpp>
#include <stout/try.hpp>
#include <stout/os/chdir.hpp>
#include <stout/os/getcwd.hpp>
#include <stout/os/mkdtemp.hpp>
#include <stout/os/realpath.hpp>
#include <stout/os/rmdir.hpp>
#if __FreeBSD__
#include <stout/os/sysctl.hpp>
#endif
class TemporaryDirectoryTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
// Save the current working directory.
cwd = os::getcwd();
// Create a temporary directory for the test.
Try<std::string> directory = os::mkdtemp();
ASSERT_SOME(directory) << "Failed to mkdtemp";
// We get the `realpath` of the temporary directory because some
// platforms, like macOS, symlink `/tmp` to `/private/var`, but
// return the symlink name when creating temporary directories.
// This is problematic because a lot of tests compare the
// `realpath` of a temporary file.
Result<std::string> realpath = os::realpath(directory.get());
ASSERT_SOME(realpath) << "Failed to get realpath of '" << directory.get()
<< "': "
<< (realpath.isError() ? realpath.error()
: "No such directory");
sandbox = realpath.get();
// Run the test out of the temporary directory we created.
ASSERT_SOME(os::chdir(sandbox.get()))
<< "Failed to chdir into '" << sandbox.get() << "'";
}
virtual void TearDown()
{
// Return to previous working directory and cleanup the sandbox.
ASSERT_SOME(os::chdir(cwd));
if (sandbox.isSome()) {
ASSERT_SOME(os::rmdir(sandbox.get()));
}
}
// A temporary directory for test purposes.
// Not to be confused with the "sandbox" that tasks are run in.
Option<std::string> sandbox;
private:
std::string cwd;
};
#ifdef __FreeBSD__
inline bool isJailed() {
int mib[4];
size_t len = 4;
::sysctlnametomib("security.jail.jailed", mib, &len);
Try<int> jailed = os::sysctl(mib[0], mib[1], mib[2]).integer();
if (jailed.isSome()) {
return jailed.get() == 1;
}
return false;
}
#endif
#endif // __STOUT_TESTS_UTILS_HPP__
<|endoftext|> |
<commit_before>/*
SWARM
Copyright (C) 2012-2017 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
void pushop(char newop, char ** cigarendp, char * op, int * count)
{
if (newop == *op)
(*count)++;
else
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = sprintf(buf, "%d", *count);
*cigarendp -= len;
strncpy(*cigarendp, buf, len);
}
*op = newop;
*count = 1;
}
}
void finishop(char ** cigarendp, char * op, int * count)
{
if ((op) && (count))
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = sprintf(buf, "%d", *count);
*cigarendp -= len;
strncpy(*cigarendp, buf, len);
}
*op = 0;
*count = 0;
}
}
const unsigned char maskup = 1;
const unsigned char maskleft = 2;
const unsigned char maskextup = 4;
const unsigned char maskextleft = 8;
/*
Needleman/Wunsch/Sellers aligner
finds a global alignment with minimum cost
there should be positive costs/penalties for gaps and for mismatches
matches should have zero cost (0)
alignment priority when backtracking (from lower right corner):
1. left/insert/e (gap in query sequence (qseq))
2. align/diag/h (match/mismatch)
3. up/delete/f (gap in database sequence (dseq))
qseq: the reference/query/upper/vertical/from sequence
dseq: the sample/database/lower/horisontal/to sequence
typical costs:
match: 0
mismatch: 3
gapopen: 4
gapextend: 3
input
dseq: pointer to start of database sequence
dend: pointer after database sequence
qseq: pointer to start of query sequence
qend: pointer after database sequence
score_matrix: 32x32 matrix of longs with scores for aligning two symbols
gapopen: positive number indicating penalty for opening a gap of length zero
gapextend: positive number indicating penalty for extending a gap
output
nwscore: the global alignment score
nwdiff: number of non-identical nucleotides in one optimal global alignment
nwalignmentlength: the length of one optimal alignment
nwalignment: cigar string with one optimal alignment
*/
void nw(char * dseq,
char * dend,
char * qseq,
char * qend,
long * score_matrix,
unsigned long gapopen,
unsigned long gapextend,
unsigned long * nwscore,
unsigned long * nwdiff,
unsigned long * nwalignmentlength,
char ** nwalignment,
unsigned char * dir,
unsigned long * hearray,
unsigned long queryno,
unsigned long dbseqno)
{
/* dir must point to at least qlen*dlen bytes of allocated memory
hearray must point to at least 2*qlen longs of allocated memory (8*qlen bytes) */
long n, e;
long unsigned *hep;
long qlen = qend - qseq;
long dlen = dend - dseq;
memset(dir, 0, qlen*dlen);
long i, j;
for(i=0; i<qlen; i++)
{
hearray[2*i] = 1 * gapopen + (i+1) * gapextend; // H (N)
hearray[2*i+1] = 2 * gapopen + (i+2) * gapextend; // E
}
for(j=0; j<dlen; j++)
{
hep = hearray;
long f = 2 * gapopen + (j+2) * gapextend;
long h = (j == 0) ? 0 : (gapopen + j * gapextend);
for(i=0; i<qlen; i++)
{
long index = qlen*j+i;
n = *hep;
e = *(hep+1);
h += score_matrix[(dseq[j]<<5) + qseq[i]];
dir[index] |= (f < h ? maskup : 0);
h = MIN(h, f);
h = MIN(h, e);
dir[index] |= (e == h ? maskleft : 0);
*hep = h;
h += gapopen + gapextend;
e += gapextend;
f += gapextend;
dir[index] |= (f < h ? maskextup : 0);
dir[index] |= (e < h ? maskextleft : 0);
f = MIN(h,f);
e = MIN(h,e);
*(hep+1) = e;
h = n;
hep += 2;
}
}
long dist = hearray[2*qlen-2];
/* backtrack: count differences and save alignment in cigar string */
long score = 0;
long alength = 0;
long matches = 0;
char * cigar = (char *) xmalloc(qlen + dlen + 1);
char * cigarend = cigar+qlen+dlen+1;
char op = 0;
int count = 0;
*(--cigarend) = 0;
i = qlen;
j = dlen;
while ((i>0) && (j>0))
{
int d = dir[qlen*(j-1)+(i-1)];
alength++;
if ((op == 'I') && (d & maskextleft))
{
score += gapextend;
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((op == 'D') && (d & maskextup))
{
score += gapextend;
i--;
pushop('D', &cigarend, &op, &count);
}
else if (d & maskleft)
{
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
else if (d & maskup)
{
score += gapextend;
if (op != 'D')
score +=gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
else
{
score += score_matrix[(dseq[j-1] << 5) + qseq[i-1]];
if (qseq[i-1] == dseq[j-1])
matches++;
i--;
j--;
pushop('M', &cigarend, &op, &count);
}
}
while(i>0)
{
alength++;
score += gapextend;
if (op != 'D')
score += gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
while(j>0)
{
alength++;
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
finishop(&cigarend, &op, &count);
/* move and reallocate cigar */
long cigarlength = cigar+qlen+dlen-cigarend;
memmove(cigar, cigarend, cigarlength+1);
cigar = (char*) xrealloc(cigar, cigarlength+1);
* nwscore = dist;
* nwdiff = alength - matches;
* nwalignmentlength = alength;
* nwalignment = cigar;
if (score != dist)
{
fprintf(stderr, "WARNING: Error with query no %lu and db sequence no %lu:\n", queryno, dbseqno);
fprintf(stderr, "Initial and recomputed alignment score disagreement: %ld %ld\n", dist, score);
fprintf(stderr, "Alignment: %s\n", cigar);
}
}
<commit_msg>socpe reduc hep<commit_after>/*
SWARM
Copyright (C) 2012-2017 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
void pushop(char newop, char ** cigarendp, char * op, int * count)
{
if (newop == *op)
(*count)++;
else
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = sprintf(buf, "%d", *count);
*cigarendp -= len;
strncpy(*cigarendp, buf, len);
}
*op = newop;
*count = 1;
}
}
void finishop(char ** cigarendp, char * op, int * count)
{
if ((op) && (count))
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = sprintf(buf, "%d", *count);
*cigarendp -= len;
strncpy(*cigarendp, buf, len);
}
*op = 0;
*count = 0;
}
}
const unsigned char maskup = 1;
const unsigned char maskleft = 2;
const unsigned char maskextup = 4;
const unsigned char maskextleft = 8;
/*
Needleman/Wunsch/Sellers aligner
finds a global alignment with minimum cost
there should be positive costs/penalties for gaps and for mismatches
matches should have zero cost (0)
alignment priority when backtracking (from lower right corner):
1. left/insert/e (gap in query sequence (qseq))
2. align/diag/h (match/mismatch)
3. up/delete/f (gap in database sequence (dseq))
qseq: the reference/query/upper/vertical/from sequence
dseq: the sample/database/lower/horisontal/to sequence
typical costs:
match: 0
mismatch: 3
gapopen: 4
gapextend: 3
input
dseq: pointer to start of database sequence
dend: pointer after database sequence
qseq: pointer to start of query sequence
qend: pointer after database sequence
score_matrix: 32x32 matrix of longs with scores for aligning two symbols
gapopen: positive number indicating penalty for opening a gap of length zero
gapextend: positive number indicating penalty for extending a gap
output
nwscore: the global alignment score
nwdiff: number of non-identical nucleotides in one optimal global alignment
nwalignmentlength: the length of one optimal alignment
nwalignment: cigar string with one optimal alignment
*/
void nw(char * dseq,
char * dend,
char * qseq,
char * qend,
long * score_matrix,
unsigned long gapopen,
unsigned long gapextend,
unsigned long * nwscore,
unsigned long * nwdiff,
unsigned long * nwalignmentlength,
char ** nwalignment,
unsigned char * dir,
unsigned long * hearray,
unsigned long queryno,
unsigned long dbseqno)
{
/* dir must point to at least qlen*dlen bytes of allocated memory
hearray must point to at least 2*qlen longs of allocated memory (8*qlen bytes) */
long n, e;
long qlen = qend - qseq;
long dlen = dend - dseq;
memset(dir, 0, qlen*dlen);
long i, j;
for(i=0; i<qlen; i++)
{
hearray[2*i] = 1 * gapopen + (i+1) * gapextend; // H (N)
hearray[2*i+1] = 2 * gapopen + (i+2) * gapextend; // E
}
for(j=0; j<dlen; j++)
{
long unsigned *hep;
hep = hearray;
long f = 2 * gapopen + (j+2) * gapextend;
long h = (j == 0) ? 0 : (gapopen + j * gapextend);
for(i=0; i<qlen; i++)
{
long index = qlen*j+i;
n = *hep;
e = *(hep+1);
h += score_matrix[(dseq[j]<<5) + qseq[i]];
dir[index] |= (f < h ? maskup : 0);
h = MIN(h, f);
h = MIN(h, e);
dir[index] |= (e == h ? maskleft : 0);
*hep = h;
h += gapopen + gapextend;
e += gapextend;
f += gapextend;
dir[index] |= (f < h ? maskextup : 0);
dir[index] |= (e < h ? maskextleft : 0);
f = MIN(h,f);
e = MIN(h,e);
*(hep+1) = e;
h = n;
hep += 2;
}
}
long dist = hearray[2*qlen-2];
/* backtrack: count differences and save alignment in cigar string */
long score = 0;
long alength = 0;
long matches = 0;
char * cigar = (char *) xmalloc(qlen + dlen + 1);
char * cigarend = cigar+qlen+dlen+1;
char op = 0;
int count = 0;
*(--cigarend) = 0;
i = qlen;
j = dlen;
while ((i>0) && (j>0))
{
int d = dir[qlen*(j-1)+(i-1)];
alength++;
if ((op == 'I') && (d & maskextleft))
{
score += gapextend;
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((op == 'D') && (d & maskextup))
{
score += gapextend;
i--;
pushop('D', &cigarend, &op, &count);
}
else if (d & maskleft)
{
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
else if (d & maskup)
{
score += gapextend;
if (op != 'D')
score +=gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
else
{
score += score_matrix[(dseq[j-1] << 5) + qseq[i-1]];
if (qseq[i-1] == dseq[j-1])
matches++;
i--;
j--;
pushop('M', &cigarend, &op, &count);
}
}
while(i>0)
{
alength++;
score += gapextend;
if (op != 'D')
score += gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
while(j>0)
{
alength++;
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
finishop(&cigarend, &op, &count);
/* move and reallocate cigar */
long cigarlength = cigar+qlen+dlen-cigarend;
memmove(cigar, cigarend, cigarlength+1);
cigar = (char*) xrealloc(cigar, cigarlength+1);
* nwscore = dist;
* nwdiff = alength - matches;
* nwalignmentlength = alength;
* nwalignment = cigar;
if (score != dist)
{
fprintf(stderr, "WARNING: Error with query no %lu and db sequence no %lu:\n", queryno, dbseqno);
fprintf(stderr, "Initial and recomputed alignment score disagreement: %ld %ld\n", dist, score);
fprintf(stderr, "Alignment: %s\n", cigar);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <sstream>
#include <deque>
#include <iostream>
#include "halValidate.h"
#include "hal.h"
using namespace std;
using namespace hal;
// current implementation is poor and hacky. should fix up to
// use iterators to properly scan the segments.
void hal::validateBottomSegment(const BottomSegment* bottomSegment)
{
const Genome* genome = bottomSegment->getGenome();
hal_index_t index = bottomSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Bottom segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (bottomSegment->getLength() < 1)
{
stringstream ss;
ss << "Bottom segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
hal_size_t numChildren = bottomSegment->getNumChildren();
for (hal_size_t child = 0; child < numChildren; ++child)
{
const Genome* childGenome = genome->getChild(child);
const hal_index_t childIndex = bottomSegment->getChildIndex(child);
if (childGenome != NULL && childIndex != NULL_INDEX)
{
if (childIndex >= (hal_index_t)childGenome->getNumTopSegments())
{
stringstream ss;
ss << "Child " << child << " index " <<childIndex << " of segment "
<< bottomSegment->getArrayIndex() << " out of range in genome "
<< childGenome->getName();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr topSegmentIteratr =
childGenome->getTopSegmentIterator(childIndex);
const TopSegment* childSegment = topSegmentIteratr->getTopSegment();
if (childSegment->getLength() != bottomSegment->getLength())
{
stringstream ss;
ss << "Child " << child << " length of segment "
<< bottomSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< childSegment->getLength() << " which does not match "
<< bottomSegment->getLength();
throw hal_exception(ss.str());
}
if (childSegment->getNextParalogyIndex() == NULL_INDEX &&
childSegment->getParentIndex() != bottomSegment->getArrayIndex())
{
throw hal_exception("parent / child index mismatch (parent=" +
genome->getName() + " child=" +
childGenome->getName());
}
}
}
const hal_index_t parseIndex = bottomSegment->getTopParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getParent() != NULL)
{
stringstream ss;
ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumTopSegments())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index " << parseIndex
<< " greater than the number of top segments, "
<< (hal_index_t)genome->getNumTopSegments();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr parseIterator =
genome->getTopSegmentIterator(parseIndex);
const TopSegment* parseSegment = parseIterator->getTopSegment();
hal_offset_t parseOffset = bottomSegment->getTopParseOffset();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset, " << parseOffset
<< ", greater than the length of the segment, "
<< parseSegment->getLength();
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
bottomSegment->getStartPosition())
{
throw hal_exception("parse index broken in bottom segment in genome " +
genome->getName());
}
}
}
void hal::validateTopSegment(const TopSegment* topSegment)
{
const Genome* genome = topSegment->getGenome();
hal_index_t index = topSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (topSegment->getLength() < 1)
{
stringstream ss;
ss << "Top segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
const Genome* parentGenome = genome->getParent();
const hal_index_t parentIndex = topSegment->getParentIndex();
if (parentGenome != NULL && parentIndex != NULL_INDEX)
{
if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments())
{
stringstream ss;
ss << "Parent index " << parentIndex << " of segment "
<< topSegment->getArrayIndex() << " out of range in genome "
<< parentGenome->getName();
throw hal_exception(ss.str());
}
BottomSegmentIteratorConstPtr bottomSegmentIterator =
parentGenome->getBottomSegmentIterator(parentIndex);
const BottomSegment* parentSegment =
bottomSegmentIterator->getBottomSegment();
if (topSegment->getLength() != parentSegment->getLength())
{
stringstream ss;
ss << "Parent length of segment " << topSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< parentSegment->getLength() << " which does not match "
<< topSegment->getLength();
throw hal_exception(ss.str());
}
}
const hal_index_t parseIndex = topSegment->getBottomParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getNumChildren() != 0)
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumBottomSegments())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index out of range";
throw hal_exception(ss.str());
}
hal_offset_t parseOffset = topSegment->getBottomParseOffset();
BottomSegmentIteratorConstPtr bottomSegmentIterator =
genome->getBottomSegmentIterator(parseIndex);
const BottomSegment* parseSegment =
bottomSegmentIterator->getBottomSegment();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset out of range";
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
topSegment->getStartPosition())
{
throw hal_exception("parse index broken in top segment in genome " +
genome->getName());
}
}
const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex();
if (paralogyIndex != NULL_INDEX)
{
TopSegmentIteratorConstPtr pti =
genome->getTopSegmentIterator(paralogyIndex);
if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex())
{
stringstream ss;
ss << "Top segment " << topSegment->getArrayIndex() << " has parent index "
<< topSegment->getParentIndex() << ", but next paraglog "
<< topSegment->getNextParalogyIndex() << " has parent Index "
<< pti->getTopSegment()->getParentIndex()
<< ". Paralogous top segments must share same parent.";
throw hal_exception(ss.str());
}
}
}
void hal::validateSequence(const Sequence* sequence)
{
// Verify that the DNA sequence doesn't contain funny characters
DNAIteratorConstPtr dnaIt = sequence->getDNAIterator();
hal_size_t length = sequence->getSequenceLength();
for (hal_size_t i = 0; i < length; ++i)
{
hal_dna_t c = dnaIt->getChar();
if (isNucleotide(c) == false)
{
stringstream ss;
ss << "Non-nucleotide character discoverd at position "
<< i << " of sequence " << sequence->getName() << ": " << c;
throw hal_exception(ss.str());
}
}
// Check the top segments
if (sequence->getGenome()->getParent() != NULL)
{
hal_size_t totalTopLength = 0;
TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator();
hal_size_t numTopSegments = sequence->getNumTopSegments();
for (hal_size_t i = 0; i < numTopSegments; ++i)
{
const TopSegment* topSegment = topIt->getTopSegment();
validateTopSegment(topSegment);
totalTopLength += topSegment->getLength();
topIt->toRight();
}
if (totalTopLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its top segments add up to " << totalTopLength;
throw hal_exception(ss.str());
}
}
// Check the bottom segments
if (sequence->getGenome()->getNumChildren() > 0)
{
hal_size_t totalBottomLength = 0;
BottomSegmentIteratorConstPtr bottomIt =
sequence->getBottomSegmentIterator();
hal_size_t numBottomSegments = sequence->getNumBottomSegments();
for (hal_size_t i = 0; i < numBottomSegments; ++i)
{
const BottomSegment* bottomSegment = bottomIt->getBottomSegment();
validateBottomSegment(bottomSegment);
totalBottomLength += bottomSegment->getLength();
bottomIt->toRight();
}
if (totalBottomLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its bottom segments add up to " << totalBottomLength;
throw hal_exception(ss.str());
}
}
}
void hal::validateGenome(const Genome* genome)
{
// first we check the sequence coverage
hal_size_t totalTop = 0;
hal_size_t totalBottom = 0;
hal_size_t totalLength = 0;
SequenceIteratorConstPtr seqIt = genome->getSequenceIterator();
hal_size_t numSequences = genome->getNumSequences();
for (hal_size_t i = 0; i < numSequences; ++i)
{
const Sequence* sequence = seqIt->getSequence();
validateSequence(sequence);
totalTop += sequence->getNumTopSegments();
totalBottom += sequence->getNumBottomSegments();
totalLength += sequence->getSequenceLength();
// make sure it doesn't overlap any other sequences;
const Sequence* s1 =
genome->getSequenceBySite(sequence->getStartPosition());
if (s1 == NULL || s1->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
const Sequence* s2 =
genome->getSequenceBySite(sequence->getStartPosition() +
sequence->getSequenceLength() - 1);
if (s2 == NULL || s2->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
}
hal_size_t genomeLength = genome->getSequenceLength();
hal_size_t genomeTop = genome->getNumTopSegments();
hal_size_t genomeBottom = genome->getNumBottomSegments();
if (genomeLength != totalLength)
{
stringstream ss;
ss << "Problem: genome has length " << genomeLength
<< "But sequences total " << totalLength;
throw hal_exception(ss.str());
}
if (genomeTop != totalTop)
{
stringstream ss;
ss << "Problem: genome has " << genomeTop << " top segments but "
<< "sequences have " << totalTop << " top segments";
throw ss.str();
}
if (genomeBottom != totalBottom)
{
stringstream ss;
ss << "Problem: genome has " << genomeBottom << " bottom segments but "
<< "sequences have " << totalBottom << " bottom segments";
throw hal_exception(ss.str());
}
}
void hal::validateAlignment(AlignmentConstPtr alignment)
{
deque<string> bfQueue;
bfQueue.push_back(alignment->getRootName());
while (bfQueue.empty() == false)
{
string name = bfQueue.back();
bfQueue.pop_back();
if (name.empty() == false)
{
const Genome* genome = alignment->openGenome(name);
if (genome == NULL)
{
throw hal_exception("Failure to open genome " + name);
}
validateGenome(genome);
vector<string> childNames = alignment->getChildNames(name);
for (size_t i = 0; i < childNames.size(); ++i)
{
bfQueue.push_front(childNames[i]);
}
}
}
}
<commit_msg>fix bug in sequence loop<commit_after>/*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <sstream>
#include <deque>
#include <iostream>
#include "halValidate.h"
#include "hal.h"
using namespace std;
using namespace hal;
// current implementation is poor and hacky. should fix up to
// use iterators to properly scan the segments.
void hal::validateBottomSegment(const BottomSegment* bottomSegment)
{
const Genome* genome = bottomSegment->getGenome();
hal_index_t index = bottomSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Bottom segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (bottomSegment->getLength() < 1)
{
stringstream ss;
ss << "Bottom segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
hal_size_t numChildren = bottomSegment->getNumChildren();
for (hal_size_t child = 0; child < numChildren; ++child)
{
const Genome* childGenome = genome->getChild(child);
const hal_index_t childIndex = bottomSegment->getChildIndex(child);
if (childGenome != NULL && childIndex != NULL_INDEX)
{
if (childIndex >= (hal_index_t)childGenome->getNumTopSegments())
{
stringstream ss;
ss << "Child " << child << " index " <<childIndex << " of segment "
<< bottomSegment->getArrayIndex() << " out of range in genome "
<< childGenome->getName();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr topSegmentIteratr =
childGenome->getTopSegmentIterator(childIndex);
const TopSegment* childSegment = topSegmentIteratr->getTopSegment();
if (childSegment->getLength() != bottomSegment->getLength())
{
stringstream ss;
ss << "Child " << child << " length of segment "
<< bottomSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< childSegment->getLength() << " which does not match "
<< bottomSegment->getLength();
throw hal_exception(ss.str());
}
if (childSegment->getNextParalogyIndex() == NULL_INDEX &&
childSegment->getParentIndex() != bottomSegment->getArrayIndex())
{
throw hal_exception("parent / child index mismatch (parent=" +
genome->getName() + " child=" +
childGenome->getName());
}
}
}
const hal_index_t parseIndex = bottomSegment->getTopParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getParent() != NULL)
{
stringstream ss;
ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumTopSegments())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index " << parseIndex
<< " greater than the number of top segments, "
<< (hal_index_t)genome->getNumTopSegments();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr parseIterator =
genome->getTopSegmentIterator(parseIndex);
const TopSegment* parseSegment = parseIterator->getTopSegment();
hal_offset_t parseOffset = bottomSegment->getTopParseOffset();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset, " << parseOffset
<< ", greater than the length of the segment, "
<< parseSegment->getLength();
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
bottomSegment->getStartPosition())
{
throw hal_exception("parse index broken in bottom segment in genome " +
genome->getName());
}
}
}
void hal::validateTopSegment(const TopSegment* topSegment)
{
const Genome* genome = topSegment->getGenome();
hal_index_t index = topSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (topSegment->getLength() < 1)
{
stringstream ss;
ss << "Top segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
const Genome* parentGenome = genome->getParent();
const hal_index_t parentIndex = topSegment->getParentIndex();
if (parentGenome != NULL && parentIndex != NULL_INDEX)
{
if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments())
{
stringstream ss;
ss << "Parent index " << parentIndex << " of segment "
<< topSegment->getArrayIndex() << " out of range in genome "
<< parentGenome->getName();
throw hal_exception(ss.str());
}
BottomSegmentIteratorConstPtr bottomSegmentIterator =
parentGenome->getBottomSegmentIterator(parentIndex);
const BottomSegment* parentSegment =
bottomSegmentIterator->getBottomSegment();
if (topSegment->getLength() != parentSegment->getLength())
{
stringstream ss;
ss << "Parent length of segment " << topSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< parentSegment->getLength() << " which does not match "
<< topSegment->getLength();
throw hal_exception(ss.str());
}
}
const hal_index_t parseIndex = topSegment->getBottomParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getNumChildren() != 0)
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumBottomSegments())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index out of range";
throw hal_exception(ss.str());
}
hal_offset_t parseOffset = topSegment->getBottomParseOffset();
BottomSegmentIteratorConstPtr bottomSegmentIterator =
genome->getBottomSegmentIterator(parseIndex);
const BottomSegment* parseSegment =
bottomSegmentIterator->getBottomSegment();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset out of range";
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
topSegment->getStartPosition())
{
throw hal_exception("parse index broken in top segment in genome " +
genome->getName());
}
}
const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex();
if (paralogyIndex != NULL_INDEX)
{
TopSegmentIteratorConstPtr pti =
genome->getTopSegmentIterator(paralogyIndex);
if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex())
{
stringstream ss;
ss << "Top segment " << topSegment->getArrayIndex() << " has parent index "
<< topSegment->getParentIndex() << ", but next paraglog "
<< topSegment->getNextParalogyIndex() << " has parent Index "
<< pti->getTopSegment()->getParentIndex()
<< ". Paralogous top segments must share same parent.";
throw hal_exception(ss.str());
}
}
}
void hal::validateSequence(const Sequence* sequence)
{
// Verify that the DNA sequence doesn't contain funny characters
DNAIteratorConstPtr dnaIt = sequence->getDNAIterator();
hal_size_t length = sequence->getSequenceLength();
for (hal_size_t i = 0; i < length; ++i)
{
hal_dna_t c = dnaIt->getChar();
if (isNucleotide(c) == false)
{
stringstream ss;
ss << "Non-nucleotide character discoverd at position "
<< i << " of sequence " << sequence->getName() << ": " << c;
throw hal_exception(ss.str());
}
}
// Check the top segments
if (sequence->getGenome()->getParent() != NULL)
{
hal_size_t totalTopLength = 0;
TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator();
hal_size_t numTopSegments = sequence->getNumTopSegments();
for (hal_size_t i = 0; i < numTopSegments; ++i)
{
const TopSegment* topSegment = topIt->getTopSegment();
validateTopSegment(topSegment);
totalTopLength += topSegment->getLength();
topIt->toRight();
}
if (totalTopLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its top segments add up to " << totalTopLength;
throw hal_exception(ss.str());
}
}
// Check the bottom segments
if (sequence->getGenome()->getNumChildren() > 0)
{
hal_size_t totalBottomLength = 0;
BottomSegmentIteratorConstPtr bottomIt =
sequence->getBottomSegmentIterator();
hal_size_t numBottomSegments = sequence->getNumBottomSegments();
for (hal_size_t i = 0; i < numBottomSegments; ++i)
{
const BottomSegment* bottomSegment = bottomIt->getBottomSegment();
validateBottomSegment(bottomSegment);
totalBottomLength += bottomSegment->getLength();
bottomIt->toRight();
}
if (totalBottomLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its bottom segments add up to " << totalBottomLength;
throw hal_exception(ss.str());
}
}
}
void hal::validateGenome(const Genome* genome)
{
// first we check the sequence coverage
hal_size_t totalTop = 0;
hal_size_t totalBottom = 0;
hal_size_t totalLength = 0;
SequenceIteratorConstPtr seqIt = genome->getSequenceIterator();
SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator();
for (; seqIt != seqEnd; seqIt->toNext())
{
const Sequence* sequence = seqIt->getSequence();
validateSequence(sequence);
totalTop += sequence->getNumTopSegments();
totalBottom += sequence->getNumBottomSegments();
totalLength += sequence->getSequenceLength();
// make sure it doesn't overlap any other sequences;
const Sequence* s1 =
genome->getSequenceBySite(sequence->getStartPosition());
if (s1 == NULL || s1->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
const Sequence* s2 =
genome->getSequenceBySite(sequence->getStartPosition() +
sequence->getSequenceLength() - 1);
if (s2 == NULL || s2->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
}
hal_size_t genomeLength = genome->getSequenceLength();
hal_size_t genomeTop = genome->getNumTopSegments();
hal_size_t genomeBottom = genome->getNumBottomSegments();
if (genomeLength != totalLength)
{
stringstream ss;
ss << "Problem: genome has length " << genomeLength
<< "But sequences total " << totalLength;
throw hal_exception(ss.str());
}
if (genomeTop != totalTop)
{
stringstream ss;
ss << "Problem: genome has " << genomeTop << " top segments but "
<< "sequences have " << totalTop << " top segments";
throw ss.str();
}
if (genomeBottom != totalBottom)
{
stringstream ss;
ss << "Problem: genome has " << genomeBottom << " bottom segments but "
<< "sequences have " << totalBottom << " bottom segments";
throw hal_exception(ss.str());
}
}
void hal::validateAlignment(AlignmentConstPtr alignment)
{
deque<string> bfQueue;
bfQueue.push_back(alignment->getRootName());
while (bfQueue.empty() == false)
{
string name = bfQueue.back();
bfQueue.pop_back();
if (name.empty() == false)
{
const Genome* genome = alignment->openGenome(name);
if (genome == NULL)
{
throw hal_exception("Failure to open genome " + name);
}
validateGenome(genome);
vector<string> childNames = alignment->getChildNames(name);
for (size_t i = 0; i < childNames.size(); ++i)
{
bfQueue.push_front(childNames[i]);
}
}
}
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef NET_WS_WEBSOCKET_HPP
#define NET_WS_WEBSOCKET_HPP
#include "header.hpp"
#include <net/http/server.hpp>
#include <net/http/basic_client.hpp>
#include <memory>
#include <stdexcept>
#include <vector>
namespace net {
struct WS_error : public std::runtime_error {
using base = std::runtime_error;
using base::base;
};
class WebSocket {
public:
class Message {
public:
using Data = std::vector<uint8_t>;
using Data_it = Data::iterator;
using Data_cit = Data::const_iterator;
auto extract_vector() noexcept {
return std::move(data_);
}
auto extract_shared_vector() {
return std::make_shared<std::vector<uint8_t>> (std::move(data_));
}
std::string to_string() const
{ return std::string(data(), size()); }
size_t size() const noexcept
{ return data_.size(); }
Data_it begin() noexcept
{ return data_.begin(); }
Data_it end() noexcept
{ return data_.end(); }
Data_cit cbegin() const noexcept
{ return data_.begin(); }
Data_cit cend() const noexcept
{ return data_.end(); }
const char* data() const noexcept
{ return (const char*) data_.data(); }
char* data() noexcept
{ return (char*) data_.data(); }
Message(const uint8_t* data, size_t len)
{
const auto* wsh = (ws_header*) data;
// setup initial header
const size_t hdr_bytes = std::min((size_t) wsh->header_length(), len);
std::memcpy(header_.data(), data, hdr_bytes);
this->header_length = hdr_bytes;
// move forward in buffer
data += hdr_bytes; len -= hdr_bytes;
// if the header became complete, reserve data
if (this->header_complete()) {
data_.reserve(header().data_length());
}
// append any remaining data
this->append(data, len);
}
size_t append(const uint8_t* data, size_t len);
bool is_complete() const noexcept
{ return header_complete() && data_.size() == header().data_length(); }
const ws_header& header() const noexcept
{ return *(ws_header*) header_.data(); }
op_code opcode() const noexcept
{ return header().opcode(); }
void unmask() noexcept
{
if (header().is_masked())
writable_header().masking_algorithm(this->data());
}
private:
Data data_;
std::array<uint8_t, 15> header_;
uint8_t header_length = 0;
inline bool header_complete() const noexcept {
return header_length >= 2 && header_length >= header().header_length();
}
ws_header& writable_header()
{ return *(ws_header*) header_.data(); }
}; // < class Message
using Message_ptr = std::unique_ptr<Message>;
using WebSocket_ptr = std::unique_ptr<WebSocket>;
// When a handshake is established and the WebSocket is created
using Connect_handler = delegate<void(WebSocket_ptr)>;
// Whether to accept the client or not before handshake
using Accept_handler = delegate<bool(net::Socket, std::string)>;
// data read (data, length)
typedef delegate<void(Message_ptr)> read_func;
// closed (status code)
typedef delegate<void(uint16_t)> close_func;
// error (reason)
typedef delegate<void(std::string)> error_func;
// ping (return value is whether to return pong or not, default yes)
typedef delegate<bool(const char* data, size_t len)> ping_func;
// pong recv
typedef delegate<void(const char* data, size_t len)> pong_func;
// if a ping resulted in a timeout
typedef delegate<void(WebSocket& ws)> pong_timeout_func;
/**
* @brief Upgrade a HTTP Request to a WebSocket connection.
*
* @param req The HTTP request
* @param writer The HTTP response writer
*
* @return A WebSocket_ptr, or nullptr if upgrade fails.
*/
static WebSocket_ptr upgrade(http::Request& req, http::Response_writer& writer);
/**
* @brief Upgrade a HTTP Response to a WebSocket connection.
*
* @param[in] err The HTTP error
* @param res The HTTP response
* @param conn The HTTP connection
* @param key The WS key sent in the HTTP request
*
* @return A WebSocket_ptr, or nullptr if upgrade fails.
*/
static WebSocket_ptr upgrade(http::Error err, http::Response& res,
http::Connection& conn, const std::string& key);
/**
* @brief Generate a random WebSocket key
*
* @return A 16 char WebSocket key
*/
static std::vector<char> generate_key();
/**
* @brief Use a HTTP Client to connect to a WebSocket destination
*
* @param client The HTTP client
* @param[in] dest The destination
* @param[in] callback The connect callback
*/
static void connect(http::Basic_client& client,
uri::URI dest,
Connect_handler callback);
/**
* @brief Creates a request handler on heap.
*
* @param[in] on_connect On connect handler
* @param[in] on_accept On accept (optional)
*
* @return A Request handler for a http::Server
*/
static http::Server::Request_handler
create_request_handler(Connect_handler on_connect,
Accept_handler on_accept = nullptr);
/**
* @brief Creates a response handler on heap.
*
* @param[in] on_connect On connect handler
* @param[in] key The WebSocket key sent in outgoing HTTP header
*
* @return A Response handler for a http::Client
*/
static http::Basic_client::Response_handler
create_response_handler(Connect_handler on_connect, std::string key);
void write(const char* buffer, size_t len, op_code = op_code::TEXT);
void write(Stream::buffer_t, op_code = op_code::TEXT);
void write(const std::string& text)
{
write(text.c_str(), text.size(), op_code::TEXT);
}
bool ping(const char* buffer, size_t len, Timer::duration_t timeout)
{
ping_timer.start(timeout);
return write_opcode(op_code::PING, buffer, len);
}
bool ping(Timer::duration_t timeout)
{ return ping(nullptr, 0, timeout); }
//void ping(Stream::buffer_t, Timer::duration_t timeout);
// close the websocket
void close(uint16_t reason = 1000);
void reset_callbacks();
// user callbacks
close_func on_close = nullptr;
error_func on_error = nullptr;
read_func on_read = nullptr;
ping_func on_ping = {this, &WebSocket::default_on_ping};
pong_func on_pong = nullptr;
pong_timeout_func on_pong_timeout = nullptr;
bool is_alive() const noexcept {
return this->stream != nullptr;
}
bool is_client() const noexcept {
return this->clientside;
}
const auto& get_connection() const noexcept {
return this->stream;
}
// op code to string
const char* to_string(op_code code);
// string description for status codes
static const char* status_code(uint16_t code);
std::string to_string() const {
return stream->to_string();
}
int get_cpuid() const noexcept {
return stream->get_cpuid();
}
// 0 == unlimited
void set_max_message_size(uint32_t sz) noexcept {
max_msg_size = sz;
}
size_t serialize_to(void* p) const /*override*/;
/* Create connection from binary data */
static std::pair<WebSocket_ptr, size_t> deserialize_from(const void*);
WebSocket(net::Stream_ptr, bool);
~WebSocket() {
assert(m_busy == false && "Cannot delete stream while in its call stack");
}
private:
net::Stream_ptr stream;
Timer ping_timer{{this, &WebSocket::pong_timeout}};
Message_ptr message;
uint32_t max_msg_size;
bool clientside;
bool m_busy = false;
uint16_t m_deferred_close = 0;
WebSocket(const WebSocket&) = delete;
WebSocket(WebSocket&&) = delete;
WebSocket& operator= (const WebSocket&) = delete;
WebSocket& operator= (WebSocket&&) = delete;
void read_data(Stream::buffer_t);
bool write_opcode(op_code code, const char*, size_t);
void failure(const std::string&);
void close_callback_once();
size_t create_message(const uint8_t*, size_t len);
void finalize_message();
bool default_on_ping(const char*, size_t)
{ return true; }
void pong_timeout()
{
if (on_pong_timeout)
on_pong_timeout(*this);
else
this->close(1000);
}
};
using WebSocket_ptr = WebSocket::WebSocket_ptr;
} // http
#endif
<commit_msg>ws: added missing interface used by websocket uniitest<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef NET_WS_WEBSOCKET_HPP
#define NET_WS_WEBSOCKET_HPP
#include "header.hpp"
#include <net/http/server.hpp>
#include <net/http/basic_client.hpp>
#include <memory>
#include <stdexcept>
#include <vector>
namespace net {
struct WS_error : public std::runtime_error {
using base = std::runtime_error;
using base::base;
};
class WebSocket {
public:
class Message {
public:
using Data = std::vector<uint8_t>;
using Data_it = Data::iterator;
using Data_cit = Data::const_iterator;
auto extract_vector() noexcept {
return std::move(data_);
}
auto extract_shared_vector() {
return std::make_shared<std::vector<uint8_t>> (std::move(data_));
}
std::string to_string() const
{ return std::string(data(), size()); }
size_t size() const noexcept
{ return data_.size(); }
Data_it begin() noexcept
{ return data_.begin(); }
Data_it end() noexcept
{ return data_.end(); }
Data_cit cbegin() const noexcept
{ return data_.begin(); }
Data_cit cend() const noexcept
{ return data_.end(); }
const char* data() const noexcept
{ return (const char*) data_.data(); }
char* data() noexcept
{ return (char*) data_.data(); }
Message(const uint8_t* data, size_t len)
{
const auto* wsh = (ws_header*) data;
// setup initial header
const size_t hdr_bytes = std::min((size_t) wsh->header_length(), len);
std::memcpy(header_.data(), data, hdr_bytes);
this->header_length = hdr_bytes;
// move forward in buffer
data += hdr_bytes; len -= hdr_bytes;
// if the header became complete, reserve data
if (this->header_complete()) {
data_.reserve(header().data_length());
}
// append any remaining data
this->append(data, len);
}
size_t append(const uint8_t* data, size_t len);
bool is_complete() const noexcept
{ return header_complete() && data_.size() == header().data_length(); }
const ws_header& header() const noexcept
{ return *(ws_header*) header_.data(); }
op_code opcode() const noexcept
{ return header().opcode(); }
void unmask() noexcept
{
if (header().is_masked())
writable_header().masking_algorithm(this->data());
}
private:
Data data_;
std::array<uint8_t, 15> header_;
uint8_t header_length = 0;
inline bool header_complete() const noexcept {
return header_length >= 2 && header_length >= header().header_length();
}
ws_header& writable_header()
{ return *(ws_header*) header_.data(); }
}; // < class Message
using Message_ptr = std::unique_ptr<Message>;
using WebSocket_ptr = std::unique_ptr<WebSocket>;
// When a handshake is established and the WebSocket is created
using Connect_handler = delegate<void(WebSocket_ptr)>;
// Whether to accept the client or not before handshake
using Accept_handler = delegate<bool(net::Socket, std::string)>;
// data read (data, length)
typedef delegate<void(Message_ptr)> read_func;
// closed (status code)
typedef delegate<void(uint16_t)> close_func;
// error (reason)
typedef delegate<void(std::string)> error_func;
// ping (return value is whether to return pong or not, default yes)
typedef delegate<bool(const char* data, size_t len)> ping_func;
// pong recv
typedef delegate<void(const char* data, size_t len)> pong_func;
// if a ping resulted in a timeout
typedef delegate<void(WebSocket& ws)> pong_timeout_func;
/**
* @brief Upgrade a HTTP Request to a WebSocket connection.
*
* @param req The HTTP request
* @param writer The HTTP response writer
*
* @return A WebSocket_ptr, or nullptr if upgrade fails.
*/
static WebSocket_ptr upgrade(http::Request& req, http::Response_writer& writer);
/**
* @brief Upgrade a HTTP Response to a WebSocket connection.
*
* @param[in] err The HTTP error
* @param res The HTTP response
* @param conn The HTTP connection
* @param key The WS key sent in the HTTP request
*
* @return A WebSocket_ptr, or nullptr if upgrade fails.
*/
static WebSocket_ptr upgrade(http::Error err, http::Response& res,
http::Connection& conn, const std::string& key);
/**
* @brief Generate a random WebSocket key
*
* @return A 16 char WebSocket key
*/
static std::vector<char> generate_key();
/**
* @brief Use a HTTP Client to connect to a WebSocket destination
*
* @param client The HTTP client
* @param[in] dest The destination
* @param[in] callback The connect callback
*/
static void connect(http::Basic_client& client,
uri::URI dest,
Connect_handler callback);
/**
* @brief Creates a request handler on heap.
*
* @param[in] on_connect On connect handler
* @param[in] on_accept On accept (optional)
*
* @return A Request handler for a http::Server
*/
static http::Server::Request_handler
create_request_handler(Connect_handler on_connect,
Accept_handler on_accept = nullptr);
/**
* @brief Creates a response handler on heap.
*
* @param[in] on_connect On connect handler
* @param[in] key The WebSocket key sent in outgoing HTTP header
*
* @return A Response handler for a http::Client
*/
static http::Basic_client::Response_handler
create_response_handler(Connect_handler on_connect, std::string key);
void write(const char* buffer, size_t len, op_code = op_code::TEXT);
void write(Stream::buffer_t, op_code = op_code::TEXT);
void write(const std::string& text)
{
write(text.c_str(), text.size(), op_code::TEXT);
}
void write(const std::shared_ptr<std::vector<unsigned char>> data)
{
write((char *)data->data(),data->size());
}
bool ping(const char* buffer, size_t len, Timer::duration_t timeout)
{
ping_timer.start(timeout);
return write_opcode(op_code::PING, buffer, len);
}
bool ping(Timer::duration_t timeout)
{ return ping(nullptr, 0, timeout); }
//void ping(Stream::buffer_t, Timer::duration_t timeout);
// close the websocket
void close(uint16_t reason = 1000);
void reset_callbacks();
// user callbacks
close_func on_close = nullptr;
error_func on_error = nullptr;
read_func on_read = nullptr;
ping_func on_ping = {this, &WebSocket::default_on_ping};
pong_func on_pong = nullptr;
pong_timeout_func on_pong_timeout = nullptr;
bool is_alive() const noexcept {
return this->stream != nullptr;
}
bool is_client() const noexcept {
return this->clientside;
}
const auto& get_connection() const noexcept {
return this->stream;
}
// op code to string
const char* to_string(op_code code);
// string description for status codes
static const char* status_code(uint16_t code);
std::string to_string() const {
return stream->to_string();
}
int get_cpuid() const noexcept {
return stream->get_cpuid();
}
// 0 == unlimited
void set_max_message_size(uint32_t sz) noexcept {
max_msg_size = sz;
}
size_t serialize_to(void* p) const /*override*/;
/* Create connection from binary data */
static std::pair<WebSocket_ptr, size_t> deserialize_from(const void*);
WebSocket(net::Stream_ptr, bool);
~WebSocket() {
assert(m_busy == false && "Cannot delete stream while in its call stack");
}
private:
net::Stream_ptr stream;
Timer ping_timer{{this, &WebSocket::pong_timeout}};
Message_ptr message;
uint32_t max_msg_size;
bool clientside;
bool m_busy = false;
uint16_t m_deferred_close = 0;
WebSocket(const WebSocket&) = delete;
WebSocket(WebSocket&&) = delete;
WebSocket& operator= (const WebSocket&) = delete;
WebSocket& operator= (WebSocket&&) = delete;
void read_data(Stream::buffer_t);
bool write_opcode(op_code code, const char*, size_t);
void failure(const std::string&);
void close_callback_once();
size_t create_message(const uint8_t*, size_t len);
void finalize_message();
bool default_on_ping(const char*, size_t)
{ return true; }
void pong_timeout()
{
if (on_pong_timeout)
on_pong_timeout(*this);
else
this->close(1000);
}
};
using WebSocket_ptr = WebSocket::WebSocket_ptr;
} // http
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <unordered_map>
#include <chrono>
#include <cstdlib>
#include <vector>
typedef size_t join_single_key_t;
typedef size_t pos_t;
typedef std::unordered_multimap<join_single_key_t, pos_t> hmap_t;
int main() {
// Initialize mmup
hmap_t mmup;
std::vector<size_t> randVals;
//generate random values
std::srand(std::time(0));
for (size_t i = 0; i < 10000; ++i) {
randVals.push_back(std::rand());
}
auto t0 = std::chrono::high_resolution_clock::now();
// TODO create different random vals for the key and the value
for (auto val : randVals) {
mmup.insert(hmap_t::value_type(val, val));
}
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << "Ticks was: " << (t1 - t0).count() << std::endl;
return 0;
}
<commit_msg>First working benchmark.<commit_after>#include <iostream>
#include <unordered_map>
#include <chrono>
#include <cstdlib>
#include <vector>
#define NUM_VALS 1000
typedef size_t join_single_key_t;
typedef size_t pos_t;
typedef std::unordered_multimap<join_single_key_t, pos_t> hmap_t;
int main() {
// Initialize mmup
hmap_t mmup, mmup2, fresh_mmup;
//generate random values
std::srand(std::time(0));
for (size_t i = 0; i < NUM_VALS; ++i) {
mmup.insert(hmap_t::value_type(std::rand(), std::rand()));
mmup2.insert(hmap_t::value_type(std::rand(), std::rand()));
}
// start the timer
auto t0 = std::chrono::high_resolution_clock::now();
// merge hash maps in fresh hash map
fresh_mmup.insert(mmup.begin(), mmup.end());
fresh_mmup.insert(mmup2.begin(), mmup2.end());
// end the timer
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << "With fresh hash map: " << (t1 - t0).count() << " ticks" << std::endl;
// start timer 2
auto t2 = std::chrono::high_resolution_clock::now();
// merge hash maps with inserting second in first
mmup.insert(mmup2.begin(), mmup2.end());
// end timer 2
auto t3 = std::chrono::high_resolution_clock::now();
std::cout << "With reusing one hash map: " << (t3 - t2).count() << " ticks" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Methcla/Utility/Macros.h"
#include "methcla_tests.hpp"
METHCLA_WITHOUT_WARNINGS_BEGIN
# include <catch.hpp>
METHCLA_WITHOUT_WARNINGS_END
#include "Methcla/Utility/MessageQueue.hpp"
#include "Methcla/Utility/Semaphore.hpp"
#include <atomic>
#include <mutex>
#include <thread>
static std::string gInputFileDirectory = "tests/input";
static std::string gOutputFileDirectory = "tests/output";
void Methcla::Tests::initialize(std::string inputFileDirectory, std::string outputFileDirectory)
{
gInputFileDirectory = inputFileDirectory;
gOutputFileDirectory = outputFileDirectory;
}
std::string Methcla::Tests::inputFile(const std::string& name)
{
return gInputFileDirectory + "/" + name;
}
std::string Methcla::Tests::outputFile(const std::string& name)
{
return gOutputFileDirectory + "/" + name;
}
namespace test_Methcla_Utility_Worker
{
struct Command
{
void perform() { }
};
};
namespace Methcla { namespace Test {
class Log
{
public:
Log()
: m_lock(s_mutex)
{ }
template <typename T> Log& operator<<(const T& x)
{
#if DEBUG
std::cerr << x;
#endif
return *this;
}
private:
std::lock_guard<std::mutex> m_lock;
static std::mutex s_mutex;
};
std::mutex Log::s_mutex;
} }
TEST_CASE("Methcla/Utility/Semaphore/constructor", "Test constructor.")
{
for (size_t n : { 1, 2, 3, 10, 20, 50, 100, 1000, 1024, 10000 }) {
Methcla::Utility::Semaphore sem(n);
size_t count(0);
for (size_t i=0; i < n; i++) {
sem.wait();
count++;
}
REQUIRE(count == n);
}
}
TEST_CASE("Methcla/Utility/Semaphore/post", "Test post/wait.")
{
for (size_t n : { 1, 2, 3, 10, 20, 50, 100, 1000, 1024, 10000 }) {
Methcla::Utility::Semaphore sem;
std::atomic<size_t> count(0);
std::thread thread([&](){
for (size_t i=0; i < n; i++) {
count++;
sem.post();
}
});
for (size_t i=0; i < n; i++) {
sem.wait();
}
REQUIRE(count.load() == n);
thread.join();
}
}
TEST_CASE("Methcla/Utility/Worker", "Check for queue overflow.")
{
using test_Methcla_Utility_Worker::Command;
const size_t queueSize = 1024;
Methcla::Utility::Worker<Command> worker(queueSize, false);
for (size_t i=0; i < worker.maxCapacity(); i++) {
worker.sendToWorker(Command());
}
REQUIRE_THROWS(worker.sendToWorker(Command()));
}
namespace test_Methcla_Utility_WorkerThread
{
struct Command
{
void perform()
{
(*m_count)++;
m_sem->post();
Methcla::Test::Log() << "POST " << m_id << "\n";
}
size_t m_id;
std::atomic<size_t>* m_count;
Methcla::Utility::Semaphore* m_sem;
};
};
TEST_CASE("Methcla/Utility/WorkerThread", "Check that all commands pushed to a worker thread are executed.")
{
using test_Methcla_Utility_WorkerThread::Command;
const size_t queueSize = 16;
for (size_t threadCount=1; threadCount <= 4; threadCount++) {
Methcla::Test::Log() << "threads " << threadCount << "\n";
Methcla::Utility::WorkerThread<Command> worker(queueSize, threadCount);
std::atomic<size_t> count(0);
Methcla::Utility::Semaphore sem;
for (size_t i=0; i < worker.maxCapacity(); i++) {
Command cmd;
cmd.m_id = i;
cmd.m_count = &count;
cmd.m_sem = &sem;
worker.sendToWorker(cmd);
}
for (size_t i=0; i < worker.maxCapacity(); i++) {
sem.wait();
Methcla::Test::Log() << "WAIT " << i << " " << count.load() << "\n";
}
REQUIRE(count.load() == worker.maxCapacity());
}
}
<commit_msg>Use Catch logging macro instead of writing to std::cerr<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Methcla/Utility/Macros.h"
#include "methcla_tests.hpp"
METHCLA_WITHOUT_WARNINGS_BEGIN
# include <catch.hpp>
METHCLA_WITHOUT_WARNINGS_END
#include "Methcla/Utility/MessageQueue.hpp"
#include "Methcla/Utility/Semaphore.hpp"
#include <atomic>
#include <mutex>
#include <thread>
static std::string gInputFileDirectory = "tests/input";
static std::string gOutputFileDirectory = "tests/output";
void Methcla::Tests::initialize(std::string inputFileDirectory, std::string outputFileDirectory)
{
gInputFileDirectory = inputFileDirectory;
gOutputFileDirectory = outputFileDirectory;
}
std::string Methcla::Tests::inputFile(const std::string& name)
{
return gInputFileDirectory + "/" + name;
}
std::string Methcla::Tests::outputFile(const std::string& name)
{
return gOutputFileDirectory + "/" + name;
}
namespace test_Methcla_Utility_Worker
{
struct Command
{
void perform() { }
};
};
namespace Methcla { namespace Test {
// Accesses to Catch log need to be synchronized.
class Log
{
public:
Log()
: m_lock(s_mutex)
{ }
template <typename T> Log& operator<<(const T& x)
{
INFO(x);
return *this;
}
private:
std::lock_guard<std::mutex> m_lock;
static std::mutex s_mutex;
};
std::mutex Log::s_mutex;
} }
TEST_CASE("Methcla/Utility/Semaphore/constructor", "Test constructor.")
{
for (size_t n : { 1, 2, 3, 10, 20, 50, 100, 1000, 1024, 10000 }) {
Methcla::Utility::Semaphore sem(n);
size_t count(0);
for (size_t i=0; i < n; i++) {
sem.wait();
count++;
}
REQUIRE(count == n);
}
}
TEST_CASE("Methcla/Utility/Semaphore/post", "Test post/wait.")
{
for (size_t n : { 1, 2, 3, 10, 20, 50, 100, 1000, 1024, 10000 }) {
Methcla::Utility::Semaphore sem;
std::atomic<size_t> count(0);
std::thread thread([&](){
for (size_t i=0; i < n; i++) {
count++;
sem.post();
}
});
for (size_t i=0; i < n; i++) {
sem.wait();
}
REQUIRE(count.load() == n);
thread.join();
}
}
TEST_CASE("Methcla/Utility/Worker", "Check for queue overflow.")
{
using test_Methcla_Utility_Worker::Command;
const size_t queueSize = 1024;
Methcla::Utility::Worker<Command> worker(queueSize, false);
for (size_t i=0; i < worker.maxCapacity(); i++) {
worker.sendToWorker(Command());
}
REQUIRE_THROWS(worker.sendToWorker(Command()));
}
namespace test_Methcla_Utility_WorkerThread
{
struct Command
{
void perform()
{
(*m_count)++;
m_sem->post();
Methcla::Test::Log() << "POST " << m_id;
}
size_t m_id;
std::atomic<size_t>* m_count;
Methcla::Utility::Semaphore* m_sem;
};
};
TEST_CASE("Methcla/Utility/WorkerThread", "Check that all commands pushed to a worker thread are executed.")
{
using test_Methcla_Utility_WorkerThread::Command;
const size_t queueSize = 16;
for (size_t threadCount=1; threadCount <= 4; threadCount++) {
Methcla::Test::Log() << "threads " << threadCount;
Methcla::Utility::WorkerThread<Command> worker(queueSize, threadCount);
std::atomic<size_t> count(0);
Methcla::Utility::Semaphore sem;
for (size_t i=0; i < worker.maxCapacity(); i++) {
Command cmd;
cmd.m_id = i;
cmd.m_count = &count;
cmd.m_sem = &sem;
worker.sendToWorker(cmd);
}
for (size_t i=0; i < worker.maxCapacity(); i++) {
sem.wait();
Methcla::Test::Log() << "WAIT " << i << " " << count.load();
}
REQUIRE(count.load() == worker.maxCapacity());
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace search::lp;
using namespace search;
namespace UnitTests
{
TEST_CLASS(test_lifelong_planning)
{
public:
TEST_METHOD(cost_function)
{
Assert::AreEqual(1, cost());
}
TEST_METHOD(infinity_function)
{
Assert::AreEqual(2147483647, infinity());
}
TEST_METHOD(key)
{
using Key = LpState::Key;
Key key{ 42, 99 };
Assert::AreEqual(42, key.first);
Assert::AreEqual(99, key.second);
Assert::IsTrue(Key{ 1, 2 } < Key{ 2, 1 });
Assert::IsTrue(Key{ 2, 1 } < Key{ 2, 2 });
Assert::IsTrue(Key{ 2, 2 } == Key{ 2, 2 });
}
TEST_METHOD(lp_coordinate)
{
Coordinate c{ 42, 99 };
Assert::AreEqual(42, c.x);
Assert::AreEqual(99, c.y);
Assert::IsTrue(Coordinate{ 1, 1 } == Coordinate{ 1, 1 });
Assert::IsTrue(Coordinate{ 1, 2 } != Coordinate{ 1, 1 });
//test neighbour
{
Coordinate c{ 1, 1 };
decltype(c.neighbours()) expect =
{
{ 0, 0 }, { 1, 0 }, { 2, 0 },
{ 0, 1 }, /* */ { 2, 1 },
{ 0, 2 }, { 1, 2 }, { 2, 2 }
};
for (auto i = 1; i != expect.size(); ++i)
Assert::IsTrue(expect[i] == c.neighbours()[i]);
}
}
TEST_METHOD(lp_manhattan)
{
Assert::AreEqual(39, LpManhattanDistance{ { 39, 39 } }({ 0, 0 }));
Assert::AreEqual(39, LpManhattanDistance{ { 38, 39 } }({ 0, 0 }));
Assert::AreEqual(38, LpManhattanDistance{ { 38, 38 } }({ 0, 0 }));
}
TEST_METHOD(lp_euclidean_distance)
{
Assert::AreEqual(100, LpEuclideanDistance{ { 60, 80 } }({ 0, 0 }));
Assert::AreEqual(50, LpEuclideanDistance{ { 30, 40 } }({ 0, 0 }));
Assert::AreEqual(14, LpEuclideanDistance{ { 10, 10 } }({ 0, 0 }));
}
TEST_METHOD(lp_state)
{
auto ls = LpState{ { 3, 4 }, 6, 7 };
Assert::AreEqual(3, ls.coordinate.x);
Assert::AreEqual(4, ls.coordinate.y);
Assert::AreEqual(6, ls.g);
Assert::AreEqual(7, ls.r);
using Key = LpState::Key;
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpManhattanDistance{ { 39, 29 } }));
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpManhattanDistance{ { 6, 7 } }));
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpEuclideanDistance{ { 39, 29 } }));
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpEuclideanDistance{ { 6, 7 } }));
}
};
}<commit_msg>Tested Matrix.<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace search::lp;
using namespace search;
namespace UnitTests
{
TEST_CLASS(test_lifelong_planning)
{
public:
using Key = LpState::Key;
TEST_METHOD(cost_function)
{
Assert::AreEqual(1, cost());
}
TEST_METHOD(infinity_function)
{
Assert::AreEqual(2147483647, infinity());
}
TEST_METHOD(key)
{
Key key{ 42, 99 };
Assert::AreEqual(42, key.first);
Assert::AreEqual(99, key.second);
Assert::IsTrue(Key{ 1, 2 } < Key{ 2, 1 });
Assert::IsTrue(Key{ 2, 1 } < Key{ 2, 2 });
Assert::IsTrue(Key{ 2, 2 } == Key{ 2, 2 });
}
TEST_METHOD(lp_coordinate)
{
Coordinate c{ 42, 99 };
Assert::AreEqual(42, c.x);
Assert::AreEqual(99, c.y);
Assert::IsTrue(Coordinate{ 1, 1 } == Coordinate{ 1, 1 });
Assert::IsTrue(Coordinate{ 1, 2 } != Coordinate{ 1, 1 });
//test neighbour
{
Coordinate c{ 1, 1 };
decltype(c.neighbours()) expect =
{
{ 0, 0 }, { 1, 0 }, { 2, 0 },
{ 0, 1 }, /* */ { 2, 1 },
{ 0, 2 }, { 1, 2 }, { 2, 2 }
};
for (auto i = 1; i != expect.size(); ++i)
Assert::IsTrue(expect[i] == c.neighbours()[i]);
}
}
TEST_METHOD(lp_manhattan)
{
Assert::AreEqual(39, LpManhattanDistance{ { 39, 39 } }({ 0, 0 }));
Assert::AreEqual(39, LpManhattanDistance{ { 38, 39 } }({ 0, 0 }));
Assert::AreEqual(38, LpManhattanDistance{ { 38, 38 } }({ 0, 0 }));
}
TEST_METHOD(lp_euclidean_distance)
{
Assert::AreEqual(100, LpEuclideanDistance{ { 60, 80 } }({ 0, 0 }));
Assert::AreEqual(50, LpEuclideanDistance{ { 30, 40 } }({ 0, 0 }));
Assert::AreEqual(14, LpEuclideanDistance{ { 10, 10 } }({ 0, 0 }));
}
TEST_METHOD(lp_state)
{
auto ls = LpState{ { 3, 4 }, 6, 7 };
Assert::AreEqual(3, ls.coordinate.x);
Assert::AreEqual(4, ls.coordinate.y);
Assert::AreEqual(6, ls.g);
Assert::AreEqual(7, ls.r);
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpManhattanDistance{ { 39, 29 } }));
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpManhattanDistance{ { 6, 7 } }));
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpEuclideanDistance{ { 39, 29 } }));
Assert::IsTrue(Key{ 6, 6 } == ls.key(LpEuclideanDistance{ { 6, 7 } }));
}
TEST_METHOD(matrix_class)
{
Matrix matrix{ 10, 10 };
//for x = 0, y = 0
{
Coordinate c = { 0, 0 };
Assert::AreEqual(0, matrix.at(c).g);
Assert::AreEqual(0, matrix.at(c).r);
Assert::IsTrue(Coordinate{ 0, 0 } == matrix.at(c).coordinate);
Assert::IsTrue(Key{ 0, 0 } == matrix.at(c).key(LpEuclideanDistance{ { 6, 7 } }));
}
//for x = 2, y = 4
{
Coordinate c = { 2, 4 };
Assert::AreEqual(0, matrix.at(c).g);
Assert::AreEqual(0, matrix.at(c).r);
Assert::IsTrue(Coordinate{ 0, 0 } == matrix.at(c).coordinate);
Assert::IsTrue(Key{ 0, 0 } == matrix.at(c).key(LpEuclideanDistance{ { 6, 7 } }));
}
}
};
}<|endoftext|> |
<commit_before>/*************************************************************************/
/* freedesktop_screensaver.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "freedesktop_screensaver.h"
#ifdef DBUS_ENABLED
#include "core/config/project_settings.h"
#include <dbus/dbus.h>
#define BUS_OBJECT_NAME "org.freedesktop.ScreenSaver"
#define BUS_OBJECT_PATH "/org/freedesktop/ScreenSaver"
#define BUS_INTERFACE "org.freedesktop.ScreenSaver"
void FreeDesktopScreenSaver::inhibit() {
if (unsupported) {
return;
}
DBusError error;
dbus_error_init(&error);
DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
unsupported = true;
return;
}
String app_name_string = ProjectSettings::get_singleton()->get("application/config/name");
CharString app_name_utf8 = app_name_string.utf8();
const char *app_name = app_name_string.is_empty() ? "Godot Engine" : app_name_utf8.get_data();
const char *reason = "Running Godot Engine project";
DBusMessage *message = dbus_message_new_method_call(
BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE,
"Inhibit");
dbus_message_append_args(
message,
DBUS_TYPE_STRING, &app_name,
DBUS_TYPE_STRING, &reason,
DBUS_TYPE_INVALID);
DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error);
dbus_message_unref(message);
if (dbus_error_is_set(&error)) {
dbus_connection_unref(bus);
unsupported = false;
return;
}
DBusMessageIter reply_iter;
dbus_message_iter_init(reply, &reply_iter);
dbus_message_iter_get_basic(&reply_iter, &cookie);
print_verbose("FreeDesktopScreenSaver: Acquired screensaver inhibition cookie: " + uitos(cookie));
dbus_message_unref(reply);
dbus_connection_unref(bus);
}
void FreeDesktopScreenSaver::uninhibit() {
if (unsupported) {
return;
}
DBusError error;
dbus_error_init(&error);
DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
unsupported = true;
return;
}
DBusMessage *message = dbus_message_new_method_call(
BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE,
"UnInhibit");
dbus_message_append_args(
message,
DBUS_TYPE_UINT32, &cookie,
DBUS_TYPE_INVALID);
DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error);
if (dbus_error_is_set(&error)) {
dbus_connection_unref(bus);
unsupported = true;
return;
}
print_verbose("FreeDesktopScreenSaver: Released screensaver inhibition cookie: " + uitos(cookie));
dbus_message_unref(message);
dbus_message_unref(reply);
dbus_connection_unref(bus);
}
#endif // DBUS_ENABLED
<commit_msg>free dbus errors when inhibiting freedesktop screensaver (prevents small memory leak)<commit_after>/*************************************************************************/
/* freedesktop_screensaver.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "freedesktop_screensaver.h"
#ifdef DBUS_ENABLED
#include "core/config/project_settings.h"
#include <dbus/dbus.h>
#define BUS_OBJECT_NAME "org.freedesktop.ScreenSaver"
#define BUS_OBJECT_PATH "/org/freedesktop/ScreenSaver"
#define BUS_INTERFACE "org.freedesktop.ScreenSaver"
void FreeDesktopScreenSaver::inhibit() {
if (unsupported) {
return;
}
DBusError error;
dbus_error_init(&error);
DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
dbus_error_free(&error);
unsupported = true;
return;
}
String app_name_string = ProjectSettings::get_singleton()->get("application/config/name");
CharString app_name_utf8 = app_name_string.utf8();
const char *app_name = app_name_string.is_empty() ? "Godot Engine" : app_name_utf8.get_data();
const char *reason = "Running Godot Engine project";
DBusMessage *message = dbus_message_new_method_call(
BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE,
"Inhibit");
dbus_message_append_args(
message,
DBUS_TYPE_STRING, &app_name,
DBUS_TYPE_STRING, &reason,
DBUS_TYPE_INVALID);
DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error);
dbus_message_unref(message);
if (dbus_error_is_set(&error)) {
dbus_error_free(&error);
dbus_connection_unref(bus);
unsupported = false;
return;
}
DBusMessageIter reply_iter;
dbus_message_iter_init(reply, &reply_iter);
dbus_message_iter_get_basic(&reply_iter, &cookie);
print_verbose("FreeDesktopScreenSaver: Acquired screensaver inhibition cookie: " + uitos(cookie));
dbus_message_unref(reply);
dbus_connection_unref(bus);
}
void FreeDesktopScreenSaver::uninhibit() {
if (unsupported) {
return;
}
DBusError error;
dbus_error_init(&error);
DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
dbus_error_free(&error);
unsupported = true;
return;
}
DBusMessage *message = dbus_message_new_method_call(
BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE,
"UnInhibit");
dbus_message_append_args(
message,
DBUS_TYPE_UINT32, &cookie,
DBUS_TYPE_INVALID);
DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error);
if (dbus_error_is_set(&error)) {
dbus_error_free(&error);
dbus_connection_unref(bus);
unsupported = true;
return;
}
print_verbose("FreeDesktopScreenSaver: Released screensaver inhibition cookie: " + uitos(cookie));
dbus_message_unref(message);
dbus_message_unref(reply);
dbus_connection_unref(bus);
}
#endif // DBUS_ENABLED
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "common/RhoPort.h"
#include "ext/rho/rhoruby.h"
#include "rubyext/WebView.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "MainWindowImpl.h"
using namespace std;
using namespace rho;
extern "C" {
void rho_conf_show_log()
{
CMainWindow::getInstance()->logCommand();
}
void rho_net_impl_network_indicator(int active)
{
//TODO: rho_net_impl_network_indicator
RAWLOGC_INFO("RhodesImpl", "rho_net_impl_network_indicator() has no implementation in RhoSimulator.");
}
void rho_map_location(char* query)
{
String url = "http://maps.google.com/?";
url += query;
rho_webview_navigate(url.c_str(), 0);
}
void rho_appmanager_load( void* httpContext, char* szQuery)
{
//TODO: rho_appmanager_load
RAWLOGC_INFO("RhodesImpl", "rho_appmanager_load() has no implementation in RhoSimulator.");
}
int rho_net_ping_network(const char* szHost)
{
//TODO: rho_net_ping_network
RAWLOGC_INFO("RhodesImpl", "rho_net_ping_network() has no implementation in RhoSimulator.");
return 1;
}
void parseHttpProxyURI(const rho::String &http_proxy)
{
// http://<login>:<passwod>@<host>:<port>
const char *default_port = "8080";
if (http_proxy.length() < 8) {
RAWLOGC_ERROR("RhodesImpl", "invalid http proxy url");
return;
}
int index = http_proxy.find("http://", 0, 7);
if (index == string::npos) {
RAWLOGC_ERROR("RhodesImpl", "http proxy url should starts with \"http://\"");
return;
}
index = 7;
enum {
ST_START,
ST_LOGIN,
ST_PASSWORD,
ST_HOST,
ST_PORT,
ST_FINISH
};
String token, login, password, host, port;
char c, state = ST_START, prev_state = state;
int length = http_proxy.length();
for (int i = index; i < length; i++) {
c = http_proxy[i];
switch (state) {
case ST_START:
if (c == '@') {
prev_state = state; state = ST_HOST;
} else if (c == ':') {
prev_state = state; state = ST_PASSWORD;
} else {
token +=c;
state = ST_HOST;
}
break;
case ST_HOST:
if (c == ':') {
host = token; token.clear();
prev_state = state; state = ST_PORT;
} else if (c == '@') {
host = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
host = token; token.clear();
}
}
break;
case ST_PORT:
if (c == '@') {
port = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
port = token; token.clear();
}
}
break;
case ST_LOGIN:
if (prev_state == ST_PORT || prev_state == ST_HOST) {
login = host; host.clear();
password = port; port.clear();
prev_state = state; state = ST_HOST;
token += c;
} else {
token += c;
if (i == (length - 1)) {
login = token; token.clear();
}
}
break;
case ST_PASSWORD:
if (c == '@') {
password = token; token.clear();
prev_state = state; state = ST_HOST;
} else {
token += c;
if (i == (length - 1)) {
password = token; token.clear();
}
}
break;
default:
;
}
}
RAWLOGC_INFO("RhodesImpl", "Setting up HTTP proxy:");
RAWLOGC_INFO1("RhodesImpl", "URI: %s", http_proxy.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy login = %s", login.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy password = %s", password.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy host = %s", host.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy port = %s", port.c_str());
if (host.length()) {
RHOCONF().setString ("http_proxy_host", host, false);
if (port.length()){
RHOCONF().setString ("http_proxy_port", port, false);
} else {
RAWLOGC_INFO("RhodesImpl", "there is no proxy port defined");
}
if (login.length())
RHOCONF().setString ("http_proxy_login", login, false);
if (password.length())
RHOCONF().setString ("http_proxy_password", password, false);
} else {
RAWLOGC_ERROR("RhodesImpl", "empty host name in HTTP-proxy URL");
}
}
} //extern "C"
<commit_msg>RhoSim stub for rho_title_change<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "common/RhoPort.h"
#include "ext/rho/rhoruby.h"
#include "rubyext/WebView.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "MainWindowImpl.h"
using namespace std;
using namespace rho;
extern "C" {
void rho_conf_show_log()
{
CMainWindow::getInstance()->logCommand();
}
void rho_title_change(const int tabIndex, const wchar_t* strTitle)
{
//TODO: implement
}
void rho_net_impl_network_indicator(int active)
{
//TODO: rho_net_impl_network_indicator
RAWLOGC_INFO("RhodesImpl", "rho_net_impl_network_indicator() has no implementation in RhoSimulator.");
}
void rho_map_location(char* query)
{
String url = "http://maps.google.com/?";
url += query;
rho_webview_navigate(url.c_str(), 0);
}
void rho_appmanager_load( void* httpContext, char* szQuery)
{
//TODO: rho_appmanager_load
RAWLOGC_INFO("RhodesImpl", "rho_appmanager_load() has no implementation in RhoSimulator.");
}
int rho_net_ping_network(const char* szHost)
{
//TODO: rho_net_ping_network
RAWLOGC_INFO("RhodesImpl", "rho_net_ping_network() has no implementation in RhoSimulator.");
return 1;
}
void parseHttpProxyURI(const rho::String &http_proxy)
{
// http://<login>:<passwod>@<host>:<port>
const char *default_port = "8080";
if (http_proxy.length() < 8) {
RAWLOGC_ERROR("RhodesImpl", "invalid http proxy url");
return;
}
int index = http_proxy.find("http://", 0, 7);
if (index == string::npos) {
RAWLOGC_ERROR("RhodesImpl", "http proxy url should starts with \"http://\"");
return;
}
index = 7;
enum {
ST_START,
ST_LOGIN,
ST_PASSWORD,
ST_HOST,
ST_PORT,
ST_FINISH
};
String token, login, password, host, port;
char c, state = ST_START, prev_state = state;
int length = http_proxy.length();
for (int i = index; i < length; i++) {
c = http_proxy[i];
switch (state) {
case ST_START:
if (c == '@') {
prev_state = state; state = ST_HOST;
} else if (c == ':') {
prev_state = state; state = ST_PASSWORD;
} else {
token +=c;
state = ST_HOST;
}
break;
case ST_HOST:
if (c == ':') {
host = token; token.clear();
prev_state = state; state = ST_PORT;
} else if (c == '@') {
host = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
host = token; token.clear();
}
}
break;
case ST_PORT:
if (c == '@') {
port = token; token.clear();
prev_state = state; state = ST_LOGIN;
} else {
token += c;
if (i == (length - 1)) {
port = token; token.clear();
}
}
break;
case ST_LOGIN:
if (prev_state == ST_PORT || prev_state == ST_HOST) {
login = host; host.clear();
password = port; port.clear();
prev_state = state; state = ST_HOST;
token += c;
} else {
token += c;
if (i == (length - 1)) {
login = token; token.clear();
}
}
break;
case ST_PASSWORD:
if (c == '@') {
password = token; token.clear();
prev_state = state; state = ST_HOST;
} else {
token += c;
if (i == (length - 1)) {
password = token; token.clear();
}
}
break;
default:
;
}
}
RAWLOGC_INFO("RhodesImpl", "Setting up HTTP proxy:");
RAWLOGC_INFO1("RhodesImpl", "URI: %s", http_proxy.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy login = %s", login.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy password = %s", password.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy host = %s", host.c_str());
RAWLOGC_INFO1("RhodesImpl", "HTTP proxy port = %s", port.c_str());
if (host.length()) {
RHOCONF().setString ("http_proxy_host", host, false);
if (port.length()){
RHOCONF().setString ("http_proxy_port", port, false);
} else {
RAWLOGC_INFO("RhodesImpl", "there is no proxy port defined");
}
if (login.length())
RHOCONF().setString ("http_proxy_login", login, false);
if (password.length())
RHOCONF().setString ("http_proxy_password", password, false);
} else {
RAWLOGC_ERROR("RhodesImpl", "empty host name in HTTP-proxy URL");
}
}
} //extern "C"
<|endoftext|> |
<commit_before>#include "bench_util.h"
struct NotPacked {
char c = 'c';
long l = 42;
char a = 'a';
char b = 'b';
int i = 42;
double d = 3.22;
};
struct Packed {
char c = 'c';
long l = 42;
char a = 'a';
char b = 'b';
int i = 42;
double d = 3.22;
} __attribute((packed));
const int qty = 1000000000;
int main (int argc, char** argv)
{
int temp;
Packed pack;
NotPacked npack;
bench::title("Iterating over packed data vs non-packed.");
printf("%d iterations. Packed size : %d bytes, Non-packed size : %d bytes\n",
qty, sizeof(Packed), sizeof(NotPacked));
bench::start();
for (int i = 0; i < qty; ++i) {
temp += npack.c;
temp += npack.l;
temp += npack.a;
temp += npack.b;
temp += npack.i;
temp += npack.d;
bench::clobber();
}
bench::stop("Non-Packed Data");
bench::start();
for (int i = 0; i < qty; ++i) {
temp += pack.c;
temp += pack.l;
temp += pack.a;
temp += pack.b;
temp += pack.i;
temp += pack.d;
bench::clobber();
}
bench::stop("Packed Data");
printf("%d", temp);
return 0;
}
<commit_msg>Examples : Fix warning.<commit_after>#include "bench_util.h"
struct NotPacked {
char c = 'c';
long l = 42;
char a = 'a';
char b = 'b';
int i = 42;
double d = 3.22;
};
struct Packed {
char c = 'c';
long l = 42;
char a = 'a';
char b = 'b';
int i = 42;
double d = 3.22;
} __attribute((packed));
const int qty = 1000000000;
int main (int argc, char** argv)
{
int temp;
Packed pack;
NotPacked npack;
bench::title("Iterating over packed data vs non-packed.");
printf("%d iterations. Packed size : %zu bytes, Non-packed size : %zu bytes\n",
qty, sizeof(Packed), sizeof(NotPacked));
bench::start();
for (int i = 0; i < qty; ++i) {
temp += npack.c;
temp += npack.l;
temp += npack.a;
temp += npack.b;
temp += npack.i;
temp += npack.d;
bench::clobber();
}
bench::stop("Non-Packed Data");
bench::start();
for (int i = 0; i < qty; ++i) {
temp += pack.c;
temp += pack.l;
temp += pack.a;
temp += pack.b;
temp += pack.i;
temp += pack.d;
bench::clobber();
}
bench::stop("Packed Data");
printf("%d", temp);
return 0;
}
<|endoftext|> |
<commit_before>/*
* KDots
* Copyright (c) 2011, 2012, 2014, 2015 Minh Ngo <minh@fedoraproject.org>
*
* 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 AUTHOR ``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 AUTHOR 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 "prioritymap.hpp"
#include <config.hpp>
#include <boost/bimap.hpp>
#include <KDebug>
#include <QFile>
#include <QTextStream>
#include <QStringList>
namespace KDots
{
namespace simpleai
{
typedef boost::bimap<MapElement, QString> MapElementToStrType;
const std::vector<MapElementToStrType::value_type> MAP_ELEMENT_TO_STR_VALUES = {
{MapElement::EM, "EM"},
{MapElement::NM, "NM"},
{MapElement::FI, "FI"},
{MapElement::SE, "SE"},
{MapElement::PF, "PF"},
{MapElement::PS, "PS"},
{MapElement::CU, "CU"}
};
const MapElementToStrType MAP_ELEMENT_TO_STR(MAP_ELEMENT_TO_STR_VALUES.begin(),
MAP_ELEMENT_TO_STR_VALUES.end());
MapData::MapData()
{
}
MapData::MapData(const MapType& map, const Point& current, float priority)
: m_map(map)
, m_current(current)
, m_priority(priority)
{
}
QString MapData::toString() const
{
QString res;
for (const auto& row : m_map)
{
res += "\n{ ";
for(const auto& cell : row)
{
res += MAP_ELEMENT_TO_STR.left.at(cell) + " ";
}
res += "}";
}
res += "\n";
return res;
}
bool MapData::operator==(const MapData& other) const
{
if (m_current != other.m_current)
return false;
if (m_priority != other.m_priority)
return false;
if (other.m_map.size() != m_map.size() || !other.m_map.size() || !m_map.size())
return false;
for (MapType::const_iterator other_itr = other.m_map.begin(),
itr = m_map.begin(), other_e = other.m_map.end();
other_itr != other_e ; ++other_itr, ++itr)
{
if (!std::equal(other_itr->begin(), other_itr->end(), itr->begin()))
return false;
}
return true;
}
bool MapData::operator!=(const MapData& other) const
{
return !(other == *this);
}
MapData PriorityMap::inverse(const MapData& data)
{
const MapType& map = data.m_map;
MapData newData;
MapType& newMap = newData.m_map;
newMap.resize(map.size());
MapType::const_iterator map_i = map.begin();
for (MapType::iterator new_i = newMap.begin(),
new_e = newMap.end();
new_i != new_e; ++new_i, ++map_i)
{
new_i->resize(map_i->size());
std::reverse_copy(map_i->begin(), map_i->end(), new_i->begin());
}
newData.m_priority = data.m_priority;
newData.m_current = {static_cast<int>(map.front().size() - 1 - data.m_current.m_x),
data.m_current.m_y};
return newData;
}
MapData PriorityMap::rotate(const MapData& data)
{
const MapType& map = data.m_map;
MapData newData;
MapType& newMap = newData.m_map;
newMap.resize(map.front().size());
std::for_each(newMap.begin(), newMap.end(), [&map](MapLine& line) {
line.resize(map.size());
});
for (int i = 0, max_i = newMap.size(), j, max_j = map.size(); i != max_i; ++i) //y
{
for (j = 0; j != max_j; ++j) //x
newMap[i][j] = map[max_j - 1 - j][i];
}
newData.m_priority = data.m_priority;
newData.m_current = {static_cast<int>(map.size() - 1 - data.m_current.m_y),
data.m_current.m_x};
return newData;
}
PriorityMap::PriorityMap()
: m_priorityMap(loadMap())
{
}
PriorityMap& PriorityMap::instance()
{
static PriorityMap obj;
return obj;
}
const QVector<MapData>& PriorityMap::priorityMap()
{
return m_priorityMap;
}
QVector<MapData> PriorityMap::loadMap() const
{
QVector<MapData> priorityMap;
QFile file(PLUGINS_DIR "/rules");
file.open(QIODevice::ReadOnly);
QTextStream in(&file);
while (!in.atEnd())
{
const float priority = in.readLine().toFloat();
Point current;
MapType map;
for (int row = 0;; ++row)
{
const QString& line = in.readLine();
if (line[0] == '/')
break;
const QStringList& cells = line.split(' ');
map.push_back(MapLine(cells.size()));
MapLine& lastRow = map.back();
for (int column = 0; column < cells.size(); ++column)
{
const MapElement type = MAP_ELEMENT_TO_STR.right.at(cells[column]);
lastRow[column] = type;
if (type == MapElement::CU)
current = {column, row};
}
}
priorityMap.push_back(MapData(std::move(map), current, priority));
}
priorityMap.reserve(priorityMap.size() * 4);
for (int i = 0, max = priorityMap.size(); i < max; ++i)
{
const MapData& data = priorityMap[i];
const MapData& invertedData = inverse(data);
priorityMap.push_back(invertedData);
MapData newData = data;
for (int j = 0; j < 3; ++j)
{
newData = rotate(newData);
priorityMap.push_back(newData);
const MapData& invertedMap = inverse(newData);
priorityMap.push_back(invertedMap);
}
}
return priorityMap;
}
}
}<commit_msg>A bit more refactoring for the PriorityMap<commit_after>/*
* KDots
* Copyright (c) 2011, 2012, 2014, 2015 Minh Ngo <minh@fedoraproject.org>
*
* 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 AUTHOR ``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 AUTHOR 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 "prioritymap.hpp"
#include <config.hpp>
#include <boost/bimap.hpp>
#include <boost/range/combine.hpp>
#include <KDebug>
#include <QFile>
#include <QTextStream>
#include <QStringList>
namespace KDots
{
namespace simpleai
{
typedef boost::bimap<MapElement, QString> MapElementToStrType;
const std::vector<MapElementToStrType::value_type> MAP_ELEMENT_TO_STR_VALUES = {
{MapElement::EM, "EM"},
{MapElement::NM, "NM"},
{MapElement::FI, "FI"},
{MapElement::SE, "SE"},
{MapElement::PF, "PF"},
{MapElement::PS, "PS"},
{MapElement::CU, "CU"}
};
const MapElementToStrType MAP_ELEMENT_TO_STR(MAP_ELEMENT_TO_STR_VALUES.begin(),
MAP_ELEMENT_TO_STR_VALUES.end());
MapData::MapData()
{
}
MapData::MapData(const MapType& map, const Point& current, float priority)
: m_map(map)
, m_current(current)
, m_priority(priority)
{
}
QString MapData::toString() const
{
QString res;
for (const auto& row : m_map)
{
res += "\n{ ";
for(const auto& cell : row)
{
res += MAP_ELEMENT_TO_STR.left.at(cell) + " ";
}
res += "}";
}
res += "\n";
return res;
}
bool MapData::operator==(const MapData& other) const
{
if (m_current != other.m_current)
return false;
if (m_priority != other.m_priority)
return false;
if (other.m_map.size() != m_map.size() || !other.m_map.size() || !m_map.size())
return false;
for (MapType::const_iterator other_itr = other.m_map.begin(),
itr = m_map.begin(), other_e = other.m_map.end();
other_itr != other_e ; ++other_itr, ++itr)
{
if (!std::equal(other_itr->begin(), other_itr->end(), itr->begin()))
return false;
}
return true;
}
bool MapData::operator!=(const MapData& other) const
{
return !(other == *this);
}
MapData PriorityMap::inverse(const MapData& data)
{
const MapType& map = data.m_map;
MapData newData;
MapType& newMap = newData.m_map;
newMap.resize(map.size());
for (const boost::tuple<const MapLine&, MapLine&>& tup : boost::combine(map, newMap))
{
MapLine& newLine = tup.get<1>();
const MapLine& oldLine = tup.get<0>();
newLine.resize(oldLine.size());
std::reverse_copy(oldLine.begin(), oldLine.end(), newLine.begin());
}
newData.m_priority = data.m_priority;
newData.m_current = {static_cast<int>(map.front().size() - 1 - data.m_current.m_x),
data.m_current.m_y};
return newData;
}
MapData PriorityMap::rotate(const MapData& data)
{
const MapType& map = data.m_map;
MapData newData;
MapType& newMap = newData.m_map;
newMap.resize(map.front().size());
for (MapLine& line : newMap)
line.resize(map.size());
for (int i = 0, max_i = newMap.size(), j, max_j = map.size(); i != max_i; ++i) //y
{
for (j = 0; j != max_j; ++j) //x
newMap[i][j] = map[max_j - 1 - j][i];
}
newData.m_priority = data.m_priority;
newData.m_current = {static_cast<int>(map.size() - 1 - data.m_current.m_y),
data.m_current.m_x};
return newData;
}
PriorityMap::PriorityMap()
: m_priorityMap(loadMap())
{
}
PriorityMap& PriorityMap::instance()
{
static PriorityMap obj;
return obj;
}
const QVector<MapData>& PriorityMap::priorityMap()
{
return m_priorityMap;
}
QVector<MapData> PriorityMap::loadMap() const
{
QVector<MapData> priorityMap;
QFile file(PLUGINS_DIR "/rules");
file.open(QIODevice::ReadOnly);
QTextStream in(&file);
while (!in.atEnd())
{
const float priority = in.readLine().toFloat();
Point current;
MapType map;
for (int row = 0;; ++row)
{
const QString& line = in.readLine();
if (line[0] == '/')
break;
const QStringList& cells = line.split(' ');
map.push_back(MapLine(cells.size()));
MapLine& lastRow = map.back();
for (int column = 0; column < cells.size(); ++column)
{
const MapElement type = MAP_ELEMENT_TO_STR.right.at(cells[column]);
lastRow[column] = type;
if (type == MapElement::CU)
current = {column, row};
}
}
priorityMap.push_back(MapData(std::move(map), current, priority));
}
priorityMap.reserve(priorityMap.size() * 4);
for (int i = 0, max = priorityMap.size(); i < max; ++i)
{
const MapData& data = priorityMap[i];
const MapData& invertedData = inverse(data);
priorityMap.push_back(invertedData);
MapData newData = data;
for (int j = 0; j < 3; ++j)
{
newData = rotate(newData);
priorityMap.push_back(newData);
const MapData& invertedMap = inverse(newData);
priorityMap.push_back(invertedMap);
}
}
return priorityMap;
}
}
}<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Moreau
*
* 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 <core.hpp>
#include <view.hpp>
#include <plugin.hpp>
#include <output.hpp>
#include "view-transform.hpp"
#include "workspace-manager.hpp"
#include <nonstd/make_unique.hpp>
class wayfire_alpha : public wayfire_plugin_t
{
axis_callback axis_cb;
public:
void init(wayfire_config *config)
{
grab_interface->name = "alpha";
grab_interface->abilities_mask = WF_ABILITY_CONTROL_WM;
axis_cb = [=] (wlr_event_pointer_axis* ev)
{
if (!output->activate_plugin(grab_interface))
return;
output->deactivate_plugin(grab_interface);
auto focus = core->get_cursor_focus();
if (!focus)
return;
auto view = core->find_view(focus->get_main_surface());
auto layer = output->workspace->get_view_layer(view);
if (layer == WF_LAYER_BACKGROUND)
return;
if (!view->get_transformer("alpha"))
view->add_transformer(nonstd::make_unique<wf_2D_view> (view), "alpha");
if (ev->orientation == WLR_AXIS_ORIENTATION_VERTICAL)
update_alpha_target(view, ev->delta);
};
auto section = config->get_section("alpha");
auto modifier = section->get_option("modifier", "<alt>");
output->add_axis(modifier, &axis_cb);
}
void update_alpha_target(wayfire_view view, float delta)
{
auto transformer = dynamic_cast<wf_2D_view*> (view->get_transformer("alpha").get());
float alpha = transformer->alpha;
alpha -= delta * 0.003;
if (alpha > 1.0)
alpha = 1.0;
if (alpha == 1.0)
return view->pop_transformer("alpha");
if (alpha < 0)
alpha = 0;
if (transformer->alpha != alpha)
{
transformer->alpha = alpha;
view->damage();
}
}
void fini()
{
output->rem_axis(&axis_cb);
}
};
extern "C"
{
wayfire_plugin_t *newInstance()
{
return new wayfire_alpha();
}
}
<commit_msg>alpha: Don't add transformer in init, add it when updating alpha instead<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Moreau
*
* 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 <core.hpp>
#include <view.hpp>
#include <plugin.hpp>
#include <output.hpp>
#include "view-transform.hpp"
#include "workspace-manager.hpp"
#include <nonstd/make_unique.hpp>
class wayfire_alpha : public wayfire_plugin_t
{
axis_callback axis_cb;
public:
void init(wayfire_config *config)
{
grab_interface->name = "alpha";
grab_interface->abilities_mask = WF_ABILITY_CONTROL_WM;
axis_cb = [=] (wlr_event_pointer_axis* ev)
{
if (!output->activate_plugin(grab_interface))
return;
output->deactivate_plugin(grab_interface);
auto focus = core->get_cursor_focus();
if (!focus)
return;
auto view = core->find_view(focus->get_main_surface());
auto layer = output->workspace->get_view_layer(view);
if (layer == WF_LAYER_BACKGROUND)
return;
if (ev->orientation == WLR_AXIS_ORIENTATION_VERTICAL)
update_alpha_target(view, ev->delta);
};
auto section = config->get_section("alpha");
auto modifier = section->get_option("modifier", "<alt>");
output->add_axis(modifier, &axis_cb);
}
void update_alpha_target(wayfire_view view, float delta)
{
wf_2D_view *transformer;
float alpha;
if (!view->get_transformer("alpha"))
view->add_transformer(nonstd::make_unique<wf_2D_view> (view), "alpha");
transformer = dynamic_cast<wf_2D_view*> (view->get_transformer("alpha").get());
alpha = transformer->alpha;
alpha -= delta * 0.003;
if (alpha > 1.0)
alpha = 1.0;
if (alpha == 1.0)
return view->pop_transformer("alpha");
if (alpha < 0)
alpha = 0;
if (transformer->alpha != alpha)
{
transformer->alpha = alpha;
view->damage();
}
}
void fini()
{
output->rem_axis(&axis_cb);
}
};
extern "C"
{
wayfire_plugin_t *newInstance()
{
return new wayfire_alpha();
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Standard Predicate Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include <ironbee/predicate/standard_predicate.hpp>
#include <ironbee/predicate/call_factory.hpp>
#include <ironbee/predicate/call_helpers.hpp>
#include <ironbee/predicate/functional.hpp>
#include <ironbee/predicate/merge_graph.hpp>
#include <ironbee/predicate/validate.hpp>
using namespace std;
namespace IronBee {
namespace Predicate {
namespace Standard {
namespace {
const string CALL_NAME_ISLITERAL("isLiteral");
//! Scoped Memory Pool Lite
static ScopedMemoryPoolLite s_mpl;
//! True Value
static const Value c_true_value =
Value::create_string(s_mpl, ByteString::create(s_mpl, ""));
//! True literal.
static const node_p c_true(new Literal(c_true_value));
//! False literal.
static const node_p c_false(new Literal());
/**
* Is argument a literal?
**/
class IsLiteral :
public Call
{
public:
//! See Call::name()
const std::string& name() const
{
return CALL_NAME_ISLITERAL;
}
/**
* See Node::transform().
*
* Will replace self with true or false based on child.
**/
bool transform(
MergeGraph& merge_graph,
const CallFactory& call_factory,
Environment environment,
NodeReporter reporter
)
{
node_p me = shared_from_this();
node_p replacement = c_false;
if (children().front()->is_literal()) {
replacement = c_true;
}
merge_graph.replace(me, replacement);
return true;
}
//! See Node::eval_calculate()
void eval_calculate(GraphEvalState&, EvalContext) const
{
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"IsLiteral evaluated. Did you not transform?"
)
);
}
//! See Node::validate().
bool validate(NodeReporter reporter) const
{
return Validate::n_children(reporter, 1);
}
};
/**
* Is argument finished?
**/
class IsFinished :
public Functional::Primary
{
public:
//! Constructor.
IsFinished() : Functional::Primary(0, 1) {}
protected:
//! See Functional::Primary::eval_primary().
void eval_primary(
MemoryManager mm,
const node_cp& me,
boost::any& substate,
NodeEvalState& my_state,
const Functional::value_vec_t& secondary_args,
const NodeEvalState& primary_arg
) const
{
if (primary_arg.is_finished()) {
my_state.finish(c_true_value);
}
}
};
/**
* Is primary argument a list longer than specified length.
**/
class IsLonger :
public Functional::Primary
{
public:
//! Constructor.
IsLonger() : Functional::Primary(0, 2) {}
protected:
//! See Functional::Base::validate_argument().
void validate_argument(
int n,
Value v,
NodeReporter reporter
) const
{
if (n == 0) {
Validate::value_is_type(v, Value::NUMBER, reporter);
}
}
//! See Functional::Primary::eval_primary().
void eval_primary(
MemoryManager mm,
const node_cp& me,
boost::any& substate,
NodeEvalState& my_state,
const Functional::value_vec_t& secondary_args,
const NodeEvalState& primary_arg
) const
{
if (! primary_arg.value()) {
return;
}
if (primary_arg.value().type() != Value::LIST) {
my_state.finish();
return;
}
if (
primary_arg.value().as_list().size() >
size_t(secondary_args[0].as_number())
) {
my_state.finish(c_true_value);
return;
}
if (primary_arg.is_finished()) {
my_state.finish();
}
}
};
/**
* Is argument a list?
**/
class IsList :
public Functional::Primary
{
public:
//! Constructor.
IsList() : Functional::Primary(0, 1) {}
protected:
//! See Functional::Primary::eval_primary().
void eval_primary(
MemoryManager mm,
const node_cp& me,
boost::any& substate,
NodeEvalState& my_state,
const Functional::value_vec_t& secondary_args,
const NodeEvalState& primary_arg
) const
{
if (! primary_arg.value().is_null()) {
if (primary_arg.value().type() == Value::LIST) {
my_state.finish(c_true_value);
}
else {
my_state.finish();
}
}
}
};
} // Anonymous
void load_predicate(CallFactory& to)
{
to
.add<IsLiteral>()
.add("isFinished", Functional::generate<IsFinished>)
.add("isLonger", Functional::generate<IsLonger>)
.add("isList", Functional::generate<IsList>)
;
}
} // Standard
} // Predicate
} // IronBee
<commit_msg>standard_predicate.cpp: Implement predicates FinishSome and FinishAll.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Standard Predicate Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include <ironbee/predicate/standard_predicate.hpp>
#include <ironbee/predicate/call_factory.hpp>
#include <ironbee/predicate/call_helpers.hpp>
#include <ironbee/predicate/functional.hpp>
#include <ironbee/predicate/merge_graph.hpp>
#include <ironbee/predicate/validate.hpp>
using namespace std;
namespace IronBee {
namespace Predicate {
namespace Standard {
namespace {
const string CALL_NAME_ISLITERAL("isLiteral");
const string CALL_FINISH_ALL("finishAll");
const string CALL_FINISH_SOME("finishSome");
//! Scoped Memory Pool Lite
static ScopedMemoryPoolLite s_mpl;
//! True Value
static const Value c_true_value =
Value::create_string(s_mpl, ByteString::create(s_mpl, ""));
//! True literal.
static const node_p c_true(new Literal(c_true_value));
//! False literal.
static const node_p c_false(new Literal());
/**
* Is argument a literal?
**/
class IsLiteral :
public Call
{
public:
//! See Call::name()
const std::string& name() const
{
return CALL_NAME_ISLITERAL;
}
/**
* See Node::transform().
*
* Will replace self with true or false based on child.
**/
bool transform(
MergeGraph& merge_graph,
const CallFactory& call_factory,
Environment environment,
NodeReporter reporter
)
{
node_p me = shared_from_this();
node_p replacement = c_false;
if (children().front()->is_literal()) {
replacement = c_true;
}
merge_graph.replace(me, replacement);
return true;
}
//! See Node::eval_calculate()
void eval_calculate(GraphEvalState&, EvalContext) const
{
BOOST_THROW_EXCEPTION(
einval() << errinfo_what(
"IsLiteral evaluated. Did you not transform?"
)
);
}
//! See Node::validate().
bool validate(NodeReporter reporter) const
{
return Validate::n_children(reporter, 1);
}
};
/**
* Is argument finished?
**/
class IsFinished :
public Functional::Primary
{
public:
//! Constructor.
IsFinished() : Functional::Primary(0, 1) {}
protected:
//! See Functional::Primary::eval_primary().
void eval_primary(
MemoryManager mm,
const node_cp& me,
boost::any& substate,
NodeEvalState& my_state,
const Functional::value_vec_t& secondary_args,
const NodeEvalState& primary_arg
) const
{
if (primary_arg.is_finished()) {
my_state.finish(c_true_value);
}
}
};
/**
* Is primary argument a list longer than specified length.
**/
class IsLonger :
public Functional::Primary
{
public:
//! Constructor.
IsLonger() : Functional::Primary(0, 2) {}
protected:
//! See Functional::Base::validate_argument().
void validate_argument(
int n,
Value v,
NodeReporter reporter
) const
{
if (n == 0) {
Validate::value_is_type(v, Value::NUMBER, reporter);
}
}
//! See Functional::Primary::eval_primary().
void eval_primary(
MemoryManager mm,
const node_cp& me,
boost::any& substate,
NodeEvalState& my_state,
const Functional::value_vec_t& secondary_args,
const NodeEvalState& primary_arg
) const
{
if (! primary_arg.value()) {
return;
}
if (primary_arg.value().type() != Value::LIST) {
my_state.finish();
return;
}
if (
primary_arg.value().as_list().size() >
size_t(secondary_args[0].as_number())
) {
my_state.finish(c_true_value);
return;
}
if (primary_arg.is_finished()) {
my_state.finish();
}
}
};
/**
* Is argument a list?
**/
class IsList :
public Functional::Primary
{
public:
//! Constructor.
IsList() : Functional::Primary(0, 1) {}
protected:
//! See Functional::Primary::eval_primary().
void eval_primary(
MemoryManager mm,
const node_cp& me,
boost::any& substate,
NodeEvalState& my_state,
const Functional::value_vec_t& secondary_args,
const NodeEvalState& primary_arg
) const
{
if (! primary_arg.value().is_null()) {
if (primary_arg.value().type() == Value::LIST) {
my_state.finish(c_true_value);
}
else {
my_state.finish();
}
}
}
};
/**
* Finish with the value of the first child that finishes.
*
* This is unlike OR in that the requirements are less. A node only need
* finish, not finish true.
**/
class FinishSome :
public Call
{
public:
//! See Call:name()
virtual const std::string& name() const;
//! See Node::validate()
virtual bool validate(NodeReporter reporter) const;
/**
* If any node is a literal or transformed to finished,
* this node replaces itself with that node.
*
* @sa See Node::trasform()
*/
virtual bool transform(
MergeGraph& merge_graph,
const CallFactory& call_factory,
Environment environment,
NodeReporter reporter
);
protected:
virtual void eval_calculate(
GraphEvalState& graph_eval_state,
EvalContext context
) const;
};
/**
* Finish with a list of the values. This finishes when all values are finished.
*
* This is effectively list.
**/
class FinishAll :
public Call
{
public:
//! See Call:name()
virtual const std::string& name() const;
//! See Node::validate()
virtual bool validate(NodeReporter reporter) const;
/**
* If all nodesa are a literal or transformed to finished,
* this node replaces itself with a constant list of those values.
*
* @sa See Node::trasform()
*/
virtual bool transform(
MergeGraph& merge_graph,
const CallFactory& call_factory,
Environment environment,
NodeReporter reporter
);
protected:
virtual void eval_initialize(
GraphEvalState& graph_eval_state,
EvalContext context
) const;
virtual void eval_calculate(
GraphEvalState& graph_eval_state,
EvalContext context
) const;
};
bool FinishAll::transform(
MergeGraph& merge_graph,
const CallFactory& call_factory,
Environment environment,
NodeReporter reporter
)
{
node_p me = shared_from_this();
if (children().size() == 0) {
node_p replacement(new Literal());
merge_graph.replace(me, replacement);
return true;
}
{
boost::shared_ptr<ScopedMemoryPoolLite> mpl(
new ScopedMemoryPoolLite()
);
IronBee::List<Value> my_value = IronBee::List<Value>::create(*mpl);
bool replace = true;
BOOST_FOREACH(const node_p& child, children()) {
if (! child->is_literal()) {
replace = false;
break;
}
Value v = literal_value(child);
my_value.push_back(v);
}
if (replace) {
node_p replacement(new Literal(mpl,
Value::alias_list(*mpl, my_value)
));
merge_graph.replace(me, replacement);
return true;
}
}
return false;
}
const std::string& FinishAll::name() const
{
return CALL_FINISH_ALL;
}
bool FinishAll::validate(NodeReporter reporter) const
{
return true;
}
void FinishAll::eval_initialize(
GraphEvalState& graph_eval_state,
EvalContext context
) const
{
NodeEvalState& my_state = graph_eval_state[index()];
node_list_t::const_iterator last_unfinished = children().begin();
my_state.state() = last_unfinished;
my_state.setup_local_list(context.memory_manager());
}
void FinishAll::eval_calculate(
GraphEvalState& graph_eval_state,
EvalContext context
) const
{
NodeEvalState& my_state = graph_eval_state[index()];
node_list_t::const_iterator last_unfinished =
boost::any_cast<node_list_t::const_iterator>(my_state.state());
while (last_unfinished != children().end()) {
size_t index = (*last_unfinished)->index();
graph_eval_state.eval(*last_unfinished, context);
Value v = graph_eval_state.value((*last_unfinished)->index());
if (! graph_eval_state.is_finished(index)) {
break;
}
my_state.append_to_list(v);
++last_unfinished;
}
if (last_unfinished == children().end()) {
my_state.finish();
}
my_state.state() = last_unfinished;
}
bool FinishSome::transform(
MergeGraph& merge_graph,
const CallFactory& call_factory,
Environment environment,
NodeReporter reporter
)
{
node_p me = shared_from_this();
if (children().size() == 0) {
node_p replacement(new Literal());
merge_graph.replace(me, replacement);
return true;
}
BOOST_FOREACH(const node_p& child, children()) {
if (child->is_literal()) {
node_p c(child);
merge_graph.replace(me, c);
return true;
}
}
return false;
}
const std::string& FinishSome::name() const
{
return CALL_FINISH_SOME;
}
bool FinishSome::validate(NodeReporter reporter) const
{
return true;
}
void FinishSome::eval_calculate(
GraphEvalState& graph_eval_state,
EvalContext context
) const
{
for (
node_list_t::const_iterator i = children().begin();
i != children().end();
++i
)
{
graph_eval_state.eval(*i, context);
if (graph_eval_state.is_finished((*i)->index())) {
Value v = graph_eval_state.value((*i)->index());
NodeEvalState& my_state = graph_eval_state[index()];
my_state.finish(v);
return;
}
}
}
} // Anonymous
void load_predicate(CallFactory& to)
{
to
.add<IsLiteral>()
.add<FinishAll>()
.add<FinishSome>()
.add("isFinished", Functional::generate<IsFinished>)
.add("isLonger", Functional::generate<IsLonger>)
.add("isList", Functional::generate<IsList>)
;
}
} // Standard
} // Predicate
} // IronBee
<|endoftext|> |
<commit_before>#include "xz.hh"
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wdocumentation"
#pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
#endif
#define lzma_nothrow
#include <lzma.h>
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
const unsigned char sXzSig[] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
constexpr ssize_t sXzBufSize = 409600;
// ----------------------------------------------------------------------
bool xz_compressed(std::string input)
{
return std::memcmp(input.c_str(), sXzSig, sizeof(sXzSig)) == 0;
}
// ----------------------------------------------------------------------
std::string xz_decompress(std::string buffer)
{
lzma_stream strm = LZMA_STREAM_INIT; /* alloc and init lzma_stream struct */
if (lzma_stream_decoder(&strm, UINT64_MAX, LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED) != LZMA_OK) {
throw std::runtime_error("lzma decompression failed 1");
}
strm.next_in = reinterpret_cast<const uint8_t *>(buffer.c_str());
strm.avail_in = buffer.size();
std::string output(sXzBufSize, ' ');
ssize_t offset = 0;
for (;;) {
strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));
strm.avail_out = sXzBufSize;
auto const r = lzma_code(&strm, LZMA_FINISH);
if (r == LZMA_STREAM_END) {
output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);
break;
}
else if (r == LZMA_OK) {
offset += sXzBufSize;
output.resize(static_cast<size_t>(offset + sXzBufSize));
}
else {
throw std::runtime_error("lzma decompression failed 2");
}
}
lzma_end(&strm);
return output;
}
// ----------------------------------------------------------------------
std::string xz_compress(std::string input)
{
lzma_stream strm = LZMA_STREAM_INIT; /* alloc and init lzma_stream struct */
if (lzma_easy_encoder(&strm, 9 | LZMA_PRESET_EXTREME, LZMA_CHECK_CRC64) != LZMA_OK) {
throw std::runtime_error("lzma compression failed 1");
}
strm.next_in = reinterpret_cast<const uint8_t *>(input.c_str());
strm.avail_in = input.size();
std::string output(sXzBufSize, ' ');
ssize_t offset = 0;
for (;;) {
strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));
strm.avail_out = sXzBufSize;
auto const r = lzma_code(&strm, LZMA_FINISH);
if (r == LZMA_STREAM_END) {
output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);
break;
}
else if (r == LZMA_OK) {
offset += sXzBufSize;
output.resize(static_cast<size_t>(offset + sXzBufSize));
}
else {
throw std::runtime_error("lzma compression failed 2");
}
}
lzma_end(&strm);
return output;
} // xz_compress
// ----------------------------------------------------------------------
<commit_msg>porting to gcc 4.9<commit_after>#include <stdexcept>
#include "xz.hh"
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wdocumentation"
#pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
#endif
#define lzma_nothrow
#include <lzma.h>
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------
const unsigned char sXzSig[] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
constexpr ssize_t sXzBufSize = 409600;
// ----------------------------------------------------------------------
bool xz_compressed(std::string input)
{
return std::memcmp(input.c_str(), sXzSig, sizeof(sXzSig)) == 0;
}
// ----------------------------------------------------------------------
std::string xz_decompress(std::string buffer)
{
lzma_stream strm = LZMA_STREAM_INIT; /* alloc and init lzma_stream struct */
if (lzma_stream_decoder(&strm, UINT64_MAX, LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED) != LZMA_OK) {
throw std::runtime_error("lzma decompression failed 1");
}
strm.next_in = reinterpret_cast<const uint8_t *>(buffer.c_str());
strm.avail_in = buffer.size();
std::string output(sXzBufSize, ' ');
ssize_t offset = 0;
for (;;) {
strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));
strm.avail_out = sXzBufSize;
auto const r = lzma_code(&strm, LZMA_FINISH);
if (r == LZMA_STREAM_END) {
output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);
break;
}
else if (r == LZMA_OK) {
offset += sXzBufSize;
output.resize(static_cast<size_t>(offset + sXzBufSize));
}
else {
throw std::runtime_error("lzma decompression failed 2");
}
}
lzma_end(&strm);
return output;
}
// ----------------------------------------------------------------------
std::string xz_compress(std::string input)
{
lzma_stream strm = LZMA_STREAM_INIT; /* alloc and init lzma_stream struct */
if (lzma_easy_encoder(&strm, 9 | LZMA_PRESET_EXTREME, LZMA_CHECK_CRC64) != LZMA_OK) {
throw std::runtime_error("lzma compression failed 1");
}
strm.next_in = reinterpret_cast<const uint8_t *>(input.c_str());
strm.avail_in = input.size();
std::string output(sXzBufSize, ' ');
ssize_t offset = 0;
for (;;) {
strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));
strm.avail_out = sXzBufSize;
auto const r = lzma_code(&strm, LZMA_FINISH);
if (r == LZMA_STREAM_END) {
output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);
break;
}
else if (r == LZMA_OK) {
offset += sXzBufSize;
output.resize(static_cast<size_t>(offset + sXzBufSize));
}
else {
throw std::runtime_error("lzma compression failed 2");
}
}
lzma_end(&strm);
return output;
} // xz_compress
// ----------------------------------------------------------------------
<|endoftext|> |
<commit_before>/* logs.cc
Eric Robert, 9 October 2013
Copyright (c) 2013 Datacratic. All rights reserved.
Basic logs
*/
#include "soa/service/logs.h"
#include "jml/utils/exc_check.h"
#include <iostream>
#include <mutex>
#include <unordered_map>
#include <vector>
namespace Datacratic {
void Logging::ConsoleWriter::head(char const * timestamp,
char const * name,
char const * function,
char const * file,
int line) {
if(color) {
stream << timestamp << " " << "\033[1;32m" << name << " ";
}
else {
stream << timestamp << " " << name << " ";
}
}
void Logging::ConsoleWriter::body(std::string const & content) {
if(color) {
stream << "\033[1;34m";
stream.write(content.c_str(), content.size() - 1);
stream << "\033[0m\n";
}
else {
stream << content;
}
std::cerr << stream.str();
stream.str("");
}
void Logging::FileWriter::head(char const * timestamp,
char const * name,
char const * function,
char const * file,
int line) {
stream << timestamp << " " << name << " ";
}
void Logging::FileWriter::body(std::string const & content) {
file << stream.str() << content;
stream.str("");
}
void Logging::FileWriter::open(char const * filename, char const mode) {
if(mode == 'a')
file.open(filename, std::ofstream::app);
else if (mode == 'w')
file.open(filename);
else
throw ML::Exception("File mode not recognized");
if(!file) {
std::cerr << "unable to open log file '" << filename << "'" << std::endl;
}
}
void Logging::JsonWriter::head(char const * timestamp,
char const * name,
char const * function,
char const * file,
int line) {
stream << "{\"time\":\"" << timestamp
<< "\",\"name\":\"" << name
<< "\",\"call\":\"" << function
<< "\",\"file\":\"" << file
<< "\",\"line\":" << line
<< ",\"text\":\"";
}
void Logging::JsonWriter::body(std::string const & content) {
stream.write(content.c_str(), content.size() - 1);
stream << "\"}\n";
if(!writer) {
std::cerr << stream.str();
}
else {
writer->body(stream.str());
}
stream.str("");
}
namespace {
struct Registry {
std::mutex lock;
std::unordered_map<std::string, std::unique_ptr<Logging::CategoryData> > categories;
};
Registry& getRegistry() {
// Will leak but that's on program exit so who cares.
static Registry* registry = new Registry;
return *registry;
}
} // namespace anonymous
struct Logging::CategoryData {
bool initialized;
bool enabled;
char const * name;
std::shared_ptr<Writer> writer;
std::stringstream stream;
CategoryData * parent;
std::vector<CategoryData *> children;
static CategoryData * getRoot();
static CategoryData * get(char const * name);
static CategoryData * create(char const * name, char const * super, bool enabled);
static void destroy(CategoryData * name);
void activate(bool recurse = true);
void deactivate(bool recurse = true);
void writeTo(std::shared_ptr<Writer> output, bool recurse = true);
private:
CategoryData(char const * name, bool enabled) :
initialized(false),
enabled(enabled),
name(name),
parent(nullptr) {
}
};
Logging::CategoryData * Logging::CategoryData::get(char const * name) {
Registry& registry = getRegistry();
auto it = registry.categories.find(name);
return it != registry.categories.end() ? it->second.get() : nullptr;
}
Logging::CategoryData * Logging::CategoryData::getRoot() {
CategoryData * root = get("*");
if (root) return root;
getRegistry().categories["*"].reset(root = new CategoryData("*", true /* enabled */));
root->parent = root;
root->writer = std::make_shared<ConsoleWriter>();
return root;
}
Logging::CategoryData * Logging::CategoryData::create(char const * name, char const * super, bool enabled) {
Registry& registry = getRegistry();
std::lock_guard<std::mutex> guard(registry.lock);
CategoryData * root = getRoot();
CategoryData * data = get(name);
if (!data) {
registry.categories[name].reset(data = new CategoryData(name, enabled));
}
else {
ExcCheck(!data->initialized,
"making duplicate category: " + std::string(name));
}
data->initialized = true;
data->parent = get(super);
if (!data->parent) {
registry.categories[super].reset(data->parent = new CategoryData(super, enabled));
}
data->parent->children.push_back(data);
if (data->parent->initialized) {
data->writer = data->parent->writer;
}
else {
data->writer = root->writer;
}
return data;
}
void Logging::CategoryData::destroy(CategoryData * data) {
if (data->parent == data) return;
Registry& registry = getRegistry();
std::string name = data->name;
std::lock_guard<std::mutex> guard(registry.lock);
auto dataIt = registry.categories.find(name);
ExcCheck(dataIt != registry.categories.end(),
"double destroy of a category: " + name);
auto& children = data->parent->children;
auto childIt = std::find(children.begin(), children.end(), data);
if (childIt != children.end()) {
children.erase(childIt);
}
CategoryData* root = getRoot();
for (auto& child : data->children) {
child->parent = root;
}
registry.categories.erase(dataIt);
}
void Logging::CategoryData::activate(bool recurse) {
enabled = true;
if(recurse) {
for(auto item : children) {
item->activate(recurse);
}
}
}
void Logging::CategoryData::deactivate(bool recurse) {
enabled = false;
if(recurse) {
for(auto item : children) {
item->deactivate(recurse);
}
}
}
void Logging::CategoryData::writeTo(std::shared_ptr<Writer> output, bool recurse) {
writer = output;
if(recurse) {
for(auto item : children) {
item->writeTo(output, recurse);
}
}
}
Logging::Category& Logging::Category::root() {
static Category root(CategoryData::getRoot());
return root;
}
Logging::Category::Category(CategoryData * data) :
data(data) {
}
Logging::Category::Category(char const * name, Category & super, bool enabled) :
data(CategoryData::create(name, super.name(), enabled)) {
}
Logging::Category::Category(char const * name, char const * super, bool enabled) :
data(CategoryData::create(name, super, enabled)) {
}
Logging::Category::Category(char const * name, bool enabled) :
data(CategoryData::create(name, "*", enabled)) {
}
Logging::Category::~Category()
{
CategoryData::destroy(data);
}
char const * Logging::Category::name() const {
return data->name;
}
bool Logging::Category::isEnabled() const {
return data->enabled;
}
bool Logging::Category::isDisabled() const {
return !data->enabled;
}
auto Logging::Category::getWriter() const -> std::shared_ptr<Writer> const &
{
return data->writer;
}
void Logging::Category::activate(bool recurse) {
data->activate(recurse);
}
void Logging::Category::deactivate(bool recurse) {
data->deactivate(recurse);
}
void Logging::Category::writeTo(std::shared_ptr<Writer> output, bool recurse) {
data->writeTo(output, recurse);
}
std::ostream & Logging::Category::beginWrite(char const * fct, char const * file, int line) {
timeval now;
gettimeofday(&now, 0);
char text[64];
auto count = strftime(text, sizeof(text), "%Y-%m-%d %H:%M:%S", localtime(&now.tv_sec));
int ms = now.tv_usec / 1000;
sprintf(text + count, ".%03d", ms);
data->writer->head(text, data->name, fct, file, line);
return data->stream;
}
void Logging::Printer::operator&(std::ostream & stream) {
std::stringstream & text = (std::stringstream &) stream;
category.getWriter()->body(text.str());
text.str("");
}
void Logging::Thrower::operator&(std::ostream & stream) {
std::stringstream & text = (std::stringstream &) stream;
std::string message(text.str());
text.str("");
throw ML::Exception(message);
}
} // namespace Datacratic
<commit_msg>hotfix for memory corruption caused by using a logging category from multiple threads.<commit_after>/* logs.cc
Eric Robert, 9 October 2013
Copyright (c) 2013 Datacratic. All rights reserved.
Basic logs
*/
#include "soa/service/logs.h"
#include "jml/utils/exc_check.h"
#include <iostream>
#include <mutex>
#include <unordered_map>
#include <vector>
namespace Datacratic {
void Logging::ConsoleWriter::head(char const * timestamp,
char const * name,
char const * function,
char const * file,
int line) {
if(color) {
stream << timestamp << " " << "\033[1;32m" << name << " ";
}
else {
stream << timestamp << " " << name << " ";
}
}
void Logging::ConsoleWriter::body(std::string const & content) {
if(color) {
stream << "\033[1;34m";
stream.write(content.c_str(), content.size() - 1);
stream << "\033[0m\n";
}
else {
stream << content;
}
std::cerr << stream.str();
stream.str("");
}
void Logging::FileWriter::head(char const * timestamp,
char const * name,
char const * function,
char const * file,
int line) {
stream << timestamp << " " << name << " ";
}
void Logging::FileWriter::body(std::string const & content) {
file << stream.str() << content;
stream.str("");
}
void Logging::FileWriter::open(char const * filename, char const mode) {
if(mode == 'a')
file.open(filename, std::ofstream::app);
else if (mode == 'w')
file.open(filename);
else
throw ML::Exception("File mode not recognized");
if(!file) {
std::cerr << "unable to open log file '" << filename << "'" << std::endl;
}
}
void Logging::JsonWriter::head(char const * timestamp,
char const * name,
char const * function,
char const * file,
int line) {
stream << "{\"time\":\"" << timestamp
<< "\",\"name\":\"" << name
<< "\",\"call\":\"" << function
<< "\",\"file\":\"" << file
<< "\",\"line\":" << line
<< ",\"text\":\"";
}
void Logging::JsonWriter::body(std::string const & content) {
stream.write(content.c_str(), content.size() - 1);
stream << "\"}\n";
if(!writer) {
std::cerr << stream.str();
}
else {
writer->body(stream.str());
}
stream.str("");
}
namespace {
struct Registry {
std::mutex lock;
std::unordered_map<std::string, std::unique_ptr<Logging::CategoryData> > categories;
};
Registry& getRegistry() {
// Will leak but that's on program exit so who cares.
static Registry* registry = new Registry;
return *registry;
}
} // namespace anonymous
struct Logging::CategoryData {
bool initialized;
bool enabled;
char const * name;
std::shared_ptr<Writer> writer;
std::stringstream stream;
CategoryData * parent;
std::vector<CategoryData *> children;
static CategoryData * getRoot();
static CategoryData * get(char const * name);
static CategoryData * create(char const * name, char const * super, bool enabled);
static void destroy(CategoryData * name);
void activate(bool recurse = true);
void deactivate(bool recurse = true);
void writeTo(std::shared_ptr<Writer> output, bool recurse = true);
private:
CategoryData(char const * name, bool enabled) :
initialized(false),
enabled(enabled),
name(name),
parent(nullptr) {
}
};
Logging::CategoryData * Logging::CategoryData::get(char const * name) {
Registry& registry = getRegistry();
auto it = registry.categories.find(name);
return it != registry.categories.end() ? it->second.get() : nullptr;
}
Logging::CategoryData * Logging::CategoryData::getRoot() {
CategoryData * root = get("*");
if (root) return root;
getRegistry().categories["*"].reset(root = new CategoryData("*", true /* enabled */));
root->parent = root;
root->writer = std::make_shared<ConsoleWriter>();
return root;
}
Logging::CategoryData * Logging::CategoryData::create(char const * name, char const * super, bool enabled) {
Registry& registry = getRegistry();
std::lock_guard<std::mutex> guard(registry.lock);
CategoryData * root = getRoot();
CategoryData * data = get(name);
if (!data) {
registry.categories[name].reset(data = new CategoryData(name, enabled));
}
else {
ExcCheck(!data->initialized,
"making duplicate category: " + std::string(name));
}
data->initialized = true;
data->parent = get(super);
if (!data->parent) {
registry.categories[super].reset(data->parent = new CategoryData(super, enabled));
}
data->parent->children.push_back(data);
if (data->parent->initialized) {
data->writer = data->parent->writer;
}
else {
data->writer = root->writer;
}
return data;
}
void Logging::CategoryData::destroy(CategoryData * data) {
if (data->parent == data) return;
Registry& registry = getRegistry();
std::string name = data->name;
std::lock_guard<std::mutex> guard(registry.lock);
auto dataIt = registry.categories.find(name);
ExcCheck(dataIt != registry.categories.end(),
"double destroy of a category: " + name);
auto& children = data->parent->children;
auto childIt = std::find(children.begin(), children.end(), data);
if (childIt != children.end()) {
children.erase(childIt);
}
CategoryData* root = getRoot();
for (auto& child : data->children) {
child->parent = root;
}
registry.categories.erase(dataIt);
}
void Logging::CategoryData::activate(bool recurse) {
enabled = true;
if(recurse) {
for(auto item : children) {
item->activate(recurse);
}
}
}
void Logging::CategoryData::deactivate(bool recurse) {
enabled = false;
if(recurse) {
for(auto item : children) {
item->deactivate(recurse);
}
}
}
void Logging::CategoryData::writeTo(std::shared_ptr<Writer> output, bool recurse) {
writer = output;
if(recurse) {
for(auto item : children) {
item->writeTo(output, recurse);
}
}
}
Logging::Category& Logging::Category::root() {
static Category root(CategoryData::getRoot());
return root;
}
Logging::Category::Category(CategoryData * data) :
data(data) {
}
Logging::Category::Category(char const * name, Category & super, bool enabled) :
data(CategoryData::create(name, super.name(), enabled)) {
}
Logging::Category::Category(char const * name, char const * super, bool enabled) :
data(CategoryData::create(name, super, enabled)) {
}
Logging::Category::Category(char const * name, bool enabled) :
data(CategoryData::create(name, "*", enabled)) {
}
Logging::Category::~Category()
{
CategoryData::destroy(data);
}
char const * Logging::Category::name() const {
return data->name;
}
bool Logging::Category::isEnabled() const {
return data->enabled;
}
bool Logging::Category::isDisabled() const {
return !data->enabled;
}
auto Logging::Category::getWriter() const -> std::shared_ptr<Writer> const &
{
return data->writer;
}
void Logging::Category::activate(bool recurse) {
data->activate(recurse);
}
void Logging::Category::deactivate(bool recurse) {
data->deactivate(recurse);
}
void Logging::Category::writeTo(std::shared_ptr<Writer> output, bool recurse) {
data->writeTo(output, recurse);
}
// This lock is a quick-fix for the case where a category is used by multiple
// threads. Note that this lock should either eventually be removed or replaced
// by a per category lock. Unfortunately the current setup makes it very
// difficult to pass the header information to the operator& so that everything
// can be dumped in the stream in one go.
namespace { std::mutex loggingMutex; }
std::ostream & Logging::Category::beginWrite(char const * fct, char const * file, int line) {
loggingMutex.lock();
timeval now;
gettimeofday(&now, 0);
char text[64];
auto count = strftime(text, sizeof(text), "%Y-%m-%d %H:%M:%S", localtime(&now.tv_sec));
int ms = now.tv_usec / 1000;
sprintf(text + count, ".%03d", ms);
data->writer->head(text, data->name, fct, file, line);
return data->stream;
}
void Logging::Printer::operator&(std::ostream & stream) {
std::stringstream & text = (std::stringstream &) stream;
category.getWriter()->body(text.str());
text.str("");
loggingMutex.unlock();
}
void Logging::Thrower::operator&(std::ostream & stream) {
std::stringstream & text = (std::stringstream &) stream;
std::string message(text.str());
text.str("");
loggingMutex.unlock();
throw ML::Exception(message);
}
} // namespace Datacratic
<|endoftext|> |
<commit_before>/*
Deutsch-Jozsa Problem
=====================
Given a list of number(0 / 1) of length n which
have one of the following condtions
- all number are equal to each other
- number of 0s is equal to number of 1s
The task is to determine which condition the list has.
By using conventional compution in worst case scenario.
At least n/2+1 queries have to be made in order to ensure
that the answer is correct.
By using randomized algorithm, more than half probability of
achieving the correct answer can be done by using only 2 queries.
However, in quantum computing, this problem can be solved by
using only 1 quantum query which will be faster than other computation.
input :
first line : n (size of list) Note: this number should be power of 2
next n lines : ai (values in the list) Note: 0 <= ai <= 1
*/
#include <QCPP.h>
#include <iostream>
#include <cmath>
#include <cassert>
#include <ctime>
#include <vector>
std::vector<int> arr;
int n;
int main() {
srand(time(NULL));
std::cin >> n;
// calcuate number of required qubits
int bit = log(n) / log(2);
// n should be power of 2
assert((1 << bit) == n);
// initialize qubits
Quantum qubits(bit + 1);
// enumerate every possibilities with equal probability
qubits.hadamardRange(0, bit);
// this part should be oracle black box
// set value according to algorithm
double prob = 1.0f / sqrt(2.0f * n);
arr.resize(n);
for(int i = 0;i < n;i++) {
int &val = arr[i];
std::cin >> val;
assert(val == 0 or val == 1);
if(val == 0) {
qubits.setPhase(2 * i, prob);
qubits.setPhase(2 * i + 1, -prob);
}else {
qubits.setPhase(2 * i, -prob);
qubits.setPhase(2 * i + 1, prob);
}
}
// pass qubits through hadamard gates again
qubits.hadamardRange(1, bit);
for(int i = 0;i < (1 << qubits.size());i++) {
std::cout << "Probability of being " << i << " : " << qubits.getPhase(i) << std::endl;
}
// there are 2 possible results
// condition will check for states of qubits 1 to bit
if((qubits.getState() & (1 << (bit+1) - (1 << 1))) == 0) {
// all data are equal
std::cout << "all numbers are equal" << std::endl;
}else {
// num of 0s and 1s are equal
std::cout << "number of 0s is equal to number of 1s" << std::endl;
}
return 0;
}<commit_msg>add more comments<commit_after>/*
Deutsch-Jozsa Problem
=====================
Given a list of number(0 / 1) of length n which
have one of the following condtions
- all number are equal to each other
- number of 0s is equal to number of 1s
The task is to determine which condition the list has.
By using conventional compution in worst case scenario.
At least n/2+1 queries have to be made in order to ensure
that the answer is correct.
By using randomized algorithm, more than half probability of
achieving the correct answer can be done by using only 2 queries.
However, in quantum computing, this problem can be solved by
using only 1 quantum query which will be faster than other computation.
input :
first line : n (size of list) Note: this number should be power of 2
next n lines : ai (values in the list) Note: 0 <= ai <= 1
*/
#include <QCPP.h>
#include <iostream>
#include <cmath>
#include <cassert>
#include <ctime>
#include <vector>
std::vector<int> arr;
int n;
int main() {
srand(time(NULL));
std::cin >> n;
// calcuate number of required qubits
int bit = log(n) / log(2);
// n should be power of 2
assert((1 << bit) == n);
// initialize qubits
Quantum qubits(bit + 1);
// enumerate every possibilities with equal probability
qubits.hadamardRange(0, bit);
// this part should be oracle black box
// set value according to algorithm
double prob = 1.0f / sqrt(2.0f * n);
arr.resize(n);
for(int i = 0;i < n;i++) {
int &val = arr[i];
std::cin >> val;
assert(val == 0 or val == 1);
if(val == 0) {
qubits.setPhase(2*i, prob);
qubits.setPhase(2*i+1, -prob);
}else {
qubits.setPhase(2*i, -prob);
qubits.setPhase(2*i+1, prob);
}
}
// pass qubits through hadamard gates again
qubits.hadamardRange(1, bit);
// output every possibility
for(int i = 0;i < (1 << qubits.size());i++) {
std::cout << "Probability of being " << i << " : " << qubits.getPhase(i) << std::endl;
}
// there are 2 possible results
// condition will check for states of qubits 1 to bit
if((qubits.getState() & (1 << (bit+1) - (1 << 1))) == 0) {
// all data are equal
std::cout << "all numbers are equal" << std::endl;
}else {
// num of 0s and 1s are equal
std::cout << "number of 0s is equal to number of 1s" << std::endl;
}
return 0;
}<|endoftext|> |
<commit_before>/**
* SCC0250 - Computação Gráfica
* Trabalho 1 - Catavento
* Alunos:
* Felipe Scrochio Custódio - 9442688
* Henrique Loschiavo -
* Lucas Antognoni -
* Gustavo Santiago -
**/
#include <GL/glut.h>
void draw(void)
{
// Background color
glClearColor(1, 1, 1, 1);
// Paint background
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(0.0f, 0.88f, 0.95f);
glVertex2f(100, -50);
glColor3f(0.96f, 0.38f, 0.56f);
glVertex2f(200, 100);
glVertex2f(300, -50);
glEnd();
glFlush();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv); // Instanciate Glut
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Defines the buffer display mode
glutInitWindowSize(800, 600); // Defines the size in pixels of the window
glutCreateWindow("Wind Vane"); // Defines the window title
glutDisplayFunc(draw); // Set rendering function as "draw(.)"
gluOrtho2D(0, 400, -150, 150); // Defines the orthogonal plane to build the scene in
glutMainLoop(); // Start operations according to the specifications above
}
<commit_msg>Mouse function added<commit_after>/**
* SCC0250 - Computação Gráfica
* Trabalho 1 - Catavento
* Alunos:
* Felipe Scrochio Custódio - 9442688
* Henrique Loschiavo -
* Lucas Antognoni -
* Gustavo Santiago -
**/
#include <GL/glut.h>
void draw(void)
{
// Background color
glClearColor(0.0f, 0.0f, 0.0f, 1);
// Paint background
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(0.0f, 0.88f, 0.95f);
glVertex2f(100, -50);
glColor3f(0.96f, 0.38f, 0.56f);
glVertex2f(200, 100);
glVertex2f(300, -50);
glEnd();
glFlush();
}
void on_mouseClick(int button, int click_state, int x_mouse_position, int y_mouse_position)
{
if (click_state == GLUT_DOWN) {
if (button == GLUT_RIGHT_BUTTON) {
// Rotate blades clockwise
} else if (button == GLUT_LEFT_BUTTON) {
// Rotate blades counter clockwise
}
}
glutPostRedisplay(); // Forces scene redraw
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv); // Instanciate Glut
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Defines the buffer display mode
glutInitWindowSize(800, 600); // Defines the size in pixels of the window
glutCreateWindow("Windmill"); // Defines the window title
glutDisplayFunc(draw); // Set rendering function as "draw(.)"
glutMouseFunc(on_mouseClick); // Handles mouse clicks
gluOrtho2D(0, 400, -150, 150); // Defines the orthogonal plane to build the scene in
glutMainLoop(); // Start operations according to the specifications above
}
<|endoftext|> |
<commit_before>//
// yas_processing_routing_module.cpp
//
#include "yas_processing_routing_modules.h"
#include "yas_processing_module.h"
#include "yas_processing_signal_event.h"
#include "yas_processing_receive_signal_processor.h"
#include "yas_processing_send_signal_processor.h"
#include "yas_processing_remove_signal_processor.h"
#include "yas_fast_each.h"
#include "yas_boolean.h"
using namespace yas;
namespace yas {
namespace processing {
namespace routing {
struct context {
signal_event signal;
time time;
context(signal_event &&signal) : signal(std::move(signal)) {
}
void reset(std::size_t const reserve_size) {
this->signal.reserve(reserve_size);
this->signal.resize(0);
this->time = nullptr;
}
};
using context_sptr = std::shared_ptr<context>;
template <typename T>
context_sptr make_context() {
return std::make_shared<context>(make_signal_event<T>(0));
}
}
}
}
template <typename T>
processing::module processing::make_signal_module(processing::routing::kind const kind) {
using namespace yas::processing::routing;
auto context = make_context<T>();
auto prepare_processor = [context](time::range const &, connector_map_t const &, connector_map_t const &,
stream &stream) mutable { context->reset(stream.sync_source().slice_length); };
auto receive_processor = processing::make_receive_signal_processor<T>(
[context](time::range const &time_range, sync_source const &, channel_index_t const,
connector_index_t const co_idx, T const *const signal_ptr) mutable {
if (co_idx == to_connector_index(routing::input::value)) {
context->time = time_range;
context->signal.copy_from(signal_ptr, time_range.length);
}
});
auto remove_processor = processing::make_remove_signal_processor<T>({to_connector_index(routing::input::value)});
auto send_processor = processing::make_send_signal_processor<T>(
[context, kind](processing::time::range const &time_range, sync_source const &, channel_index_t const,
connector_index_t const co_idx, T *const signal_ptr) {
if (co_idx == to_connector_index(routing::output::value)) {
auto out_each = make_fast_each(signal_ptr, time_range.length);
processing::signal_event const &input_signal = context->signal;
auto const *src_ptr = input_signal.data<T>();
processing::time const &input_time = context->time;
auto const src_offset = input_time ? time_range.frame - input_time.get<time::range>().frame : 0;
auto const &src_length = input_time ? input_time.get<time::range>().length : 0;
while (yas_fast_each_next(out_each)) {
auto const &idx = yas_fast_each_index(out_each);
auto const src_idx = idx + src_offset;
auto const &src_value = (src_idx >= 0 && src_idx < src_length) ? src_ptr[src_idx] : 0;
yas_fast_each_value(out_each) = static_cast<T>(src_value);
}
}
});
module::processors_t processors{prepare_processor, receive_processor};
if (kind == routing::kind::move) {
processors.emplace_back(std::move(remove_processor));
}
processors.emplace_back(std::move(send_processor));
return processing::module{std::move(processors)};
}
template processing::module processing::make_signal_module<double>(processing::routing::kind const);
template processing::module processing::make_signal_module<float>(processing::routing::kind const);
template processing::module processing::make_signal_module<int64_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<int32_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<int16_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<int8_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint64_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint32_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint16_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint8_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<boolean>(processing::routing::kind const);
<commit_msg>update routing_module<commit_after>//
// yas_processing_routing_module.cpp
//
#include "yas_processing_routing_modules.h"
#include "yas_processing_module.h"
#include "yas_processing_signal_event.h"
#include "yas_processing_receive_signal_processor.h"
#include "yas_processing_send_signal_processor.h"
#include "yas_processing_remove_signal_processor.h"
#include "yas_processing_signal_process_context.h"
#include "yas_fast_each.h"
#include "yas_boolean.h"
using namespace yas;
template <typename T>
processing::module processing::make_signal_module(processing::routing::kind const kind) {
using namespace yas::processing::routing;
auto context = std::make_shared<signal_process_context<T, 1>>();
auto prepare_processor = [context](time::range const &, connector_map_t const &, connector_map_t const &,
stream &stream) mutable { context->reset(stream.sync_source().slice_length); };
auto receive_processor = processing::make_receive_signal_processor<T>(
[context](time::range const &time_range, sync_source const &, channel_index_t const,
connector_index_t const co_idx, T const *const signal_ptr) mutable {
if (co_idx == to_connector_index(routing::input::value)) {
context->set_time(time{time_range}, co_idx);
context->copy_data_from(signal_ptr, time_range.length, co_idx);
}
});
auto remove_processor = processing::make_remove_signal_processor<T>({to_connector_index(routing::input::value)});
auto send_processor = processing::make_send_signal_processor<T>(
[context, kind](processing::time::range const &time_range, sync_source const &, channel_index_t const,
connector_index_t const co_idx, T *const signal_ptr) {
if (co_idx == to_connector_index(routing::output::value)) {
auto const input_co_idx = to_connector_index(input::value);
auto const *src_ptr = context->data(input_co_idx);
processing::time const &input_time = context->time(input_co_idx);
auto const src_offset = input_time ? time_range.frame - input_time.get<time::range>().frame : 0;
auto const &src_length = input_time ? input_time.get<time::range>().length : 0;
auto out_each = make_fast_each(signal_ptr, time_range.length);
while (yas_fast_each_next(out_each)) {
auto const &idx = yas_fast_each_index(out_each);
auto const src_idx = idx + src_offset;
auto const &src_value = (src_idx >= 0 && src_idx < src_length) ? src_ptr[src_idx] : 0;
yas_fast_each_value(out_each) = static_cast<T>(src_value);
}
}
});
module::processors_t processors{prepare_processor, receive_processor};
if (kind == routing::kind::move) {
processors.emplace_back(std::move(remove_processor));
}
processors.emplace_back(std::move(send_processor));
return processing::module{std::move(processors)};
}
template processing::module processing::make_signal_module<double>(processing::routing::kind const);
template processing::module processing::make_signal_module<float>(processing::routing::kind const);
template processing::module processing::make_signal_module<int64_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<int32_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<int16_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<int8_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint64_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint32_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint16_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<uint8_t>(processing::routing::kind const);
template processing::module processing::make_signal_module<boolean>(processing::routing::kind const);
<|endoftext|> |
<commit_before>// sol2
// The MIT License (MIT)
// Copyright (c) 2013-2018 Rapptz, ThePhD and contributors
// 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 SOL_LOAD_RESULT_HPP
#define SOL_LOAD_RESULT_HPP
#include "stack.hpp"
#include "function.hpp"
#include "proxy_base.hpp"
#include <cstdint>
namespace sol {
struct load_result : public proxy_base<load_result> {
private:
lua_State* L;
int index;
int returncount;
int popcount;
load_status err;
template <typename T>
decltype(auto) tagged_get(types<optional<T>>) const {
if (!valid()) {
return optional<T>(nullopt);
}
return stack::get<optional<T>>(L, index);
}
template <typename T>
decltype(auto) tagged_get(types<T>) const {
#if defined(SOL_SAFE_PROXIES) && SOL_SAFE_PROXIES != 0
if (!valid()) {
type_panic_c_str(L, index, type_of(L, index), type::none);
}
#endif // Check Argument Safety
return stack::get<T>(L, index);
}
optional<error> tagged_get(types<optional<error>>) const {
if (valid()) {
return nullopt;
}
return error(detail::direct_error, stack::get<std::string>(L, index));
}
error tagged_get(types<error>) const {
#if defined(SOL_SAFE_PROXIES) && SOL_SAFE_PROXIES != 0
if (valid()) {
type_panic_c_str(L, index, type_of(L, index), type::none, "expecting an error type (a string, from Lua)");
}
#endif // Check Argument Safety
return error(detail::direct_error, stack::get<std::string>(L, index));
}
public:
load_result() = default;
load_result(lua_State* Ls, int stackindex = -1, int retnum = 0, int popnum = 0, load_status lerr = load_status::ok) noexcept
: L(Ls), index(stackindex), returncount(retnum), popcount(popnum), err(lerr) {
}
load_result(const load_result&) = default;
load_result& operator=(const load_result&) = default;
load_result(load_result&& o) noexcept
: L(o.L), index(o.index), returncount(o.returncount), popcount(o.popcount), err(o.err) {
// Must be manual, otherwise destructor will screw us
// return count being 0 is enough to keep things clean
// but we will be thorough
o.L = nullptr;
o.index = 0;
o.returncount = 0;
o.popcount = 0;
o.err = load_status::syntax;
}
load_result& operator=(load_result&& o) noexcept {
L = o.L;
index = o.index;
returncount = o.returncount;
popcount = o.popcount;
err = o.err;
// Must be manual, otherwise destructor will screw us
// return count being 0 is enough to keep things clean
// but we will be thorough
o.L = nullptr;
o.index = 0;
o.returncount = 0;
o.popcount = 0;
o.err = load_status::syntax;
return *this;
}
load_status status() const noexcept {
return err;
}
bool valid() const noexcept {
return status() == load_status::ok;
}
template <typename T>
T get() const {
return tagged_get(types<meta::unqualified_t<T>>());
}
template <typename... Ret, typename... Args>
decltype(auto) call(Args&&... args) {
#if defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 191200000
// MSVC is ass sometimes
return get<protected_function>().call<Ret...>(std::forward<Args>(args)...);
#else
return get<protected_function>().template call<Ret...>(std::forward<Args>(args)...);
#endif
}
template <typename... Args>
decltype(auto) operator()(Args&&... args) {
return call<>(std::forward<Args>(args)...);
}
lua_State* lua_state() const noexcept {
return L;
};
int stack_index() const noexcept {
return index;
};
~load_result() {
stack::remove(L, index, popcount);
}
};
} // namespace sol
#endif // SOL_LOAD_RESULT_HPP
<commit_msg>Add the clang check to load_result.hpp as well<commit_after>// sol2
// The MIT License (MIT)
// Copyright (c) 2013-2018 Rapptz, ThePhD and contributors
// 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 SOL_LOAD_RESULT_HPP
#define SOL_LOAD_RESULT_HPP
#include "stack.hpp"
#include "function.hpp"
#include "proxy_base.hpp"
#include <cstdint>
namespace sol {
struct load_result : public proxy_base<load_result> {
private:
lua_State* L;
int index;
int returncount;
int popcount;
load_status err;
template <typename T>
decltype(auto) tagged_get(types<optional<T>>) const {
if (!valid()) {
return optional<T>(nullopt);
}
return stack::get<optional<T>>(L, index);
}
template <typename T>
decltype(auto) tagged_get(types<T>) const {
#if defined(SOL_SAFE_PROXIES) && SOL_SAFE_PROXIES != 0
if (!valid()) {
type_panic_c_str(L, index, type_of(L, index), type::none);
}
#endif // Check Argument Safety
return stack::get<T>(L, index);
}
optional<error> tagged_get(types<optional<error>>) const {
if (valid()) {
return nullopt;
}
return error(detail::direct_error, stack::get<std::string>(L, index));
}
error tagged_get(types<error>) const {
#if defined(SOL_SAFE_PROXIES) && SOL_SAFE_PROXIES != 0
if (valid()) {
type_panic_c_str(L, index, type_of(L, index), type::none, "expecting an error type (a string, from Lua)");
}
#endif // Check Argument Safety
return error(detail::direct_error, stack::get<std::string>(L, index));
}
public:
load_result() = default;
load_result(lua_State* Ls, int stackindex = -1, int retnum = 0, int popnum = 0, load_status lerr = load_status::ok) noexcept
: L(Ls), index(stackindex), returncount(retnum), popcount(popnum), err(lerr) {
}
load_result(const load_result&) = default;
load_result& operator=(const load_result&) = default;
load_result(load_result&& o) noexcept
: L(o.L), index(o.index), returncount(o.returncount), popcount(o.popcount), err(o.err) {
// Must be manual, otherwise destructor will screw us
// return count being 0 is enough to keep things clean
// but we will be thorough
o.L = nullptr;
o.index = 0;
o.returncount = 0;
o.popcount = 0;
o.err = load_status::syntax;
}
load_result& operator=(load_result&& o) noexcept {
L = o.L;
index = o.index;
returncount = o.returncount;
popcount = o.popcount;
err = o.err;
// Must be manual, otherwise destructor will screw us
// return count being 0 is enough to keep things clean
// but we will be thorough
o.L = nullptr;
o.index = 0;
o.returncount = 0;
o.popcount = 0;
o.err = load_status::syntax;
return *this;
}
load_status status() const noexcept {
return err;
}
bool valid() const noexcept {
return status() == load_status::ok;
}
template <typename T>
T get() const {
return tagged_get(types<meta::unqualified_t<T>>());
}
template <typename... Ret, typename... Args>
decltype(auto) call(Args&&... args) {
#if !defined(__clang__) && defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 191200000
// MSVC is ass sometimes
return get<protected_function>().call<Ret...>(std::forward<Args>(args)...);
#else
return get<protected_function>().template call<Ret...>(std::forward<Args>(args)...);
#endif
}
template <typename... Args>
decltype(auto) operator()(Args&&... args) {
return call<>(std::forward<Args>(args)...);
}
lua_State* lua_state() const noexcept {
return L;
};
int stack_index() const noexcept {
return index;
};
~load_result() {
stack::remove(L, index, popcount);
}
};
} // namespace sol
#endif // SOL_LOAD_RESULT_HPP
<|endoftext|> |
<commit_before>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
template <typename T>
bool is_type_supported(int vec_width, const Target &target) {
return target.supports_type(type_of<T>().with_lanes(vec_width));
}
template <>
bool is_type_supported<float>(int vec_width, const Target &target) {
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
return vec_width == 1;
} else {
return true;
}
}
template <>
bool is_type_supported<double>(int vec_width, const Target &target) {
if (target.has_feature(Target::OpenCL) &&
!target.has_feature(Target::CLDoubles)) {
return false;
} else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
return vec_width == 1;
} else {
return true;
}
}
template<typename A, typename B>
bool test(int vec_width, const Target &target) {
if (!is_type_supported<A>(vec_width, target) || !is_type_supported<B>(vec_width, target)) {
// Type not supported, return pass.
return true;
}
int W = 1024;
int H = 1;
Buffer<A> input(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
input(x, y) = (A)((rand()&0xffff)*0.1);
}
}
Var x, y;
Func f;
f(x, y) = cast<B>(input(x, y));
if (target.has_gpu_feature()) {
Var xo, xi;
f.gpu_tile(x, xo, xi, 64);
} else {
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
// TODO: Non-native vector widths hang the compiler here.
//f.hexagon();
}
if (vec_width > 1) {
f.vectorize(x, vec_width);
}
}
Buffer<B> output = f.realize(W, H);
/*
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
printf("%d %d -> %d %d\n", x, y, (int)(input(x, y)), (int)(output(x, y)));
}
}
*/
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
bool ok = ((B)(input(x, y)) == output(x, y));
if (!ok) {
printf("%s x %d -> %s x %d failed\n",
string_of_type<A>(), vec_width,
string_of_type<B>(), vec_width);
printf("At %d %d, %f -> %f instead of %f\n",
x, y,
(double)(input(x, y)),
(double)(output(x, y)),
(double)((B)(input(x, y))));
return false;
}
}
}
return true;
}
template<typename A>
bool test_all(int vec_width, const Target &target) {
bool ok = true;
ok = ok && test<A, float>(vec_width, target);
ok = ok && test<A, double>(vec_width, target);
ok = ok && test<A, uint8_t>(vec_width, target);
ok = ok && test<A, int8_t>(vec_width, target);
ok = ok && test<A, uint16_t>(vec_width, target);
ok = ok && test<A, int16_t>(vec_width, target);
ok = ok && test<A, uint32_t>(vec_width, target);
ok = ok && test<A, int32_t>(vec_width, target);
return ok;
}
int main(int argc, char **argv) {
// We don't test this on windows, because float-to-int conversions
// on windows use _ftol2, which has its own unique calling
// convention, and older LLVMs (e.g. pnacl) don't do it right so
// you get clobbered registers.
#ifdef WIN32
printf("Not testing on windows\n");
return 0;
#endif
Target target = get_jit_target_from_environment();
bool ok = true;
// We only test power-of-two vector widths for now
for (int vec_width = 1; vec_width <= 64; vec_width*=2) {
printf("Testing vector width %d\n", vec_width);
ok = ok && test_all<float>(vec_width, target);
ok = ok && test_all<double>(vec_width, target);
ok = ok && test_all<uint8_t>(vec_width, target);
ok = ok && test_all<int8_t>(vec_width, target);
ok = ok && test_all<uint16_t>(vec_width, target);
ok = ok && test_all<int16_t>(vec_width, target);
ok = ok && test_all<uint32_t>(vec_width, target);
ok = ok && test_all<int32_t>(vec_width, target);
}
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<commit_msg>Speed up vector_cast test by using std::async<commit_after>#include "Halide.h"
#include <stdio.h>
#include <future>
using namespace Halide;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
template <typename T>
bool is_type_supported(int vec_width, const Target &target) {
return target.supports_type(type_of<T>().with_lanes(vec_width));
}
template <>
bool is_type_supported<float>(int vec_width, const Target &target) {
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
return vec_width == 1;
} else {
return true;
}
}
template <>
bool is_type_supported<double>(int vec_width, const Target &target) {
if (target.has_feature(Target::OpenCL) &&
!target.has_feature(Target::CLDoubles)) {
return false;
} else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
return vec_width == 1;
} else {
return true;
}
}
template<typename A, typename B>
bool test(int vec_width, const Target &target) {
if (!is_type_supported<A>(vec_width, target) || !is_type_supported<B>(vec_width, target)) {
// Type not supported, return pass.
return true;
}
int W = 1024;
int H = 1;
Buffer<A> input(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
input(x, y) = (A)((rand()&0xffff)*0.1);
}
}
Var x, y;
Func f;
f(x, y) = cast<B>(input(x, y));
if (target.has_gpu_feature()) {
Var xo, xi;
f.gpu_tile(x, xo, xi, 64);
} else {
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
// TODO: Non-native vector widths hang the compiler here.
//f.hexagon();
}
if (vec_width > 1) {
f.vectorize(x, vec_width);
}
}
Buffer<B> output = f.realize(W, H);
/*
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
printf("%d %d -> %d %d\n", x, y, (int)(input(x, y)), (int)(output(x, y)));
}
}
*/
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
bool ok = ((B)(input(x, y)) == output(x, y));
if (!ok) {
fprintf(stderr, "%s x %d -> %s x %d failed\n",
string_of_type<A>(), vec_width,
string_of_type<B>(), vec_width);
fprintf(stderr, "At %d %d, %f -> %f instead of %f\n",
x, y,
(double)(input(x, y)),
(double)(output(x, y)),
(double)((B)(input(x, y))));
return false;
}
}
}
return true;
}
template<typename A>
void test_all(int vec_width, const Target &target, std::vector<std::future<bool>> &futures) {
futures.push_back(std::async(test<A, float>, vec_width, target));
futures.push_back(std::async(test<A, double>, vec_width, target));
futures.push_back(std::async(test<A, uint8_t>, vec_width, target));
futures.push_back(std::async(test<A, int8_t>, vec_width, target));
futures.push_back(std::async(test<A, uint16_t>, vec_width, target));
futures.push_back(std::async(test<A, int16_t>, vec_width, target));
futures.push_back(std::async(test<A, uint32_t>, vec_width, target));
futures.push_back(std::async(test<A, int32_t>, vec_width, target));
}
int main(int argc, char **argv) {
// We don't test this on windows, because float-to-int conversions
// on windows use _ftol2, which has its own unique calling
// convention, and older LLVMs (e.g. pnacl) don't do it right so
// you get clobbered registers.
#ifdef WIN32
printf("Not testing on windows\n");
return 0;
#endif
Target target = get_jit_target_from_environment();
// We only test power-of-two vector widths for now
std::vector<std::future<bool>> futures;
for (int vec_width = 1; vec_width <= 64; vec_width*=2) {
printf("Testing vector width %d\n", vec_width);
test_all<float>(vec_width, target, futures);
test_all<double>(vec_width, target, futures);
test_all<uint8_t>(vec_width, target, futures);
test_all<int8_t>(vec_width, target, futures);
test_all<uint16_t>(vec_width, target, futures);
test_all<int16_t>(vec_width, target, futures);
test_all<uint32_t>(vec_width, target, futures);
test_all<int32_t>(vec_width, target, futures);
}
bool ok = true;
for (auto &f : futures) {
f.wait();
ok &= f.get();
}
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#include "perfetto/base/logging.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/cts/utils.h"
#include "test/gtest_and_gmock.h"
#include "test/test_helper.h"
#include "protos/perfetto/config/profiling/perf_event_config.gen.h"
#include "protos/perfetto/trace/profiling/profile_common.gen.h"
#include "protos/perfetto/trace/profiling/profile_packet.gen.h"
#include "protos/perfetto/trace/trace_packet.gen.h"
namespace perfetto {
namespace {
// Skip these tests if the device in question doesn't have the necessary kernel
// LSM hooks in perf_event_open. This comes up when a device with an older
// kernel upgrades to R.
bool HasPerfLsmHooks() {
char buf[PROP_VALUE_MAX + 1] = {};
int ret = __system_property_get("sys.init.perf_lsm_hooks", buf);
PERFETTO_CHECK(ret >= 0);
return std::string(buf) == "1";
}
std::vector<protos::gen::TracePacket> ProfileSystemWide(std::string app_name) {
base::TestTaskRunner task_runner;
// (re)start the target app's main activity
if (IsAppRunning(app_name)) {
StopApp(app_name, "old.app.stopped", &task_runner);
task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/);
}
StartAppActivity(app_name, "BusyWaitActivity", "target.app.running",
&task_runner,
/*delay_ms=*/100);
task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/);
// set up tracing
TestHelper helper(&task_runner);
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(20 * 1024);
trace_config.set_duration_ms(3000);
trace_config.set_data_source_stop_timeout_ms(8000);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("linux.perf");
ds_config->set_target_buffer(0);
protos::gen::PerfEventConfig perf_config;
perf_config.set_all_cpus(true);
perf_config.set_sampling_frequency(10); // Hz
ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());
// start tracing
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled(15000 /*ms*/);
helper.ReadData();
helper.WaitForReadData();
return helper.trace();
}
void AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,
int target_pid) {
ASSERT_GT(packets.size(), 0u);
int total_perf_packets = 0;
int total_samples = 0;
int target_samples = 0;
for (const auto& packet : packets) {
if (!packet.has_perf_sample())
continue;
total_perf_packets++;
EXPECT_GT(packet.timestamp(), 0u) << "all packets should have a timestamp";
const auto& sample = packet.perf_sample();
if (sample.has_kernel_records_lost())
continue;
if (sample.has_sample_skipped_reason())
continue;
total_samples++;
EXPECT_GT(sample.tid(), 0u);
EXPECT_GT(sample.callstack_iid(), 0u);
if (sample.pid() == static_cast<uint32_t>(target_pid))
target_samples++;
}
EXPECT_GT(target_samples, 0) << "packets.size(): " << packets.size()
<< ", total_perf_packets: " << total_perf_packets
<< ", total_samples: " << total_samples << "\n";
}
void AssertNoStacksForPid(std::vector<protos::gen::TracePacket> packets,
int target_pid) {
// The process can still be sampled, but the stacks should be discarded
// without unwinding.
for (const auto& packet : packets) {
if (packet.perf_sample().pid() == static_cast<uint32_t>(target_pid)) {
EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);
EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());
}
}
}
TEST(TracedPerfCtsTest, SystemWideDebuggableApp) {
if (!HasPerfLsmHooks())
return;
std::string app_name = "android.perfetto.cts.app.debuggable";
const auto& packets = ProfileSystemWide(app_name);
int app_pid = PidForProcessName(app_name);
ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
AssertHasSampledStacksForPid(packets, app_pid);
StopApp(app_name);
}
TEST(TracedPerfCtsTest, SystemWideProfileableApp) {
if (!HasPerfLsmHooks())
return;
std::string app_name = "android.perfetto.cts.app.profileable";
const auto& packets = ProfileSystemWide(app_name);
int app_pid = PidForProcessName(app_name);
ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
AssertHasSampledStacksForPid(packets, app_pid);
StopApp(app_name);
}
TEST(TracedPerfCtsTest, SystemWideReleaseApp) {
if (!HasPerfLsmHooks())
return;
std::string app_name = "android.perfetto.cts.app.release";
const auto& packets = ProfileSystemWide(app_name);
int app_pid = PidForProcessName(app_name);
ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
if (IsDebuggableBuild())
AssertHasSampledStacksForPid(packets, app_pid);
else
AssertNoStacksForPid(packets, app_pid);
StopApp(app_name);
}
} // namespace
} // namespace perfetto
<commit_msg>Check if target app is still running at end of test.<commit_after>/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#include "perfetto/base/logging.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/cts/utils.h"
#include "test/gtest_and_gmock.h"
#include "test/test_helper.h"
#include "protos/perfetto/config/profiling/perf_event_config.gen.h"
#include "protos/perfetto/trace/profiling/profile_common.gen.h"
#include "protos/perfetto/trace/profiling/profile_packet.gen.h"
#include "protos/perfetto/trace/trace_packet.gen.h"
namespace perfetto {
namespace {
// Skip these tests if the device in question doesn't have the necessary kernel
// LSM hooks in perf_event_open. This comes up when a device with an older
// kernel upgrades to R.
bool HasPerfLsmHooks() {
char buf[PROP_VALUE_MAX + 1] = {};
int ret = __system_property_get("sys.init.perf_lsm_hooks", buf);
PERFETTO_CHECK(ret >= 0);
return std::string(buf) == "1";
}
std::vector<protos::gen::TracePacket> ProfileSystemWide(std::string app_name) {
base::TestTaskRunner task_runner;
// (re)start the target app's main activity
if (IsAppRunning(app_name)) {
StopApp(app_name, "old.app.stopped", &task_runner);
task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/);
}
StartAppActivity(app_name, "BusyWaitActivity", "target.app.running",
&task_runner,
/*delay_ms=*/100);
task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/);
// set up tracing
TestHelper helper(&task_runner);
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(20 * 1024);
trace_config.set_duration_ms(3000);
trace_config.set_data_source_stop_timeout_ms(8000);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("linux.perf");
ds_config->set_target_buffer(0);
protos::gen::PerfEventConfig perf_config;
perf_config.set_all_cpus(true);
perf_config.set_sampling_frequency(10); // Hz
ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());
// start tracing
helper.StartTracing(trace_config);
helper.WaitForTracingDisabled(15000 /*ms*/);
helper.ReadData();
helper.WaitForReadData();
return helper.trace();
}
void AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,
int target_pid) {
ASSERT_GT(packets.size(), 0u);
int total_perf_packets = 0;
int total_samples = 0;
int target_samples = 0;
for (const auto& packet : packets) {
if (!packet.has_perf_sample())
continue;
total_perf_packets++;
EXPECT_GT(packet.timestamp(), 0u) << "all packets should have a timestamp";
const auto& sample = packet.perf_sample();
if (sample.has_kernel_records_lost())
continue;
if (sample.has_sample_skipped_reason())
continue;
total_samples++;
EXPECT_GT(sample.tid(), 0u);
EXPECT_GT(sample.callstack_iid(), 0u);
if (sample.pid() == static_cast<uint32_t>(target_pid))
target_samples++;
}
EXPECT_GT(target_samples, 0) << "packets.size(): " << packets.size()
<< ", total_perf_packets: " << total_perf_packets
<< ", total_samples: " << total_samples << "\n";
}
void AssertNoStacksForPid(std::vector<protos::gen::TracePacket> packets,
int target_pid) {
// The process can still be sampled, but the stacks should be discarded
// without unwinding.
for (const auto& packet : packets) {
if (packet.perf_sample().pid() == static_cast<uint32_t>(target_pid)) {
EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);
EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());
}
}
}
TEST(TracedPerfCtsTest, SystemWideDebuggableApp) {
if (!HasPerfLsmHooks())
return;
std::string app_name = "android.perfetto.cts.app.debuggable";
const auto& packets = ProfileSystemWide(app_name);
int app_pid = PidForProcessName(app_name);
ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
AssertHasSampledStacksForPid(packets, app_pid);
PERFETTO_CHECK(IsAppRunning(app_name));
StopApp(app_name);
}
TEST(TracedPerfCtsTest, SystemWideProfileableApp) {
if (!HasPerfLsmHooks())
return;
std::string app_name = "android.perfetto.cts.app.profileable";
const auto& packets = ProfileSystemWide(app_name);
int app_pid = PidForProcessName(app_name);
ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
AssertHasSampledStacksForPid(packets, app_pid);
PERFETTO_CHECK(IsAppRunning(app_name));
StopApp(app_name);
}
TEST(TracedPerfCtsTest, SystemWideReleaseApp) {
if (!HasPerfLsmHooks())
return;
std::string app_name = "android.perfetto.cts.app.release";
const auto& packets = ProfileSystemWide(app_name);
int app_pid = PidForProcessName(app_name);
ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
if (IsDebuggableBuild())
AssertHasSampledStacksForPid(packets, app_pid);
else
AssertNoStacksForPid(packets, app_pid);
PERFETTO_CHECK(IsAppRunning(app_name));
StopApp(app_name);
}
} // namespace
} // namespace perfetto
<|endoftext|> |
<commit_before>#include <os>
#include <iostream>
using namespace std;
struct TestAddr
{
// constructors
TestAddr()
: i64{0, 0} {}
TestAddr(uint32_t a, uint32_t b, uint32_t c, uint32_t d)
: i32{a, b, c, d} {}
TestAddr(uint64_t top, uint64_t bot)
: i64{top, bot} {}
// copy-constructor
TestAddr(const TestAddr& a)
{
printf("TestAddr copy constructor\n");
printf("TestAddr %s\n", a.to_string().c_str());
this->i64[0] = a.i64[0];
this->i64[1] = a.i64[1];
}
// move constructor
TestAddr& operator= (const TestAddr& a)
{
printf("TestAddr move constructor\n");
printf("TestAddr %s\n", a.to_string().c_str());
this->i64[0] = a.i64[0];
this->i64[1] = a.i64[1];
return *this;
}
// returns this IPv6 address as a string
std::string to_string() const;
// fields
uint64_t i64[2];
uint32_t i32[4];
uint16_t i16[8];
uint8_t i8[16];
};
const std::string lut = "0123456789abcdef";
std::string TestAddr::to_string() const
{
//const std::string lut = "0123456789abcdef";
std::string ret(40, '\0');
int counter = 0;
const uint8_t* octet = i8;
for (int i = 0; i < 16; i++)
{
ret[counter++] = 'c'; //lut[(octet[i] & 0xF0) >> 4];
ret[counter++] = 'd'; //lut[(octet[i] & 0x0F) >> 0];
if (i & 1)
ret[counter++] = ':';
}
printf("string: %s len: %d\n", ret.c_str(), counter);
ret[counter-1] = 0;
return ret;
}
void Service::start()
{
std::cout << "*** Service is up - with OS Included! ***" << std::endl;
TestAddr ip6(1234, 1234);
register void* sp asm ("sp");
printf("stack: %p\n", sp);
TestAddr test = ip6;
std::cout << "ip6 = " << ip6.to_string() << std::endl;
printf("ipv6 %s\n", ip6.to_string().c_str());
}
<commit_msg>Another testcase<commit_after>#include <os>
#include <iostream>
#include <x86intrin.h>
using namespace std;
#define SSE_ALIGNED alignof(__m128i)
struct TestAddr
{
// constructors
TestAddr()
: i64{0, 0} {}
TestAddr(uint32_t a, uint32_t b, uint32_t c, uint32_t d)
: i32{a, b, c, d} {}
TestAddr(uint64_t top, uint64_t bot)
: i64{top, bot} {}
// copy-constructor
TestAddr(const TestAddr& a)
{
printf("TestAddr copy constructor\n");
printf("TestAddr %s\n", a.to_string().c_str());
this->i64[0] = a.i64[0];
this->i64[1] = a.i64[1];
}
// move constructor
TestAddr& operator= (const TestAddr& a)
{
printf("TestAddr move constructor\n");
printf("TestAddr %s\n", a.to_string().c_str());
this->i64[0] = a.i64[0];
this->i64[1] = a.i64[1];
return *this;
}
// returns this IPv6 address as a string
std::string to_string() const;
// fields
uint64_t i64[2];
uint32_t i32[4];
uint16_t i16[8];
uint8_t i8[16];
}; // __attribute__((aligned(SSE_ALIGNED)));
const std::string lut = "0123456789abcdef";
const std::string test = ""; // uncommenting this makes the image work
std::string TestAddr::to_string() const
{
//static const std::string lut = "0123456789abcdef";
std::string ret(40, '\0');
int counter = 0;
const uint8_t* octet = i8;
for (size_t i = 0; i < sizeof(i8); i++)
{
ret[counter++] = lut[(octet[i] & 0xF0) >> 4];
ret[counter++] = lut[(octet[i] & 0x0F) >> 0];
if (i & 1)
ret[counter++] = ':';
}
ret[counter-1] = 0;
//printf("string: %s len: %d\n", ret.c_str(), counter);
return ret;
}
void Service::start()
{
std::cout << "*** Service is up - with OS Included! ***" << std::endl;
TestAddr ip6(1234, 1234);
register void* sp asm ("sp");
printf("stack: %p\n", sp);
TestAddr test = ip6;
std::cout << "ip6 = " << ip6.to_string() << std::endl;
printf("ipv6 %s\n", ip6.to_string().c_str());
}
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#define BH_TIMING_SUM
#include <bh_timing.hpp>
#include <bh_component.h>
#include "component_interface.h"
#include "expander.hpp"
//
// Components
//
static bh_component myself; // Myself
static bh_component_iface *child; // My child
// The timing ID for the filter
static bh_intp exec_timing;
static bool timing;
static bohrium::filter::composite::Expander* expander = NULL;
//
// Component interface init/execute/shutdown
//
bh_error bh_filter_bcexp_init(const char* name)
{
bh_error err; // Initialize myself
if ((err = bh_component_init(&myself, name)) != BH_SUCCESS) {
return err;
}
if (myself.nchildren != 1) { // For now only one child is supported
fprintf(stderr,
"[FILTER-bcexp] Only a single child is supported, has %lld.",
myself.nchildren);
return BH_ERROR;
}
timing = bh_component_config_lookup_bool(&myself, "timing", false);
if (timing)
exec_timing = bh_timer_new("[BC-Exp] Execution");
child = &myself.children[0]; // Initiate child
if ((err = child->init(child->name)) != 0) {
return err;
}
bh_intp gc_threshold, sign, matmul, powk, repeat, reduce1d;
if ((BH_SUCCESS!=bh_component_config_int_option(&myself, "gc_threshold", 0, 2000, &gc_threshold)) or \
(BH_SUCCESS!=bh_component_config_int_option(&myself, "matmul", 0, 1, &matmul)) or \
(BH_SUCCESS!=bh_component_config_int_option(&myself, "sign", 0, 1, &sign)) or \
(BH_SUCCESS!=bh_component_config_int_option(&myself, "powk", 0, 1, &powk)) or \
(BH_SUCCESS!=bh_component_config_int_option(&myself, "repeat", 0, 1, &repeat))) {
return BH_ERROR;
}
reduce1d = bh_component_config_lookup_int(&myself, "reduce1d", 0);
try { // Construct the expander
expander = new bohrium::filter::composite::Expander(gc_threshold,
matmul,
sign,
powk,
reduce1d,
repeat);
} catch (std::bad_alloc& ba) {
fprintf(stderr, "Failed constructing Expander due to allocation error.\n");
}
if (NULL == expander) {
return BH_ERROR;
} else {
return BH_SUCCESS;
}
}
bh_error bh_filter_bcexp_shutdown(void)
{
bh_error err = child->shutdown();
bh_component_destroy(&myself);
delete expander;
expander = NULL;
if (timing)
bh_timer_finalize(exec_timing);
return err;
}
bh_error bh_filter_bcexp_extmethod(const char *name, bh_opcode opcode)
{
return child->extmethod(name, opcode);
}
bh_error bh_filter_bcexp_execute(bh_ir* bhir)
{
bh_uint64 start = 0;
if (timing)
start = bh_timer_stamp();
expander->expand(*bhir); // Expand composites
if (timing)
bh_timer_add(exec_timing, start, bh_timer_stamp());
bh_error res = child->execute(bhir); // Send the bhir down the stack
if (timing)
start = bh_timer_stamp();
expander->gc(); // Collect garbage
if (timing)
bh_timer_add(exec_timing, start, bh_timer_stamp());
return res; // Send result up the stack
}
<commit_msg>[bcexp] Defaults for component values<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#define BH_TIMING_SUM
#include <bh_timing.hpp>
#include <bh_component.h>
#include "component_interface.h"
#include "expander.hpp"
//
// Components
//
static bh_component myself; // Myself
static bh_component_iface *child; // My child
// The timing ID for the filter
static bh_intp exec_timing;
static bool timing;
static bohrium::filter::composite::Expander* expander = NULL;
//
// Component interface init/execute/shutdown
//
bh_error bh_filter_bcexp_init(const char* name)
{
bh_error err; // Initialize myself
if ((err = bh_component_init(&myself, name)) != BH_SUCCESS) {
return err;
}
if (myself.nchildren != 1) { // For now only one child is supported
fprintf(stderr,
"[FILTER-bcexp] Only a single child is supported, has %lld.",
myself.nchildren);
return BH_ERROR;
}
timing = bh_component_config_lookup_bool(&myself, "timing", false);
if (timing)
exec_timing = bh_timer_new("[BC-Exp] Execution");
child = &myself.children[0]; // Initiate child
if ((err = child->init(child->name)) != 0) {
return err;
}
try { // Construct the expander
expander = new bohrium::filter::composite::Expander(
bh_component_config_lookup_int( &myself, "gc_threshold", 400),
bh_component_config_lookup_bool(&myself, "matmul", true),
bh_component_config_lookup_bool(&myself, "sign", true),
bh_component_config_lookup_bool(&myself, "powk", true),
bh_component_config_lookup_bool(&myself, "reduce1d", false),
bh_component_config_lookup_bool(&myself, "repeat", true)
);
} catch (std::bad_alloc& ba) {
fprintf(stderr, "Failed constructing Expander due to allocation error.\n");
return BH_ERROR;
}
return BH_SUCCESS;
}
bh_error bh_filter_bcexp_shutdown(void)
{
bh_error err = child->shutdown();
bh_component_destroy(&myself);
delete expander;
expander = NULL;
if (timing)
bh_timer_finalize(exec_timing);
return err;
}
bh_error bh_filter_bcexp_extmethod(const char *name, bh_opcode opcode)
{
return child->extmethod(name, opcode);
}
bh_error bh_filter_bcexp_execute(bh_ir* bhir)
{
bh_uint64 start = 0;
if (timing)
start = bh_timer_stamp();
expander->expand(*bhir); // Expand composites
if (timing)
bh_timer_add(exec_timing, start, bh_timer_stamp());
bh_error res = child->execute(bhir); // Send the bhir down the stack
if (timing)
start = bh_timer_stamp();
expander->gc(); // Collect garbage
if (timing)
bh_timer_add(exec_timing, start, bh_timer_stamp());
return res; // Send result up the stack
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
<commit_msg>Added Fusion style to application.<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QStyleFactory>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle(QStyleFactory::create("Fusion"));
for(int i = 0; i < QStyleFactory::keys().size(); i++)
{
qDebug() << QStyleFactory::keys()[i];
}
MainWindow w;
w.show();
return a.exec();
}
<|endoftext|> |
<commit_before>6ff6c89a-5216-11e5-915d-6c40088e03e4<commit_msg>6ffd6a1a-5216-11e5-8b23-6c40088e03e4<commit_after>6ffd6a1a-5216-11e5-8b23-6c40088e03e4<|endoftext|> |
<commit_before>cbb6fd97-327f-11e5-863e-9cf387a8033e<commit_msg>cbc46de6-327f-11e5-b01d-9cf387a8033e<commit_after>cbc46de6-327f-11e5-b01d-9cf387a8033e<|endoftext|> |
<commit_before>#include <specs/specs.h>
go_bandit([](){
describe("dots_reporter:", [&](){
unique_ptr<std::stringstream> stm;
unique_ptr<bandit::dots_reporter> reporter;
before_each([&](){
stm = unique_ptr<std::stringstream>(new std::stringstream());
reporter = unique_ptr<bandit::dots_reporter>(new dots_reporter(*(stm.get())));
});
auto output = [&](){ return stm->str(); };
describe("an empty test run", [&](){
before_each([&](){
reporter->test_run_starting();
reporter->test_run_complete();
});
it("reports no tests where run", [&](){
AssertThat(output(), Equals("\nCould not find any tests.\n"));
});
});
describe("a successful test run", [&](){
before_each([&](){
reporter->test_run_starting();
reporter->context_starting("my context");
reporter->it_starting("my test");
reporter->it_succeeded("my test");
reporter->context_ended("my context");
reporter->test_run_complete();
});
it("reports a successful test run", [&](){
AssertThat(output(), EndsWith("Test run complete. 1 tests run. 1 succeeded.\n"));
});
});
describe("a failing test run", [&](){
before_each([&](){
reporter->test_run_starting();
reporter->context_starting("my context");
reporter->it_starting("my test");
assertion_exception exception("assertion failed!", "some_file", 123);
reporter->it_failed("my test", exception);
reporter->context_ended("my context");
reporter->test_run_complete();
});
it("reports a failing test run in summary", [&](){
AssertThat(output(), EndsWith("Test run complete. 1 tests run. 0 succeeded. 1 failed.\n"));
});
it("reports the failed assertion", [&](){
AssertThat(output(), Contains("some_file:123: assertion failed!"));
});
});
});
});
<commit_msg>dots_reporter displays progress.<commit_after>#include <specs/specs.h>
go_bandit([](){
describe("dots_reporter:", [&](){
unique_ptr<std::stringstream> stm;
unique_ptr<bandit::dots_reporter> reporter;
before_each([&](){
stm = unique_ptr<std::stringstream>(new std::stringstream());
reporter = unique_ptr<bandit::dots_reporter>(new dots_reporter(*(stm.get())));
});
auto output = [&](){ return stm->str(); };
describe("an empty test run", [&](){
before_each([&](){
reporter->test_run_starting();
reporter->test_run_complete();
});
it("reports no tests where run", [&](){
AssertThat(output(), Equals("\nCould not find any tests.\n"));
});
});
describe("a successful test run", [&](){
before_each([&](){
reporter->test_run_starting();
reporter->context_starting("my context");
reporter->it_starting("my test");
reporter->it_succeeded("my test");
reporter->context_ended("my context");
reporter->test_run_complete();
});
it("reports a successful test run", [&](){
AssertThat(output(), EndsWith("Test run complete. 1 tests run. 1 succeeded.\n"));
});
it("displays a dot for the successful test", [&](){
AssertThat(output(), StartsWith("."));
});
});
describe("a failing test run", [&](){
before_each([&](){
reporter->test_run_starting();
reporter->context_starting("my context");
reporter->it_starting("my test");
assertion_exception exception("assertion failed!", "some_file", 123);
reporter->it_failed("my test", exception);
reporter->context_ended("my context");
reporter->test_run_complete();
});
it("reports a failing test run in summary", [&](){
AssertThat(output(), EndsWith("Test run complete. 1 tests run. 0 succeeded. 1 failed.\n"));
});
it("reports the failed assertion", [&](){
AssertThat(output(), Contains("some_file:123: assertion failed!"));
});
it("reports an 'F' for the failed assertion", [&](){
AssertThat(output(), StartsWith("F"));
});
});
});
});
<|endoftext|> |
<commit_before>a2289e42-ad59-11e7-be2c-ac87a332f658<commit_msg>Initial commit.2<commit_after>a3af24de-ad59-11e7-8b12-ac87a332f658<|endoftext|> |
<commit_before>a92e9a9c-35ca-11e5-9051-6c40088e03e4<commit_msg>a93656b0-35ca-11e5-965d-6c40088e03e4<commit_after>a93656b0-35ca-11e5-965d-6c40088e03e4<|endoftext|> |
<commit_before>8e93eef8-2e4f-11e5-873a-28cfe91dbc4b<commit_msg>8e9c8535-2e4f-11e5-90d9-28cfe91dbc4b<commit_after>8e9c8535-2e4f-11e5-90d9-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include "Coordinate.h"
#include "Maze.h"
using std::vector;
using std::string;
const Coordinate dirs[] = {
Coordinate( -1, 0 ),
Coordinate( 0, 1 ),
Coordinate( 0, -1 ),
Coordinate( 1, 0 )
};
const char left[] = { 'a', 'h' };
const char down[] = { 's', 'j' };
const char up[] = { 'w', 'k' };
const char right[] = { 'd', 'l' };
bool isPartOf( const char arr[], char val ){
return arr[0] == val || arr[1] == val;
}
int main(){
std::cout << "program begin" << std::endl << std::endl;
int w = 21, h = 21;
string inputW, inputH;
std::cout << "maze width (20): ";
std::getline( std::cin, inputW );
if( !inputW.empty() )
w = std::stoi( inputW );
std::cout << "maze height (20): ";
std::getline( std::cin, inputH );
if( !inputH.empty() )
h = std::stoi( inputH );
if( w % 2 == 0 )
w += 1;
if( h % 2 == 0 )
h += 1;
Maze maze( w, h );
vector<vector<char>> map;
Coordinate player( 1, 1 );
string dir;
int round = 0;
int security = 1000;
while( --security > 0 && !( player.x == maze.goal.x && player.y == maze.goal.y ) ){
std::cout << "start frame" << std::endl;
maze.fillPrintMap( map );
map[ player.x ][ player.y ] = 'o';
std::system( "clear" );
std::cout << std::endl << " Round: " << ++round << "\t pos: [" << player.x << "," << player.y << "]" << std::endl << std::endl;
for( int i = 0; i < w; ++i ){
std::cout << " ";
for( int j = 0; j < h; ++j ){
std::cout << map[j][i];
}
std::cout << std::endl;
}
std::cout << std::endl << " next moves (hjkl/aswd+ENTER): ";
std::cin >> dir;
unsigned int dirIndex = -1;
while( ++dirIndex < dir.length() ){
if( isPartOf( left, dir[ dirIndex ] ) && !maze.getCell( player + dirs[0] ) ){
player = player + dirs[ 0 ];
}
if( isPartOf( down, dir[ dirIndex ] ) && !maze.getCell( player + dirs[1] ) ){
player = player + dirs[ 1 ];
}
if( isPartOf( up, dir[ dirIndex ] ) && !maze.getCell( player + dirs[2] ) ){
player = player + dirs[ 2 ];
}
if( isPartOf( right, dir[ dirIndex ] ) && !maze.getCell( player + dirs[3] ) ){
player = player + dirs[ 3 ];
}
}
}
std::cout << security << std::endl;
if( security == 0 )
std::cout << "took too much, we were afraid the program broke" << std::endl;
else
std::cout << "YOU WIN!" << std::endl;
std::cout << std::endl << "program end" << std::endl;
return 0;
}
<commit_msg>fixed direction size error<commit_after>#include <iostream>
#include <vector>
#include <string>
#include "Coordinate.h"
#include "Maze.h"
using std::vector;
using std::string;
const Coordinate dirs[] = {
Coordinate( -1, 0 ),
Coordinate( 0, 1 ),
Coordinate( 0, -1 ),
Coordinate( 1, 0 )
};
const char left[] = { 'a', 'h' };
const char down[] = { 's', 'j' };
const char up[] = { 'w', 'k' };
const char right[] = { 'd', 'l' };
bool isPartOf( const char arr[], char val ){
return arr[0] == val || arr[1] == val;
}
int main(){
std::cout << "program begin" << std::endl << std::endl;
int w = 21, h = 21;
string inputW, inputH;
std::cout << "maze width (20): ";
std::getline( std::cin, inputW );
if( !inputW.empty() )
w = std::stoi( inputW );
std::cout << "maze height (20): ";
std::getline( std::cin, inputH );
if( !inputH.empty() )
h = std::stoi( inputH );
if( w % 2 == 0 )
w += 1;
if( h % 2 == 0 )
h += 1;
Maze maze( w, h );
vector<vector<char>> map;
Coordinate player( 1, 1 );
string dir;
int round = 0;
int security = 1000;
while( --security > 0 && !( player.x == maze.goal.x && player.y == maze.goal.y ) ){
std::cout << "start frame" << std::endl;
maze.fillPrintMap( map );
map[ player.x ][ player.y ] = 'o';
std::system( "clear" );
std::cout << std::endl << " Round: " << ++round << "\t pos: [" << player.x << "," << player.y << "]" << std::endl << std::endl;
for( int i = 0; i < h; ++i ){
std::cout << " ";
for( int j = 0; j < w; ++j ){
std::cout << map[j][i];
}
std::cout << std::endl;
}
std::cout << std::endl << " next moves (hjkl/aswd+ENTER): ";
std::cin >> dir;
unsigned int dirIndex = -1;
while( ++dirIndex < dir.length() ){
if( isPartOf( left, dir[ dirIndex ] ) && !maze.getCell( player + dirs[0] ) ){
player = player + dirs[ 0 ];
}
if( isPartOf( down, dir[ dirIndex ] ) && !maze.getCell( player + dirs[1] ) ){
player = player + dirs[ 1 ];
}
if( isPartOf( up, dir[ dirIndex ] ) && !maze.getCell( player + dirs[2] ) ){
player = player + dirs[ 2 ];
}
if( isPartOf( right, dir[ dirIndex ] ) && !maze.getCell( player + dirs[3] ) ){
player = player + dirs[ 3 ];
}
}
}
std::cout << security << std::endl;
if( security == 0 )
std::cout << "took too much, we were afraid the program broke" << std::endl;
else
std::cout << "YOU WIN!" << std::endl;
std::cout << std::endl << "program end" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>c3641afd-327f-11e5-9535-9cf387a8033e<commit_msg>c36a88eb-327f-11e5-9fbd-9cf387a8033e<commit_after>c36a88eb-327f-11e5-9fbd-9cf387a8033e<|endoftext|> |
<commit_before>070602f0-2f67-11e5-b189-6c40088e03e4<commit_msg>070cb0fa-2f67-11e5-af7d-6c40088e03e4<commit_after>070cb0fa-2f67-11e5-af7d-6c40088e03e4<|endoftext|> |
<commit_before>5bf67435-2d16-11e5-af21-0401358ea401<commit_msg>5bf67436-2d16-11e5-af21-0401358ea401<commit_after>5bf67436-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
* Ali Saidi
*/
#ifndef __ARCH_SPARC_MISCREGFILE_HH__
#define __ARCH_SPARC_MISCREGFILE_HH__
#include "arch/sparc/faults.hh"
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/types.hh"
#include "cpu/cpuevent.hh"
#include <string>
namespace SparcISA
{
//These functions map register indices to names
std::string getMiscRegName(RegIndex);
enum MiscRegIndex
{
/** Ancillary State Registers */
// MISCREG_Y,
// MISCREG_CCR,
MISCREG_ASI,
MISCREG_TICK,
MISCREG_FPRS,
MISCREG_PCR,
MISCREG_PIC,
MISCREG_GSR,
MISCREG_SOFTINT_SET,
MISCREG_SOFTINT_CLR,
MISCREG_SOFTINT, /* 10 */
MISCREG_TICK_CMPR,
MISCREG_STICK,
MISCREG_STICK_CMPR,
/** Privilged Registers */
MISCREG_TPC,
MISCREG_TNPC,
MISCREG_TSTATE,
MISCREG_TT,
MISCREG_PRIVTICK,
MISCREG_TBA,
MISCREG_PSTATE, /* 20 */
MISCREG_TL,
MISCREG_PIL,
MISCREG_CWP,
// MISCREG_CANSAVE,
// MISCREG_CANRESTORE,
// MISCREG_CLEANWIN,
// MISCREG_OTHERWIN,
// MISCREG_WSTATE,
MISCREG_GL,
/** Hyper privileged registers */
MISCREG_HPSTATE, /* 30 */
MISCREG_HTSTATE,
MISCREG_HINTP,
MISCREG_HTBA,
MISCREG_HVER,
MISCREG_STRAND_STS_REG,
MISCREG_HSTICK_CMPR,
/** Floating Point Status Register */
MISCREG_FSR,
/** MMU Internal Registers */
MISCREG_MMU_P_CONTEXT,
MISCREG_MMU_S_CONTEXT, /* 40 */
MISCREG_MMU_PART_ID,
MISCREG_MMU_LSU_CTRL,
MISCREG_MMU_ITLB_C0_TSB_PS0,
MISCREG_MMU_ITLB_C0_TSB_PS1,
MISCREG_MMU_ITLB_C0_CONFIG,
MISCREG_MMU_ITLB_CX_TSB_PS0,
MISCREG_MMU_ITLB_CX_TSB_PS1,
MISCREG_MMU_ITLB_CX_CONFIG,
MISCREG_MMU_ITLB_SFSR,
MISCREG_MMU_ITLB_TAG_ACCESS, /* 50 */
MISCREG_MMU_DTLB_C0_TSB_PS0,
MISCREG_MMU_DTLB_C0_TSB_PS1,
MISCREG_MMU_DTLB_C0_CONFIG,
MISCREG_MMU_DTLB_CX_TSB_PS0,
MISCREG_MMU_DTLB_CX_TSB_PS1,
MISCREG_MMU_DTLB_CX_CONFIG,
MISCREG_MMU_DTLB_SFSR,
MISCREG_MMU_DTLB_SFAR,
MISCREG_MMU_DTLB_TAG_ACCESS,
/** Scratchpad regiscers **/
MISCREG_SCRATCHPAD_R0, /* 60 */
MISCREG_SCRATCHPAD_R1,
MISCREG_SCRATCHPAD_R2,
MISCREG_SCRATCHPAD_R3,
MISCREG_SCRATCHPAD_R4,
MISCREG_SCRATCHPAD_R5,
MISCREG_SCRATCHPAD_R6,
MISCREG_SCRATCHPAD_R7,
/* CPU Queue Registers */
MISCREG_QUEUE_CPU_MONDO_HEAD,
MISCREG_QUEUE_CPU_MONDO_TAIL,
MISCREG_QUEUE_DEV_MONDO_HEAD, /* 70 */
MISCREG_QUEUE_DEV_MONDO_TAIL,
MISCREG_QUEUE_RES_ERROR_HEAD,
MISCREG_QUEUE_RES_ERROR_TAIL,
MISCREG_QUEUE_NRES_ERROR_HEAD,
MISCREG_QUEUE_NRES_ERROR_TAIL,
/* All the data for the TLB packed up in one register. */
MISCREG_TLB_DATA,
MISCREG_NUMMISCREGS
};
struct HPSTATE {
const static uint64_t id = 0x800; // this impl. dependent (id) field m
const static uint64_t ibe = 0x400;
const static uint64_t red = 0x20;
const static uint64_t hpriv = 0x4;
const static uint64_t tlz = 0x1;
};
struct PSTATE {
const static int cle = 0x200;
const static int tle = 0x100;
const static int mm = 0xC0;
const static int pef = 0x10;
const static int am = 0x8;
const static int priv = 0x4;
const static int ie = 0x2;
};
const int NumMiscArchRegs = MISCREG_NUMMISCREGS;
const int NumMiscRegs = MISCREG_NUMMISCREGS;
// The control registers, broken out into fields
class MiscRegFile
{
private:
/* ASR Registers */
//uint64_t y; // Y (used in obsolete multiplication)
//uint8_t ccr; // Condition Code Register
uint8_t asi; // Address Space Identifier
uint64_t tick; // Hardware clock-tick counter
uint8_t fprs; // Floating-Point Register State
uint64_t gsr; // General Status Register
uint64_t softint;
uint64_t tick_cmpr; // Hardware tick compare registers
uint64_t stick; // Hardware clock-tick counter
uint64_t stick_cmpr; // Hardware tick compare registers
/* Privileged Registers */
uint64_t tpc[MaxTL]; // Trap Program Counter (value from
// previous trap level)
uint64_t tnpc[MaxTL]; // Trap Next Program Counter (value from
// previous trap level)
uint64_t tstate[MaxTL]; // Trap State
uint16_t tt[MaxTL]; // Trap Type (Type of trap which occured
// on the previous level)
uint64_t tba; // Trap Base Address
uint16_t pstate; // Process State Register
uint8_t tl; // Trap Level
uint8_t pil; // Process Interrupt Register
uint8_t cwp; // Current Window Pointer
//uint8_t cansave; // Savable windows
//uint8_t canrestore; // Restorable windows
//uint8_t cleanwin; // Clean windows
//uint8_t otherwin; // Other windows
//uint8_t wstate; // Window State
uint8_t gl; // Global level register
/** Hyperprivileged Registers */
uint64_t hpstate; // Hyperprivileged State Register
uint64_t htstate[MaxTL];// Hyperprivileged Trap State Register
uint64_t hintp;
uint64_t htba; // Hyperprivileged Trap Base Address register
uint64_t hstick_cmpr; // Hardware tick compare registers
uint64_t strandStatusReg;// Per strand status register
/** Floating point misc registers. */
uint64_t fsr; // Floating-Point State Register
/** MMU Internal Registers */
uint16_t priContext;
uint16_t secContext;
uint16_t partId;
uint64_t lsuCtrlReg;
uint64_t iTlbC0TsbPs0;
uint64_t iTlbC0TsbPs1;
uint64_t iTlbC0Config;
uint64_t iTlbCXTsbPs0;
uint64_t iTlbCXTsbPs1;
uint64_t iTlbCXConfig;
uint64_t iTlbSfsr;
uint64_t iTlbTagAccess;
uint64_t dTlbC0TsbPs0;
uint64_t dTlbC0TsbPs1;
uint64_t dTlbC0Config;
uint64_t dTlbCXTsbPs0;
uint64_t dTlbCXTsbPs1;
uint64_t dTlbCXConfig;
uint64_t dTlbSfsr;
uint64_t dTlbSfar;
uint64_t dTlbTagAccess;
uint64_t scratchPad[8];
uint64_t cpu_mondo_head;
uint64_t cpu_mondo_tail;
uint64_t dev_mondo_head;
uint64_t dev_mondo_tail;
uint64_t res_error_head;
uint64_t res_error_tail;
uint64_t nres_error_head;
uint64_t nres_error_tail;
// These need to check the int_dis field and if 0 then
// set appropriate bit in softint and checkinterrutps on the cpu
#if FULL_SYSTEM
void setFSRegWithEffect(int miscReg, const MiscReg &val,
ThreadContext *tc);
MiscReg readFSRegWithEffect(int miscReg, ThreadContext * tc);
// Update interrupt state on softint or pil change
void checkSoftInt(ThreadContext *tc);
/** Process a tick compare event and generate an interrupt on the cpu if
* appropriate. */
void processTickCompare(ThreadContext *tc);
void processSTickCompare(ThreadContext *tc);
void processHSTickCompare(ThreadContext *tc);
typedef CpuEventWrapper<MiscRegFile,
&MiscRegFile::processTickCompare> TickCompareEvent;
TickCompareEvent *tickCompare;
typedef CpuEventWrapper<MiscRegFile,
&MiscRegFile::processSTickCompare> STickCompareEvent;
STickCompareEvent *sTickCompare;
typedef CpuEventWrapper<MiscRegFile,
&MiscRegFile::processHSTickCompare> HSTickCompareEvent;
HSTickCompareEvent *hSTickCompare;
#endif
public:
void clear();
MiscRegFile()
{
clear();
}
MiscReg readReg(int miscReg);
MiscReg readRegWithEffect(int miscReg, ThreadContext *tc);
void setReg(int miscReg, const MiscReg &val);
void setRegWithEffect(int miscReg,
const MiscReg &val, ThreadContext * tc);
int getInstAsid()
{
return priContext | (uint32_t)partId << 13;
}
int getDataAsid()
{
return priContext | (uint32_t)partId << 13;
}
void serialize(std::ostream & os);
void unserialize(Checkpoint * cp, const std::string & section);
void copyMiscRegs(ThreadContext * tc);
protected:
bool isHyperPriv() { return (hpstate & (1 << 2)); }
bool isPriv() { return (hpstate & (1 << 2)) || (pstate & (1 << 2)); }
bool isNonPriv() { return !isPriv(); }
};
}
#endif
<commit_msg>Add in a declaration of class Checkpoint rather than expecting it to come from some other include.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
* Ali Saidi
*/
#ifndef __ARCH_SPARC_MISCREGFILE_HH__
#define __ARCH_SPARC_MISCREGFILE_HH__
#include "arch/sparc/faults.hh"
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/types.hh"
#include "cpu/cpuevent.hh"
#include <string>
class Checkpoint;
namespace SparcISA
{
//These functions map register indices to names
std::string getMiscRegName(RegIndex);
enum MiscRegIndex
{
/** Ancillary State Registers */
// MISCREG_Y,
// MISCREG_CCR,
MISCREG_ASI,
MISCREG_TICK,
MISCREG_FPRS,
MISCREG_PCR,
MISCREG_PIC,
MISCREG_GSR,
MISCREG_SOFTINT_SET,
MISCREG_SOFTINT_CLR,
MISCREG_SOFTINT, /* 10 */
MISCREG_TICK_CMPR,
MISCREG_STICK,
MISCREG_STICK_CMPR,
/** Privilged Registers */
MISCREG_TPC,
MISCREG_TNPC,
MISCREG_TSTATE,
MISCREG_TT,
MISCREG_PRIVTICK,
MISCREG_TBA,
MISCREG_PSTATE, /* 20 */
MISCREG_TL,
MISCREG_PIL,
MISCREG_CWP,
// MISCREG_CANSAVE,
// MISCREG_CANRESTORE,
// MISCREG_CLEANWIN,
// MISCREG_OTHERWIN,
// MISCREG_WSTATE,
MISCREG_GL,
/** Hyper privileged registers */
MISCREG_HPSTATE, /* 30 */
MISCREG_HTSTATE,
MISCREG_HINTP,
MISCREG_HTBA,
MISCREG_HVER,
MISCREG_STRAND_STS_REG,
MISCREG_HSTICK_CMPR,
/** Floating Point Status Register */
MISCREG_FSR,
/** MMU Internal Registers */
MISCREG_MMU_P_CONTEXT,
MISCREG_MMU_S_CONTEXT, /* 40 */
MISCREG_MMU_PART_ID,
MISCREG_MMU_LSU_CTRL,
MISCREG_MMU_ITLB_C0_TSB_PS0,
MISCREG_MMU_ITLB_C0_TSB_PS1,
MISCREG_MMU_ITLB_C0_CONFIG,
MISCREG_MMU_ITLB_CX_TSB_PS0,
MISCREG_MMU_ITLB_CX_TSB_PS1,
MISCREG_MMU_ITLB_CX_CONFIG,
MISCREG_MMU_ITLB_SFSR,
MISCREG_MMU_ITLB_TAG_ACCESS, /* 50 */
MISCREG_MMU_DTLB_C0_TSB_PS0,
MISCREG_MMU_DTLB_C0_TSB_PS1,
MISCREG_MMU_DTLB_C0_CONFIG,
MISCREG_MMU_DTLB_CX_TSB_PS0,
MISCREG_MMU_DTLB_CX_TSB_PS1,
MISCREG_MMU_DTLB_CX_CONFIG,
MISCREG_MMU_DTLB_SFSR,
MISCREG_MMU_DTLB_SFAR,
MISCREG_MMU_DTLB_TAG_ACCESS,
/** Scratchpad regiscers **/
MISCREG_SCRATCHPAD_R0, /* 60 */
MISCREG_SCRATCHPAD_R1,
MISCREG_SCRATCHPAD_R2,
MISCREG_SCRATCHPAD_R3,
MISCREG_SCRATCHPAD_R4,
MISCREG_SCRATCHPAD_R5,
MISCREG_SCRATCHPAD_R6,
MISCREG_SCRATCHPAD_R7,
/* CPU Queue Registers */
MISCREG_QUEUE_CPU_MONDO_HEAD,
MISCREG_QUEUE_CPU_MONDO_TAIL,
MISCREG_QUEUE_DEV_MONDO_HEAD, /* 70 */
MISCREG_QUEUE_DEV_MONDO_TAIL,
MISCREG_QUEUE_RES_ERROR_HEAD,
MISCREG_QUEUE_RES_ERROR_TAIL,
MISCREG_QUEUE_NRES_ERROR_HEAD,
MISCREG_QUEUE_NRES_ERROR_TAIL,
/* All the data for the TLB packed up in one register. */
MISCREG_TLB_DATA,
MISCREG_NUMMISCREGS
};
struct HPSTATE {
const static uint64_t id = 0x800; // this impl. dependent (id) field m
const static uint64_t ibe = 0x400;
const static uint64_t red = 0x20;
const static uint64_t hpriv = 0x4;
const static uint64_t tlz = 0x1;
};
struct PSTATE {
const static int cle = 0x200;
const static int tle = 0x100;
const static int mm = 0xC0;
const static int pef = 0x10;
const static int am = 0x8;
const static int priv = 0x4;
const static int ie = 0x2;
};
const int NumMiscArchRegs = MISCREG_NUMMISCREGS;
const int NumMiscRegs = MISCREG_NUMMISCREGS;
// The control registers, broken out into fields
class MiscRegFile
{
private:
/* ASR Registers */
//uint64_t y; // Y (used in obsolete multiplication)
//uint8_t ccr; // Condition Code Register
uint8_t asi; // Address Space Identifier
uint64_t tick; // Hardware clock-tick counter
uint8_t fprs; // Floating-Point Register State
uint64_t gsr; // General Status Register
uint64_t softint;
uint64_t tick_cmpr; // Hardware tick compare registers
uint64_t stick; // Hardware clock-tick counter
uint64_t stick_cmpr; // Hardware tick compare registers
/* Privileged Registers */
uint64_t tpc[MaxTL]; // Trap Program Counter (value from
// previous trap level)
uint64_t tnpc[MaxTL]; // Trap Next Program Counter (value from
// previous trap level)
uint64_t tstate[MaxTL]; // Trap State
uint16_t tt[MaxTL]; // Trap Type (Type of trap which occured
// on the previous level)
uint64_t tba; // Trap Base Address
uint16_t pstate; // Process State Register
uint8_t tl; // Trap Level
uint8_t pil; // Process Interrupt Register
uint8_t cwp; // Current Window Pointer
//uint8_t cansave; // Savable windows
//uint8_t canrestore; // Restorable windows
//uint8_t cleanwin; // Clean windows
//uint8_t otherwin; // Other windows
//uint8_t wstate; // Window State
uint8_t gl; // Global level register
/** Hyperprivileged Registers */
uint64_t hpstate; // Hyperprivileged State Register
uint64_t htstate[MaxTL];// Hyperprivileged Trap State Register
uint64_t hintp;
uint64_t htba; // Hyperprivileged Trap Base Address register
uint64_t hstick_cmpr; // Hardware tick compare registers
uint64_t strandStatusReg;// Per strand status register
/** Floating point misc registers. */
uint64_t fsr; // Floating-Point State Register
/** MMU Internal Registers */
uint16_t priContext;
uint16_t secContext;
uint16_t partId;
uint64_t lsuCtrlReg;
uint64_t iTlbC0TsbPs0;
uint64_t iTlbC0TsbPs1;
uint64_t iTlbC0Config;
uint64_t iTlbCXTsbPs0;
uint64_t iTlbCXTsbPs1;
uint64_t iTlbCXConfig;
uint64_t iTlbSfsr;
uint64_t iTlbTagAccess;
uint64_t dTlbC0TsbPs0;
uint64_t dTlbC0TsbPs1;
uint64_t dTlbC0Config;
uint64_t dTlbCXTsbPs0;
uint64_t dTlbCXTsbPs1;
uint64_t dTlbCXConfig;
uint64_t dTlbSfsr;
uint64_t dTlbSfar;
uint64_t dTlbTagAccess;
uint64_t scratchPad[8];
uint64_t cpu_mondo_head;
uint64_t cpu_mondo_tail;
uint64_t dev_mondo_head;
uint64_t dev_mondo_tail;
uint64_t res_error_head;
uint64_t res_error_tail;
uint64_t nres_error_head;
uint64_t nres_error_tail;
// These need to check the int_dis field and if 0 then
// set appropriate bit in softint and checkinterrutps on the cpu
#if FULL_SYSTEM
void setFSRegWithEffect(int miscReg, const MiscReg &val,
ThreadContext *tc);
MiscReg readFSRegWithEffect(int miscReg, ThreadContext * tc);
// Update interrupt state on softint or pil change
void checkSoftInt(ThreadContext *tc);
/** Process a tick compare event and generate an interrupt on the cpu if
* appropriate. */
void processTickCompare(ThreadContext *tc);
void processSTickCompare(ThreadContext *tc);
void processHSTickCompare(ThreadContext *tc);
typedef CpuEventWrapper<MiscRegFile,
&MiscRegFile::processTickCompare> TickCompareEvent;
TickCompareEvent *tickCompare;
typedef CpuEventWrapper<MiscRegFile,
&MiscRegFile::processSTickCompare> STickCompareEvent;
STickCompareEvent *sTickCompare;
typedef CpuEventWrapper<MiscRegFile,
&MiscRegFile::processHSTickCompare> HSTickCompareEvent;
HSTickCompareEvent *hSTickCompare;
#endif
public:
void clear();
MiscRegFile()
{
clear();
}
MiscReg readReg(int miscReg);
MiscReg readRegWithEffect(int miscReg, ThreadContext *tc);
void setReg(int miscReg, const MiscReg &val);
void setRegWithEffect(int miscReg,
const MiscReg &val, ThreadContext * tc);
int getInstAsid()
{
return priContext | (uint32_t)partId << 13;
}
int getDataAsid()
{
return priContext | (uint32_t)partId << 13;
}
void serialize(std::ostream & os);
void unserialize(Checkpoint * cp, const std::string & section);
void copyMiscRegs(ThreadContext * tc);
protected:
bool isHyperPriv() { return (hpstate & (1 << 2)); }
bool isPriv() { return (hpstate & (1 << 2)) || (pstate & (1 << 2)); }
bool isNonPriv() { return !isPriv(); }
};
}
#endif
<|endoftext|> |
<commit_before>6edcb0a2-5216-11e5-b716-6c40088e03e4<commit_msg>6ee355ca-5216-11e5-b6a7-6c40088e03e4<commit_after>6ee355ca-5216-11e5-b6a7-6c40088e03e4<|endoftext|> |
<commit_before>#include <cstdio>
#include "Observer.hpp"
namespace
{
void formatAngle(char *str, int const length, double const angleDeg)
{
long const angleMilliDeg = std::lround(degrees(angleDeg) * 1000);
long const degrees = angleMilliDeg / 1000 % 360;
long const milliDegrees = angleMilliDeg % 1000;
if (milliDegrees == 0)
{
snprintf(str, length, "%2.2li", degrees);
} else
{
snprintf(str, length, "%2.2li-%3.3li", degrees, milliDegrees);
}
}
}
// pictures
Pictures::Pictures(std::uint32_t nx, std::uint32_t ny)
: nx_{ nx }
, ny_{ ny }
{
f_ = new double[ nx*ny ]();
q_ = new double[ nx*ny ]();
u_ = new double[ nx*ny ]();
}
Pictures::~Pictures()
{
delete[] f_;
delete[] q_;
delete[] u_;
}
Pictures::Pictures(Pictures&& other) noexcept
: nx_{ other.nx_ }
, ny_{ other.ny_ }
, f_{ other.f_ }
, q_{ other.q_ }
, u_{ other.u_ }
{
other.f_ = nullptr;
other.q_ = nullptr;
other.u_ = nullptr;
}
Pictures& Pictures::operator=(Pictures&& other) noexcept
{
std::swap(f_, other.f_);
std::swap(q_, other.q_);
std::swap(u_, other.u_);
nx_ = other.nx_;
ny_ = other.ny_;
return *this;
}
// place photon on the images
void Pictures::bin(Photon const& ph, int64_t const xl, int64_t const yl, int64_t const id, double const weight)
{
// place weighted photon into image location
if((id == -1 || static_cast<std::uint64_t>(id) == ph.nscat()) && (xl>=0) && (yl >= 0) && ((std::uint32_t)xl < nx_) && ((std::uint32_t)yl < ny_) )
{
f_[xl+yl*nx_] += weight * ph.weight() * ph.fi();
q_[xl+yl*nx_] += weight * ph.weight() * ph.fq();
u_[xl+yl*nx_] += weight * ph.weight()*ph.fu();
}
}
void Pictures::normalize(std::uint64_t const numPhotons)
{
for (std::uint64_t i=0; i!=nx_*ny_; ++i)
{
f_[i] /= numPhotons;
q_[i] /= numPhotons;
u_[i] /= numPhotons;
}
}
void Pictures::write(double const phi, double const theta, int const key) const
{
int const FILENAME_LENGTH{ 40 };
int const ANGLE_LENGTH{ 10 };
char fname[FILENAME_LENGTH];
char phiStr[ANGLE_LENGTH];
char thetaStr[ANGLE_LENGTH];
formatAngle(phiStr, ANGLE_LENGTH, phi);
formatAngle(thetaStr, ANGLE_LENGTH, theta);
snprintf(fname, FILENAME_LENGTH, "fimage%s_%s_%2.2i.dat", phiStr, thetaStr, key);
std::ofstream f(fname);
f.precision(14);
for (std::uint64_t y=0; y != ny_; ++y)
{
for (std::uint64_t x=0; x!=nx_; ++x)
{
f << f_[x + y * nx_] << "\t";
}
f << "\n";
}
f.close();
snprintf(fname, FILENAME_LENGTH, "qimage%s_%s_%2.2i.dat", phiStr, thetaStr, key);
std::ofstream q(fname);
q.precision(14);
for (std::uint64_t y=0; y != ny_; ++y)
{
for (std::uint64_t x=0; x!=nx_; ++x)
{
q << q_[x + y * nx_] << "\t";
}
q << "\n";
}
q.close();
snprintf(fname, FILENAME_LENGTH, "uimage%s_%s_%2.2i.dat", phiStr, thetaStr, key);
std::ofstream u(fname);
u.precision(14);
for (std::uint64_t y=0; y != ny_; ++y)
{
for (std::uint64_t x=0; x!=nx_; ++x)
{
u << u_[x + y * nx_] << "\t";
}
u << "\n";
}
u.close();
}
void Pictures::sum(std::ofstream& file)
{
double fsum=0, qsum=0, usum=0;
for (std::uint64_t x=0; x!=nx_; ++x)
{
for (std::uint64_t y=0; y != ny_; ++y)
{
fsum += f_[y + x * ny_];
qsum += q_[y + x * ny_];
usum += u_[y + x * ny_];
}
}
file << "\tF= " << fsum << "\tQ= " << qsum << "\tU= " << usum
<< "\tp= " << std::sqrt(qsum*qsum + usum*usum)/fsum
<< "\tphi= " << 90 * std::atan2(usum, qsum)/PI;
}
Observer::Observer(double const phi, double const theta, double const rimage, std::uint32_t const Nx, std::uint32_t const Ny)
: result_(Nx, Ny)
, result0_(Nx, Ny)
, result1_(Nx, Ny)
, result2_(Nx, Ny)
, direction_{phi, theta}
, nx_(Nx)
, ny_(Ny)
{
rimage_ = rimage;
theta_ = theta;
cosp_ = std::cos(phi);
sinp_ = std::sin(phi);
}
void Observer::normalize(std::uint64_t const numPhotons)
{
result_.normalize(numPhotons);
result0_.normalize(numPhotons);
result1_.normalize(numPhotons);
result2_.normalize(numPhotons);
}
void Observer::writeToMapFiles(bool const fWriteSingleAndDoubleScatterings)
{
result_.write(direction_.phi(), theta_, 0);
if (fWriteSingleAndDoubleScatterings)
{
result1_.write(direction_.phi(), theta_, 1);
result2_.write(direction_.phi(), theta_, 2);
}
}
void Observer::write(std::ofstream& file)
{
file << "phi= " << degrees(direction_.phi()) << "\ttheta= " << degrees(theta_);
result_.sum(file);
result0_.sum(file);
result1_.sum(file);
result2_.sum(file);
file << "\n";
}
bool Observer::inFov(const Photon &photon) const
{
double const yimage = rimage_ + photon.pos().z() * direction_.sinTheta() -
direction_.cosTheta() * (photon.pos().y()*sinp_ + photon.pos().x()*cosp_);
double const ximage = rimage_ + photon.pos().y()*cosp_ - photon.pos().x()*sinp_;
auto const xl = static_cast<int64_t>(nx_ * ximage / (2.0 * rimage_));
auto const yl = static_cast<int64_t>(ny_ * yimage / (2.0 * rimage_));
return (xl>=0) && (yl >= 0) && ((std::uint32_t)xl < nx_) && ((std::uint32_t)yl < ny_);
}
void Observer::bin(Photon const& photon)
{
double const yimage = imageY(photon.pos());
double const ximage = imageX(photon.pos());
auto const xl = static_cast<int64_t>(nx_ * ximage / (2.0 * rimage_));
auto const yl = static_cast<int64_t>(ny_ * yimage / (2.0 * rimage_));
result_.bin(photon, xl, yl, -1, 1.0);
result0_.bin(photon, xl, yl, 0, 1.0);
result1_.bin(photon, xl, yl, 1, 1.0);
result2_.bin(photon, xl, yl, 2, 1.0);
}
// TODO: Add tests for this method
void Observer::bin(Photon const& photon, const Vector3d &pos1, const Vector3d &pos2)
{
double const yimage1 = imageY(pos1);
double const ximage1 = imageX(pos1);
auto const xl1 = static_cast<int64_t>(nx_ * ximage1 / (2.0 * rimage_));
auto const yl1 = static_cast<int64_t>(ny_ * yimage1 / (2.0 * rimage_));
double const yimage2 = imageY(pos2);
double const ximage2 = imageX(pos2);
auto const xl2 = static_cast<int64_t>(nx_ * ximage2 / (2.0 * rimage_));
auto const yl2 = static_cast<int64_t>(ny_ * yimage2 / (2.0 * rimage_));
if (xl1 == xl2 && yl1 == yl2)
{
bin(photon, xl2, yl2, 1.0);
return;
}
double xImageMin = std::min(ximage1, ximage2);
double xImageMax = std::max(ximage1, ximage2);
int64_t borderX = xl1;
int64_t lastBorderX = xl2;
if (ximage1 > ximage2)
{
xImageMin = ximage2;
xImageMax = ximage1;
borderX = xl2;
lastBorderX = xl1;
}
double yImageMin = yimage1;
double yImageMax = yimage2;
int64_t borderY = yl1;
int64_t lastBorderY = yl2;
if (yimage1 > yimage2)
{
yImageMin = yimage2;
yImageMax = yimage1;
borderY = yl2;
lastBorderY = yl1;
}
double const dx = xImageMax - xImageMin;
double const dy = yImageMax - yImageMin;
double const totalW = std::sqrt(dx*dx + dy*dy);
double x = xImageMin;
double y = yImageMax;
while (borderX <= lastBorderX && borderY <= lastBorderY)
{
double const xborder = std::min(static_cast<double>(borderX+1) * (2.0 * rimage_) / nx_, xImageMax);
double const yborder = std::min(static_cast<double>(borderY+1) * (2.0 * rimage_) / ny_, yImageMax);
double const xt = dx > 0 ? (xborder - x) / dx : std::numeric_limits<double>::infinity();
double const yt = dy > 0 ? (yborder - y) / dy : std::numeric_limits<double>::infinity();
if (xt < yt)
{
double yNew = y + xt * dy;
double w = std::sqrt((yNew - y)*(yNew-y) + (xborder - x)*(xborder - x));
bin(photon, borderX, borderY, w / totalW);
++borderX;
y = yNew;
x = xborder;
} else {
double xNew = x + yt * dx;
double w = std::sqrt((xNew - x)*(xNew-x) + (yborder - y)*(yborder - y));
bin(photon, borderX, borderY, w / totalW);
++borderY;
y = xborder;
x = xNew;
}
}
}
inline double Observer::imageX(Vector3d const &position) const
{
return rimage_ + position.y() * cosp_ - position.x() * sinp_;
}
inline double Observer::imageY(Vector3d const &position) const
{
return rimage_ + position.z() * direction_.sinTheta() - direction_.cosTheta() * (position.y()*sinp_ + position.x()*cosp_);
}
inline void Observer::bin(const Photon &photon, int64_t const x, int64_t const y, const double weight)
{
result_.bin(photon, x, y, -1, weight);
result0_.bin(photon, x, y, 0, weight);
result1_.bin(photon, x, y, 1, weight);
result2_.bin(photon, x, y, 2, weight);
}
<commit_msg>Fix Observer::bin method<commit_after>#include <cstdio>
#include "Observer.hpp"
namespace
{
void formatAngle(char *str, int const length, double const angleDeg)
{
long const angleMilliDeg = std::lround(degrees(angleDeg) * 1000);
long const degrees = angleMilliDeg / 1000 % 360;
long const milliDegrees = angleMilliDeg % 1000;
if (milliDegrees == 0)
{
snprintf(str, length, "%2.2li", degrees);
} else
{
snprintf(str, length, "%2.2li-%3.3li", degrees, milliDegrees);
}
}
}
// pictures
Pictures::Pictures(std::uint32_t nx, std::uint32_t ny)
: nx_{ nx }
, ny_{ ny }
{
f_ = new double[ nx*ny ]();
q_ = new double[ nx*ny ]();
u_ = new double[ nx*ny ]();
}
Pictures::~Pictures()
{
delete[] f_;
delete[] q_;
delete[] u_;
}
Pictures::Pictures(Pictures&& other) noexcept
: nx_{ other.nx_ }
, ny_{ other.ny_ }
, f_{ other.f_ }
, q_{ other.q_ }
, u_{ other.u_ }
{
other.f_ = nullptr;
other.q_ = nullptr;
other.u_ = nullptr;
}
Pictures& Pictures::operator=(Pictures&& other) noexcept
{
std::swap(f_, other.f_);
std::swap(q_, other.q_);
std::swap(u_, other.u_);
nx_ = other.nx_;
ny_ = other.ny_;
return *this;
}
// place photon on the images
void Pictures::bin(Photon const& ph, int64_t const xl, int64_t const yl, int64_t const id, double const weight)
{
// place weighted photon into image location
if((id == -1 || static_cast<std::uint64_t>(id) == ph.nscat()) && (xl>=0) && (yl >= 0) && ((std::uint32_t)xl < nx_) && ((std::uint32_t)yl < ny_) )
{
f_[xl+yl*nx_] += weight * ph.weight() * ph.fi();
q_[xl+yl*nx_] += weight * ph.weight() * ph.fq();
u_[xl+yl*nx_] += weight * ph.weight()*ph.fu();
}
}
void Pictures::normalize(std::uint64_t const numPhotons)
{
for (std::uint64_t i=0; i!=nx_*ny_; ++i)
{
f_[i] /= numPhotons;
q_[i] /= numPhotons;
u_[i] /= numPhotons;
}
}
void Pictures::write(double const phi, double const theta, int const key) const
{
int const FILENAME_LENGTH{ 40 };
int const ANGLE_LENGTH{ 10 };
char fname[FILENAME_LENGTH];
char phiStr[ANGLE_LENGTH];
char thetaStr[ANGLE_LENGTH];
formatAngle(phiStr, ANGLE_LENGTH, phi);
formatAngle(thetaStr, ANGLE_LENGTH, theta);
snprintf(fname, FILENAME_LENGTH, "fimage%s_%s_%2.2i.dat", phiStr, thetaStr, key);
std::ofstream f(fname);
f.precision(14);
for (std::uint64_t y=0; y != ny_; ++y)
{
for (std::uint64_t x=0; x!=nx_; ++x)
{
f << f_[x + y * nx_] << "\t";
}
f << "\n";
}
f.close();
snprintf(fname, FILENAME_LENGTH, "qimage%s_%s_%2.2i.dat", phiStr, thetaStr, key);
std::ofstream q(fname);
q.precision(14);
for (std::uint64_t y=0; y != ny_; ++y)
{
for (std::uint64_t x=0; x!=nx_; ++x)
{
q << q_[x + y * nx_] << "\t";
}
q << "\n";
}
q.close();
snprintf(fname, FILENAME_LENGTH, "uimage%s_%s_%2.2i.dat", phiStr, thetaStr, key);
std::ofstream u(fname);
u.precision(14);
for (std::uint64_t y=0; y != ny_; ++y)
{
for (std::uint64_t x=0; x!=nx_; ++x)
{
u << u_[x + y * nx_] << "\t";
}
u << "\n";
}
u.close();
}
void Pictures::sum(std::ofstream& file)
{
double fsum=0, qsum=0, usum=0;
for (std::uint64_t x=0; x!=nx_; ++x)
{
for (std::uint64_t y=0; y != ny_; ++y)
{
fsum += f_[y + x * ny_];
qsum += q_[y + x * ny_];
usum += u_[y + x * ny_];
}
}
file << "\tF= " << fsum << "\tQ= " << qsum << "\tU= " << usum
<< "\tp= " << std::sqrt(qsum*qsum + usum*usum)/fsum
<< "\tphi= " << 90 * std::atan2(usum, qsum)/PI;
}
Observer::Observer(double const phi, double const theta, double const rimage, std::uint32_t const Nx, std::uint32_t const Ny)
: result_(Nx, Ny)
, result0_(Nx, Ny)
, result1_(Nx, Ny)
, result2_(Nx, Ny)
, direction_{phi, theta}
, nx_(Nx)
, ny_(Ny)
{
rimage_ = rimage;
theta_ = theta;
cosp_ = std::cos(phi);
sinp_ = std::sin(phi);
}
void Observer::normalize(std::uint64_t const numPhotons)
{
result_.normalize(numPhotons);
result0_.normalize(numPhotons);
result1_.normalize(numPhotons);
result2_.normalize(numPhotons);
}
void Observer::writeToMapFiles(bool const fWriteSingleAndDoubleScatterings)
{
result_.write(direction_.phi(), theta_, 0);
if (fWriteSingleAndDoubleScatterings)
{
result1_.write(direction_.phi(), theta_, 1);
result2_.write(direction_.phi(), theta_, 2);
}
}
void Observer::write(std::ofstream& file)
{
file << "phi= " << degrees(direction_.phi()) << "\ttheta= " << degrees(theta_);
result_.sum(file);
result0_.sum(file);
result1_.sum(file);
result2_.sum(file);
file << "\n";
}
bool Observer::inFov(const Photon &photon) const
{
double const yimage = rimage_ + photon.pos().z() * direction_.sinTheta() -
direction_.cosTheta() * (photon.pos().y()*sinp_ + photon.pos().x()*cosp_);
double const ximage = rimage_ + photon.pos().y()*cosp_ - photon.pos().x()*sinp_;
auto const xl = static_cast<int64_t>(nx_ * ximage / (2.0 * rimage_));
auto const yl = static_cast<int64_t>(ny_ * yimage / (2.0 * rimage_));
return (xl>=0) && (yl >= 0) && ((std::uint32_t)xl < nx_) && ((std::uint32_t)yl < ny_);
}
void Observer::bin(Photon const& photon)
{
double const yimage = imageY(photon.pos());
double const ximage = imageX(photon.pos());
auto const xl = static_cast<int64_t>(nx_ * ximage / (2.0 * rimage_));
auto const yl = static_cast<int64_t>(ny_ * yimage / (2.0 * rimage_));
result_.bin(photon, xl, yl, -1, 1.0);
result0_.bin(photon, xl, yl, 0, 1.0);
result1_.bin(photon, xl, yl, 1, 1.0);
result2_.bin(photon, xl, yl, 2, 1.0);
}
// TODO: Add tests for this method
void Observer::bin(Photon const& photon, const Vector3d &pos1, const Vector3d &pos2)
{
double const yimage1 = imageY(pos1);
double const ximage1 = imageX(pos1);
auto const xl1 = static_cast<int64_t>(nx_ * ximage1 / (2.0 * rimage_));
auto const yl1 = static_cast<int64_t>(ny_ * yimage1 / (2.0 * rimage_));
double const yimage2 = imageY(pos2);
double const ximage2 = imageX(pos2);
auto const xl2 = static_cast<int64_t>(nx_ * ximage2 / (2.0 * rimage_));
auto const yl2 = static_cast<int64_t>(ny_ * yimage2 / (2.0 * rimage_));
if (xl1 == xl2 && yl1 == yl2)
{
bin(photon, xl2, yl2, 1.0);
return;
}
double xImageMin = std::min(ximage1, ximage2);
double xImageMax = std::max(ximage1, ximage2);
int64_t borderX = xl1;
int64_t lastBorderX = xl2;
if (ximage1 > ximage2)
{
xImageMin = ximage2;
xImageMax = ximage1;
borderX = xl2;
lastBorderX = xl1;
}
double yImageMin = yimage1;
double yImageMax = yimage2;
int64_t borderY = yl1;
int64_t lastBorderY = yl2;
if (yimage1 > yimage2)
{
yImageMin = yimage2;
yImageMax = yimage1;
borderY = yl2;
lastBorderY = yl1;
}
double const dx = xImageMax - xImageMin;
double const dy = yImageMax - yImageMin;
double const totalW = std::sqrt(dx*dx + dy*dy);
double x = xImageMin;
double y = yImageMin;
while (borderX <= lastBorderX && borderY <= lastBorderY)
{
double const xborder = std::min(static_cast<double>(borderX+1) * (2.0 * rimage_) / nx_, xImageMax);
double const yborder = std::min(static_cast<double>(borderY+1) * (2.0 * rimage_) / ny_, yImageMax);
double const xt = dx > 0 ? (xborder - x) / dx : std::numeric_limits<double>::infinity();
double const yt = dy > 0 ? (yborder - y) / dy : std::numeric_limits<double>::infinity();
if (xt < yt)
{
double yNew = y + xt * dy;
double w = std::sqrt((yNew - y)*(yNew-y) + (xborder - x)*(xborder - x));
bin(photon, borderX, borderY, w / totalW);
++borderX;
x = xborder;
y = yNew;
} else {
double xNew = x + yt * dx;
double w = std::sqrt((xNew - x)*(xNew-x) + (yborder - y)*(yborder - y));
bin(photon, borderX, borderY, w / totalW);
++borderY;
x = xNew;
y = yborder;
}
}
}
inline double Observer::imageX(Vector3d const &position) const
{
return rimage_ + position.y() * cosp_ - position.x() * sinp_;
}
inline double Observer::imageY(Vector3d const &position) const
{
return rimage_ + position.z() * direction_.sinTheta() - direction_.cosTheta() * (position.y()*sinp_ + position.x()*cosp_);
}
inline void Observer::bin(const Photon &photon, int64_t const x, int64_t const y, const double weight)
{
result_.bin(photon, x, y, -1, weight);
result0_.bin(photon, x, y, 0, weight);
result1_.bin(photon, x, y, 1, weight);
result2_.bin(photon, x, y, 2, weight);
}
<|endoftext|> |
<commit_before>7f6cf647-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf648-2d15-11e5-af21-0401358ea401<commit_after>7f6cf648-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7813d488-2d53-11e5-baeb-247703a38240<commit_msg>7814544e-2d53-11e5-baeb-247703a38240<commit_after>7814544e-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>221a730c-ad5b-11e7-9d7d-ac87a332f658<commit_msg>Did ANOTHER thing<commit_after>22ddb97d-ad5b-11e7-8325-ac87a332f658<|endoftext|> |
<commit_before>973c4852-35ca-11e5-888f-6c40088e03e4<commit_msg>97479b1c-35ca-11e5-84f1-6c40088e03e4<commit_after>97479b1c-35ca-11e5-84f1-6c40088e03e4<|endoftext|> |
<commit_before>b13b8a4a-327f-11e5-97d6-9cf387a8033e<commit_msg>b141578f-327f-11e5-87cf-9cf387a8033e<commit_after>b141578f-327f-11e5-87cf-9cf387a8033e<|endoftext|> |
<commit_before>5ec04fb0-5216-11e5-b651-6c40088e03e4<commit_msg>5ec70788-5216-11e5-9d95-6c40088e03e4<commit_after>5ec70788-5216-11e5-9d95-6c40088e03e4<|endoftext|> |
<commit_before>e3241982-327f-11e5-93e1-9cf387a8033e<commit_msg>e329f0bd-327f-11e5-97a4-9cf387a8033e<commit_after>e329f0bd-327f-11e5-97a4-9cf387a8033e<|endoftext|> |
<commit_before>6b3e69f6-2fa5-11e5-9ea8-00012e3d3f12<commit_msg>6b40b3e4-2fa5-11e5-9221-00012e3d3f12<commit_after>6b40b3e4-2fa5-11e5-9221-00012e3d3f12<|endoftext|> |
<commit_before>/*
Please see LICENSE_flynda
*/
#include "inotify-cxx.h"
#include<string>
#include<iostream>
#include <stdio.h>
#include<thread>
void watch(std::string& folder);
std::string exec(char* cmd);
int main(){
using namespace std;
/*
watching a directory
*/
string dir = "/tmp";
string dir2 = "/proc/33/fd";
//start by fidnding pid of the l**da applet thingie
char cmd[] = "lsof -n | grep Flash";
string result = exec(cmd);
cout << result << endl;
//thread(watch,dir);
return 0;
}
/*
Method for watching the provided directory
for any event fired events
*/
void watch(std::string& folder){
using namespace std;
//creating the watcher -- adding directory
Inotify notify;
InotifyWatch watch(folder, IN_ALL_EVENTS);
notify.SetNonBlock(false);
notify.Add(watch);
//wating for a response
while(true){
notify.WaitForEvents();
//dealing with fired events
int num_events = notify.GetEventCount();
for (int i=num_events; i>0; --i){
InotifyEvent event;
//getting current fired event
if (notify.GetEvent(&event)){
string event_name = event.GetName();
uint32_t mask = event.GetMask();
//do something here
cout << event_name << " : " << mask << endl;
}
else{
//event retrieval failed
cerr << "event retrieval failed" << endl;
}
}
}
}
/*
Method stolen from @waqas to save time
http://stackoverflow.com/a/478960
*/
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
<commit_msg>can retrieve pid<commit_after>/*
Please see LICENSE_flynda
*/
#include "inotify-cxx.h"
#include<string>
#include<iostream>
#include <stdio.h>
#include<thread>
#include <sstream>
void watch(std::string& folder);
std::string exec(char* cmd);
int main(){
using namespace std;
/*
watching a directory
*/
string dir = "/tmp";
string dir2 = "/proc/33/fd";
//start by fidnding pid of the l**da applet thingie
char cmd[] = "lsof -n | grep Flash";
string result = exec(cmd);
stringstream ss(result);
string null_stream;
int pid;
ss >> null_stream;
ss >> pid;
cout << result << endl;
cout << pid << endl;
//thread(watch,dir);
return 0;
}
/*
Method for watching the provided directory
for any event fired events
*/
void watch(std::string& folder){
using namespace std;
//creating the watcher -- adding directory
Inotify notify;
InotifyWatch watch(folder, IN_ALL_EVENTS);
notify.SetNonBlock(false);
notify.Add(watch);
//wating for a response
while(true){
notify.WaitForEvents();
//dealing with fired events
int num_events = notify.GetEventCount();
for (int i=num_events; i>0; --i){
InotifyEvent event;
//getting current fired event
if (notify.GetEvent(&event)){
string event_name = event.GetName();
uint32_t mask = event.GetMask();
//do something here
cout << event_name << " : " << mask << endl;
}
else{
//event retrieval failed
cerr << "event retrieval failed" << endl;
}
}
}
}
/*
Method stolen from @waqas to save time
http://stackoverflow.com/a/478960
*/
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
<|endoftext|> |
<commit_before>// Written by : Chirantan Mitra
#include <igloo/igloo_alt.h>
#include <matrix.h>
using namespace igloo;
using namespace CMatrix;
class testFunctionoidWithOneParameter
{
public:
double operator() (double x)
{
return x + 1.0;
}
};
class testFunctionoidWithTwoParameters
{
public:
double operator() (double x, double y)
{
return x + y;
}
};
Describe(CMatrix_when_receiving_a_functionoid_with_one_parameter)
{
Describe(On_map)
{
Matrix<double> twoByTwoMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
twoByTwoMatrix.setSize(2, 2);
twoByTwoMatrix(0, 0) = 1.0; twoByTwoMatrix(0, 1) = 2.0;
twoByTwoMatrix(1, 0) = 3.0; twoByTwoMatrix(1, 1) = 4.0;
expectedMatrix.setSize(2, 2);
expectedMatrix(0, 0) = 2.0; expectedMatrix(0, 1) = 3.0;
expectedMatrix(1, 0) = 4.0; expectedMatrix(1, 1) = 5.0;
}
It(applies_it_to_all_members)
{
Assert::That(twoByTwoMatrix.map(new testFunctionoidWithOneParameter), Equals(expectedMatrix));
}
It(DoesNotMutate)
{
twoByTwoMatrix.map(new testFunctionoidWithOneParameter);
Assert::That(twoByTwoMatrix, !Equals(expectedMatrix));
}
};
};
Describe(CMatrix_when_receiving_a_functionoid_with_two_parameters)
{
Describe(On_fill_by_position)
{
Matrix<double> twoByTwoMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
twoByTwoMatrix.setSize(2, 2);
expectedMatrix.setSize(2, 2);
expectedMatrix(0, 0) = 0.0; expectedMatrix(0, 1) = 1.0;
expectedMatrix(1, 0) = 1.0; expectedMatrix(1, 1) = 2.0;
}
It(applies_it_to_all_members)
{
Assert::That(twoByTwoMatrix.fillByPosition(new testFunctionoidWithTwoParameters), Equals(expectedMatrix));
}
It(mutates)
{
twoByTwoMatrix.fillByPosition(new testFunctionoidWithTwoParameters);
Assert::That(twoByTwoMatrix == expectedMatrix);
}
};
Describe(On_fill_by_position_and_shift)
{
Matrix<double> threeByThreeMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
threeByThreeMatrix.setSize(3, 3);
expectedMatrix.setSize(3, 3);
expectedMatrix(0, 0) = -2.0; expectedMatrix(0, 1) = -1.0; expectedMatrix(0, 2) = 0.0;
expectedMatrix(1, 0) = -1.0; expectedMatrix(1, 1) = 0.0; expectedMatrix(1, 2) = 1.0;
expectedMatrix(2, 0) = 0.0; expectedMatrix(2, 1) = 1.0; expectedMatrix(2, 2) = 2.0;
}
It(applies_it_to_all_members)
{
Assert::That(threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1), Equals(expectedMatrix));
}
It(mutates)
{
threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1);
Assert::That(threeByThreeMatrix, Equals(expectedMatrix));
}
};
Describe(On_fill_by_position_and_shift_and_scale)
{
Matrix<double> threeByThreeMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
threeByThreeMatrix.setSize(3, 3);
expectedMatrix.setSize(3, 3);
expectedMatrix(0, 0) = 1.0; expectedMatrix(0, 1) = -2.0; expectedMatrix(0, 2) = -5.0;
expectedMatrix(1, 0) = 3.0; expectedMatrix(1, 1) = 0.0; expectedMatrix(1, 2) = -3.0;
expectedMatrix(2, 0) = 5.0; expectedMatrix(2, 1) = 2.0; expectedMatrix(2, 2) = -1.0;
}
It(applies_it_to_all_members)
{
Assert::That(threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1, 2.0, -3.0), Equals(expectedMatrix));
}
It(mutates)
{
threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1, 2.0, -3.0);
Assert::That(threeByThreeMatrix, Equals(expectedMatrix));
}
};
};
<commit_msg>Use snake-case names in tests<commit_after>// Written by : Chirantan Mitra
#include <igloo/igloo_alt.h>
#include <matrix.h>
using namespace igloo;
using namespace CMatrix;
class testFunctionoidWithOneParameter
{
public:
double operator() (double x)
{
return x + 1.0;
}
};
class testFunctionoidWithTwoParameters
{
public:
double operator() (double x, double y)
{
return x + y;
}
};
Describe(CMatrix_when_receiving_a_functionoid_with_one_parameter)
{
Describe(On_map)
{
Matrix<double> twoByTwoMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
twoByTwoMatrix.setSize(2, 2);
twoByTwoMatrix(0, 0) = 1.0; twoByTwoMatrix(0, 1) = 2.0;
twoByTwoMatrix(1, 0) = 3.0; twoByTwoMatrix(1, 1) = 4.0;
expectedMatrix.setSize(2, 2);
expectedMatrix(0, 0) = 2.0; expectedMatrix(0, 1) = 3.0;
expectedMatrix(1, 0) = 4.0; expectedMatrix(1, 1) = 5.0;
}
It(applies_it_to_all_members)
{
Assert::That(twoByTwoMatrix.map(new testFunctionoidWithOneParameter), Equals(expectedMatrix));
}
It(does_not_mutate)
{
twoByTwoMatrix.map(new testFunctionoidWithOneParameter);
Assert::That(twoByTwoMatrix, !Equals(expectedMatrix));
}
};
};
Describe(CMatrix_when_receiving_a_functionoid_with_two_parameters)
{
Describe(On_fill_by_position)
{
Matrix<double> twoByTwoMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
twoByTwoMatrix.setSize(2, 2);
expectedMatrix.setSize(2, 2);
expectedMatrix(0, 0) = 0.0; expectedMatrix(0, 1) = 1.0;
expectedMatrix(1, 0) = 1.0; expectedMatrix(1, 1) = 2.0;
}
It(applies_it_to_all_members)
{
Assert::That(twoByTwoMatrix.fillByPosition(new testFunctionoidWithTwoParameters), Equals(expectedMatrix));
}
It(mutates)
{
twoByTwoMatrix.fillByPosition(new testFunctionoidWithTwoParameters);
Assert::That(twoByTwoMatrix == expectedMatrix);
}
};
Describe(On_fill_by_position_and_shift)
{
Matrix<double> threeByThreeMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
threeByThreeMatrix.setSize(3, 3);
expectedMatrix.setSize(3, 3);
expectedMatrix(0, 0) = -2.0; expectedMatrix(0, 1) = -1.0; expectedMatrix(0, 2) = 0.0;
expectedMatrix(1, 0) = -1.0; expectedMatrix(1, 1) = 0.0; expectedMatrix(1, 2) = 1.0;
expectedMatrix(2, 0) = 0.0; expectedMatrix(2, 1) = 1.0; expectedMatrix(2, 2) = 2.0;
}
It(applies_it_to_all_members)
{
Assert::That(threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1), Equals(expectedMatrix));
}
It(mutates)
{
threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1);
Assert::That(threeByThreeMatrix, Equals(expectedMatrix));
}
};
Describe(On_fill_by_position_and_shift_and_scale)
{
Matrix<double> threeByThreeMatrix;
Matrix<double> expectedMatrix;
void SetUp()
{
threeByThreeMatrix.setSize(3, 3);
expectedMatrix.setSize(3, 3);
expectedMatrix(0, 0) = 1.0; expectedMatrix(0, 1) = -2.0; expectedMatrix(0, 2) = -5.0;
expectedMatrix(1, 0) = 3.0; expectedMatrix(1, 1) = 0.0; expectedMatrix(1, 2) = -3.0;
expectedMatrix(2, 0) = 5.0; expectedMatrix(2, 1) = 2.0; expectedMatrix(2, 2) = -1.0;
}
It(applies_it_to_all_members)
{
Assert::That(threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1, 2.0, -3.0), Equals(expectedMatrix));
}
It(mutates)
{
threeByThreeMatrix.fillByPosition(new testFunctionoidWithTwoParameters, 1, 1, 2.0, -3.0);
Assert::That(threeByThreeMatrix, Equals(expectedMatrix));
}
};
};
<|endoftext|> |
<commit_before>83000d88-2d15-11e5-af21-0401358ea401<commit_msg>83000d89-2d15-11e5-af21-0401358ea401<commit_after>83000d89-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>120b3c5e-2748-11e6-abc9-e0f84713e7b8<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>1217369e-2748-11e6-bd8b-e0f84713e7b8<|endoftext|> |
<commit_before>92323b58-2d14-11e5-af21-0401358ea401<commit_msg>92323b59-2d14-11e5-af21-0401358ea401<commit_after>92323b59-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <cassert>
#include <napkin/exception.h>
#include "db.h"
#include "config.h"
namespace napkin {
extern const char *sql_bootstrap;
db_t::db_t() {
const char *h = getenv("HOME");
if(h) {
datadir = h;
datadir += "/."PACKAGE_NAME"/";
}else{
#if defined(HAVE_GET_CURRENT_DIR_NAME)
char *cwd = get_current_dir_name();
if(!cwd)
throw napkin::exception("failed to get_current_dir_name()");
datadir = cwd;
free(cwd);
#elif defined(HAVE_GETCWD)
{
char cwd[
# if defined(MAXPATH)
MAXPATH
# elif defined(MAXPATHLEN)
MAXPATHLEN
# else /* maxpath */
512
#endif /* maxpath */
];
if(!getcwd(cwd,sizeof(cwd)))
throw napkin::exception("failed to getcwd()");
datadir = cwd;
}
#else /* get cwd */
# error dunno how to get current workdir
#endif /* get cwd */
datadir += "/."PACKAGE_NAME"/";
}
if(access(datadir.c_str(),R_OK|W_OK)
&& mkdir(datadir.c_str(),0700))
throw napkin::exception("no access to '"+datadir+"' directory");
open((datadir+PACKAGE_NAME".db").c_str());
assert(_D);
char **resp; int nr,nc; char *errm;
if(sqlite3_get_table(
_D,
"SELECT s_tobed FROM sleeps LIMIT 0",
&resp,&nr,&nc,&errm)!=SQLITE_OK) {
if(sqlite3_exec(_D,sql_bootstrap,NULL,NULL,&errm)!=SQLITE_OK)
throw napkin::exception(string("failed to bootstrap sqlite database: ")+errm);
}else
sqlite3_free_table(resp);
}
void db_t::store(const hypnodata_t& hd) {
sqlite::mem_t<char*> S = sqlite3_mprintf(
"INSERT INTO sleeps ("
"s_tobed,s_alarm,"
"s_window,s_data_a,"
"s_almost_awakes,"
"s_timezone"
") VALUES ("
"%Q,%Q,%d,%d,%Q,%ld"
")",
hd.w3c_to_bed().c_str(),
hd.w3c_alarm().c_str(),
hd.window,hd.data_a,
hd.w3c_almostawakes().c_str(),
timezone );
try {
exec(S);
}catch(sqlite::exception& se) {
if(se.rcode==SQLITE_CONSTRAINT)
throw exception_db_already("The record seems to be already in the database");
throw exception_db("Well, some error occured");
}
}
void db_t::remove(const hypnodata_t& hd) {
sqlite::mem_t<char*> S = sqlite3_mprintf(
"DELETE FROM sleeps"
" WHERE s_tobed=%Q AND s_alarm=%Q",
hd.w3c_to_bed().c_str(),
hd.w3c_alarm().c_str() );
exec(S);
}
void db_t::load(list<hypnodata_ptr_t>& rv,
const string& sql) {
sqlite::table_t T;
int nr,nc;
get_table( string(
"SELECT"
" s_tobed, s_alarm,"
" s_window, s_data_a,"
" s_almost_awakes"
" FROM sleeps"
" "+sql).c_str(),T,&nr,&nc );
if(nr) {
assert(nc==5);
for(int r=1;r<=nr;++r) {
hypnodata_ptr_t hd(new hypnodata_t());
hd->set_to_bed(T.get(r,0,nc));
hd->set_alarm(T.get(r,1,nc));
hd->set_window(T.get(r,2,nc));
hd->set_data_a(T.get(r,3,nc));
hd->set_almost_awakes(T.get(r,4,nc));
rv.push_back(hd);
}
}
}
}
<commit_msg>whitespace-only change Signed-off-by: Michael Krelin <hacker@klever.net><commit_after>#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <cassert>
#include <napkin/exception.h>
#include "db.h"
#include "config.h"
namespace napkin {
extern const char *sql_bootstrap;
db_t::db_t() {
const char *h = getenv("HOME");
if(h) {
datadir = h;
datadir += "/."PACKAGE_NAME"/";
}else{
#if defined(HAVE_GET_CURRENT_DIR_NAME)
char *cwd = get_current_dir_name();
if(!cwd)
throw napkin::exception("failed to get_current_dir_name()");
datadir = cwd;
free(cwd);
#elif defined(HAVE_GETCWD)
{
char cwd[
# if defined(MAXPATH)
MAXPATH
# elif defined(MAXPATHLEN)
MAXPATHLEN
# else /* maxpath */
512
# endif /* maxpath */
];
if(!getcwd(cwd,sizeof(cwd)))
throw napkin::exception("failed to getcwd()");
datadir = cwd;
}
#else /* get cwd */
# error dunno how to get current workdir
#endif /* get cwd */
datadir += "/."PACKAGE_NAME"/";
}
if(access(datadir.c_str(),R_OK|W_OK)
&& mkdir(datadir.c_str(),0700))
throw napkin::exception("no access to '"+datadir+"' directory");
open((datadir+PACKAGE_NAME".db").c_str());
assert(_D);
char **resp; int nr,nc; char *errm;
if(sqlite3_get_table(
_D,
"SELECT s_tobed FROM sleeps LIMIT 0",
&resp,&nr,&nc,&errm)!=SQLITE_OK) {
if(sqlite3_exec(_D,sql_bootstrap,NULL,NULL,&errm)!=SQLITE_OK)
throw napkin::exception(string("failed to bootstrap sqlite database: ")+errm);
}else
sqlite3_free_table(resp);
}
void db_t::store(const hypnodata_t& hd) {
sqlite::mem_t<char*> S = sqlite3_mprintf(
"INSERT INTO sleeps ("
"s_tobed,s_alarm,"
"s_window,s_data_a,"
"s_almost_awakes,"
"s_timezone"
") VALUES ("
"%Q,%Q,%d,%d,%Q,%ld"
")",
hd.w3c_to_bed().c_str(),
hd.w3c_alarm().c_str(),
hd.window,hd.data_a,
hd.w3c_almostawakes().c_str(),
timezone );
try {
exec(S);
}catch(sqlite::exception& se) {
if(se.rcode==SQLITE_CONSTRAINT)
throw exception_db_already("The record seems to be already in the database");
throw exception_db("Well, some error occured");
}
}
void db_t::remove(const hypnodata_t& hd) {
sqlite::mem_t<char*> S = sqlite3_mprintf(
"DELETE FROM sleeps"
" WHERE s_tobed=%Q AND s_alarm=%Q",
hd.w3c_to_bed().c_str(),
hd.w3c_alarm().c_str() );
exec(S);
}
void db_t::load(list<hypnodata_ptr_t>& rv,
const string& sql) {
sqlite::table_t T;
int nr,nc;
get_table( string(
"SELECT"
" s_tobed, s_alarm,"
" s_window, s_data_a,"
" s_almost_awakes"
" FROM sleeps"
" "+sql).c_str(),T,&nr,&nc );
if(nr) {
assert(nc==5);
for(int r=1;r<=nr;++r) {
hypnodata_ptr_t hd(new hypnodata_t());
hd->set_to_bed(T.get(r,0,nc));
hd->set_alarm(T.get(r,1,nc));
hd->set_window(T.get(r,2,nc));
hd->set_data_a(T.get(r,3,nc));
hd->set_almost_awakes(T.get(r,4,nc));
rv.push_back(hd);
}
}
}
}
<|endoftext|> |
<commit_before>b0183bb0-2e4f-11e5-968e-28cfe91dbc4b<commit_msg>b01ed7ae-2e4f-11e5-8230-28cfe91dbc4b<commit_after>b01ed7ae-2e4f-11e5-8230-28cfe91dbc4b<|endoftext|> |
<commit_before>92323b53-2d14-11e5-af21-0401358ea401<commit_msg>92323b54-2d14-11e5-af21-0401358ea401<commit_after>92323b54-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f461dc5c-327f-11e5-8fca-9cf387a8033e<commit_msg>Final commit :sunglasses:<commit_after>#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>8d6dfcb2-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcb3-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcb3-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>66381c6e-2e3a-11e5-b445-c03896053bdd<commit_msg>6647888c-2e3a-11e5-9f70-c03896053bdd<commit_after>6647888c-2e3a-11e5-9f70-c03896053bdd<|endoftext|> |
<commit_before>#include <QApplication>
#include <QtQml>
#include <QtQuick/QQuickView>
#include <QtCore/QString>
#include <QDebug>
#include "aztterplugin/aztterplugin.h"
#include "aztterplugin/azttertweetlistmodel.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine(QUrl("qrc:/qml/main.qml"));
auto *aztterPlugin = new AztterPlugin();
engine.rootContext()->setContextProperty(QLatin1String("aztter"), aztterPlugin);
auto *tweetListModel = new AztterTweetListModel();
engine.rootContext()->setContextProperty(QLatin1String("tweetListModel"), tweetListModel);
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
if ( !window ) {
qWarning("Error: Your root item has to be a Window.");
return -1;
}
window->show();
return app.exec();
}
<commit_msg>add offlineStoragePath debug output<commit_after>#include <QApplication>
#include <QtQml>
#include <QtQuick/QQuickView>
#include <QtCore/QString>
#include <QDebug>
#include "aztterplugin/aztterplugin.h"
#include "aztterplugin/azttertweetlistmodel.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine(QUrl("qrc:/qml/main.qml"));
auto *aztterPlugin = new AztterPlugin();
engine.rootContext()->setContextProperty(QLatin1String("aztter"), aztterPlugin);
auto *tweetListModel = new AztterTweetListModel();
engine.rootContext()->setContextProperty(QLatin1String("tweetListModel"), tweetListModel);
qDebug() << "OfflineStoragePath: " << engine.offlineStoragePath();
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
if ( !window ) {
qWarning("Error: Your root item has to be a Window.");
return -1;
}
window->show();
return app.exec();
}
<|endoftext|> |
<commit_before>#include <shaderboiler.h>
#include <iostream>
void main()
{
using namespace sb;
using namespace sb::gl440;
{
context ctx;
vec4 AmbientColor = ctx.uniform<vec4>("AmbientColor");
vec3 normal = ctx.in<vec3>("normal");
vec3 vertex_to_light_vector = ctx.in<vec3>("vertex_to_light_vector");
// Defining The Material Colors
const vec4 DiffuseColor = vec4(1.0, 0.0, 0.0, 1.0).SetName("DiffuseColor");
ivec1 a = gl_MaxProgramTexelOffset;
// Scaling The Input Vector To Length 1
//vec3 normalized_normal = normalize(normal);
vec3 normalized_normal = normal;
//vec3 normalized_vertex_to_light_vector = normalize(vertex_to_light_vector);
vec3 normalized_vertex_to_light_vector = vertex_to_light_vector * 2;
// Calculating The Diffuse Term And Clamping It To [0;1]
Float DiffuseTerm = max(dot(normal, vertex_to_light_vector), 0.0).SetName("DiffuseTerm");
// Calculating The Final Color
ctx[fs::gl_FragColor] = AmbientColor + DiffuseColor * DiffuseTerm;
std::cout << ctx.genShader();
}
std::cout << "Test3" << "\n";
context ctx;
vec2 a = ctx.in<vec2>("a");
vec2 b = ctx.in<vec2>("b");
vec2 d = ctx.out<vec2>("d");
vec2 g(1.0f, 2.0f);
a = 3.0f * (a + b * 1.0f) * g;
d = a * (a * 1.0f);
std::cout << ctx.genShader();
}
<commit_msg>Updated example<commit_after>#include <shaderboiler.h>
#include <iostream>
void main()
{
using namespace sb;
using namespace sb::gl440;
using namespace sb::fs;
{
context ctx;
vec4 AmbientColor = ctx.uniform<vec4>("AmbientColor");
vec3 normal = ctx.in<vec3>("normal");
vec3 vertex_to_light_vector = ctx.in<vec3>("vertex_to_light_vector");
array<vec3> lights = ctx.uniform<array<vec3> >("lights[5]");
array<vec3> lights2(3);
lights2[0] = vec3(0.0);
vec3 b = lights2[0];
// Defining The Material Colors
const vec4 DiffuseColor = vec4(1.0, 0.0, 0.0, 1.0).SetName("DiffuseColor");
ivec1 a = gl_MaxProgramTexelOffset;
// Scaling The Input Vector To Length 1
//vec3 normalized_normal = normalize(normal);
vec3 normalized_normal = normal;
//vec3 normalized_vertex_to_light_vector = normalize(vertex_to_light_vector);
vec3 normalized_vertex_to_light_vector = vertex_to_light_vector * 2;
// Calculating The Diffuse Term And Clamping It To [0;1]
Float DiffuseTerm = max(dot(normal, vertex_to_light_vector), 0.0).SetName("DiffuseTerm");
// Calculating The Final Color
ctx[fs::gl_FragColor] = AmbientColor + DiffuseColor * DiffuseTerm;
std::cout << ctx.genShader();
}
std::cout << "Test3" << "\n";
context ctx;
vec2 a = ctx.in<vec2>("a");
vec2 b = ctx.in<vec2>("b");
vec2 d = ctx.out<vec2>("d");
vec2 g(1.0f, 2.0f);
a = 3.0f * (a + b * 1.0f) * g;
d = a * (a * 1.0f);
std::cout << ctx.genShader();
}
<|endoftext|> |
<commit_before>a29a5511-ad58-11e7-9044-ac87a332f658<commit_msg>new flies<commit_after>a30d6954-ad58-11e7-be60-ac87a332f658<|endoftext|> |
<commit_before>796b8c54-2d53-11e5-baeb-247703a38240<commit_msg>796c1372-2d53-11e5-baeb-247703a38240<commit_after>796c1372-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>fff7fad4-2e4e-11e5-acd0-28cfe91dbc4b<commit_msg>fffe753a-2e4e-11e5-9dca-28cfe91dbc4b<commit_after>fffe753a-2e4e-11e5-9dca-28cfe91dbc4b<|endoftext|> |
<commit_before>1a432952-585b-11e5-a9c0-6c40088e03e4<commit_msg>1a4cc6a6-585b-11e5-b119-6c40088e03e4<commit_after>1a4cc6a6-585b-11e5-b119-6c40088e03e4<|endoftext|> |
<commit_before>5de73052-5216-11e5-8823-6c40088e03e4<commit_msg>5dee000a-5216-11e5-b586-6c40088e03e4<commit_after>5dee000a-5216-11e5-b586-6c40088e03e4<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.